# Question
Title: What is a simple algorithm for calculating evenly distributed points on an ellipse?
I am looking for a simple algorithm to plot evenly distributed points on an ellipse, given the major and minor axes. This is really easy to do with a circle like so:

```
var numberOfPoints = 8;
var angleIncrement = 360 / numberOfPoints;
var circleRadius = 100;
for (var i = 0; i < numberOfPoints; i++) {
    var p = new Point();
    p.x = (circleRadius * Math.cos((angleIncrement * i) * (Math.PI / 180)));
    p.y = (circleRadius * Math.sin((angleIncrement * i) * (Math.PI / 180)));
}

```

(which creates points that are the same distance apart from their neighboring points) but I can't find or figure out a way to do this on an ellipse. (Solutions in AS3 preferred, but not required.)

# Answer
> 6 votes
Re-parameterize it by arc length and sample uniformly. If you need help doing the math, I would ask it here:
https://math.stackexchange.com/

it was also asked here: https://mathoverflow.net/questions/28070/finding-n-points-that-are-equidistant-around-the-circumference-of-an-ellipse

# Answer
> 6 votes
## Reasonable approximation

As already stated in other answers, there is no exact way to do this. However, it is possible to efficiently approximate a solution.

My formula will only handle the **upper right** quadrant. Various sign changes will need to be applied to handle other quadrants.

Let *d* be your desired arc distance between consecutive points. Suppose the last plotted point is at *(x,y)*.

```
  |
b +-------._  (x,y)
  |         `@-._
  |              `-.
  |                 `.
  |                   \
 -+--------------------+--->
 O|                    a

```

Then the **next point** should be plotted at the following coordinates:

```
x' = x + d / sqrt(1 + b²x² / (a²(a²-x²)))
y' = b sqrt(1 - x'²/a²)

```

## Proof

Let the next point be at *(x+Δx,y+Δy)*. Both points satisfy the ellipse equation:

```
x²/a² + y²/b² = 1
(x+Δx)²/a² + (y+Δy)²/b² = 1

```

Getting rid of *y* in the equations gives:

```
Δy = b (sqrt(1 - (x+Δx)²/a²) - sqrt(1 - x²/a²))

```

We assume *Δx* is small enough, so we replace *f(x+Δx)-f(x)* with *f'(x)Δx* using the linear approximation for *f'*:

```
Δy = -bxΔx / (a² sqrt(1 - x²/a²))

```

If *d* is small enough, then *Δx* and *Δy* are small enough and the arc length is close to the euclidian distance between the points. The following approximation is therefore valid:

```
Δx² + Δy² ~ d²

```

We replace *Δy* in the above and solve for *Δx*:

```
Δx ~ d / sqrt(1 + b²x² / (a²(a²-x²)))

```

## What if *d* is not small enough?

If *d* is too large for the above approximations to be valid, simply replace *d* with *d/N*, for instance *N = 3*, and only plot one point out of *N*.

## Final note

This method has problems at extrema (*x = 0* or *y = 0*), that can be dealt with using additional approximations (*ie.* skipping the last point of the quadrant, whether it's actually plotted or not).

Handling the whole ellipse will probably be more robust by redoing the whole thing using polar coordinates. However, it's some work, and this is an old question, so I'll only do it if there is some interest from the original poster :-)

# Answer
> 0 votes
I kinds of depends exactly what you mean by "evenly". I wrote a post about using ellipses in my game here: http://world-create.blogspot.com/2009/01/ellipse-maths.html

From the post:

```
class Ellipse
{
  Vector3 m_centre;
  Vector3 m_up;
  Vector3 m_along;
  float m_h;
  float m_l;
};

Vector3 Ellipse::PointAt(float t)
{
  float c = cos(t);
  float s = sin(t);

  return m_h * c * m_up + m_l * s * m_along + m_centre;
}

```

You can get points evenly spaced around the ellipse *by angle* by doing:

```
PointAt(0.0f);
PointAt(kHalfPi);
PointAt(kPi);
PointAt(kHalfPi * 3.0f);
PointAt(kTwoPi);

```

But depending on the specifics of your ellipse these values could be bunched up ( if there is a "pointy" end to the ellipse ).

# Answer
> 0 votes
The answer, with full Java code is located on StackOverflow here

## Answered by:

edited Dec 11 '13 at 4:14 John Paul

answered Dec 11 '13 at 3:48 Dave

```
package com.math;

public class CalculatePoints {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    /*
     *
    dp(t) = sqrt( (r1*sin(t))^2 + (r2*cos(t))^2)
    circ = sum(dp(t), t=0..2*Pi step 0.0001)

    n = 20

    nextPoint = 0
    run = 0.0
    for t=0..2*Pi step 0.0001
        if n*run/circ >= nextPoint then
            set point (r1*cos(t), r2*sin(t))
            nextPoint = nextPoint + 1
        next
        run = run + dp(t)
    next
 */

    double r1 = 20.0;
    double r2 = 10.0;

    double theta = 0.0;
    double twoPi = Math.PI*2.0;
    double deltaTheta = 0.0001;
    double numIntegrals = Math.round(twoPi/deltaTheta);
    double circ=0.0;
    double dpt=0.0;

    /* integrate over the elipse to get the circumference */
    for( int i=0; i < numIntegrals; i++ ) {
        theta += i*deltaTheta;
        dpt = computeDpt( r1, r2, theta);
        circ += dpt;
    }
    System.out.println( "circumference = " + circ );

    int n=20;
    int nextPoint = 0;
    double run = 0.0;
    theta = 0.0;

    for( int i=0; i < numIntegrals; i++ ) {
        theta += deltaTheta;
        double subIntegral = n*run/circ;
        if( (int) subIntegral >= nextPoint ) {
            double x = r1 * Math.cos(theta);
            double y = r2 * Math.sin(theta);
            System.out.println( "x=" + Math.round(x) + ", y=" + Math.round(y));
            nextPoint++;
        }
        run += computeDpt(r1, r2, theta);
    }
}

static double computeDpt( double r1, double r2, double theta ) {
    double dp=0.0;

    double dpt_sin = Math.pow(r1*Math.sin(theta), 2.0);
    double dpt_cos = Math.pow( r2*Math.cos(theta), 2.0);
    dp = Math.sqrt(dpt_sin + dpt_cos);

    return dp;
}

}

```

---
Tags: mathematics, actionscript-3
---


# Question
Title: Can I develop a game for Kinect without a Kinect?
I have to make a game in Unity3D using Kinect. The problem is I don't have the Kinect yet. I need to wait until they deliver it to me.

Can I imitate Kinect's movement for debugging my app?

# Answer
> 3 votes
The Unity plugins for the Kinect v2 (midway down the page - "Unity Pro Packages") work just fine when a Kinect is absent. You won't get any input from them obviously, but they also don't crash your game or spam the console with errors (which is more than I can say for some other plugins... ;) )

So you should be able to install the SDK and Unity plugins and start writing your code that interfaces with the Kinect while you wait for the device to arrive.

Testing the code in the meantime will be tricky. The plugins don't contain an emulation feature so far as I'm aware, so you'd have to insert your own.

For example, when making Glimpse, we made it so that the gamepad buttons could emulate the eyes closing, letting both developers test the game even though we had only one Kinect device between us.

(Some older plugins I've used in the past have an emulation built-in, but I've never used that feature so I can't say whether it's worth the grief of dealing with an out-of-date and non-official implementation. I'd lean toward sticking with the Kinect SDK v2.0 because it's so much nicer to use)

How complex your emulation code would have to be depends on what you're trying to emulate. It would be easy to add a bit of debug code to the ColorSourceManager so it always returns a particular texture, or the output of a webcam. Emulating skeletal movement would be trickier.

If you're interested in pursuing emulation and need some help, I'd recommend creating a new question, describing the exact use case you're trying to emulate and how. (eg. I'm trying to emulate a skeleton standing 1.5m away from the kinect, which moves its right hand in the direction I move my mouse)

# Answer
> 5 votes
Can you? Yes. Should you? No.

You won't be able to accurately test without the correct hardware. If you have it coming, you should just wait so you don't make yourself do extra work.

---
Tags: unity, debugging, kinect
---


title: Hide some objects from the camera (fog)

text:
# Question
Title: Hide some objects from the camera (fog)
I'm trying to implement a visibility representation in a 2D game ( no plains, no quads - plain 2D ) In the examples below I have calculated what the player can see using raytracing and added all the colliding points as vertices to a polygon 2D collider. What is within the polygon is in view.

I want everything outside this visible area to be darker / faded out / fogged out, so that it is not visible / as visible as what is in the view. Prefably I would want to choose what objects are included in this darkening, so that static enviroment is not affected but enemy players are.

Simply deactivating the object's renderers is not an option. I also though about overlaying a texture and using a cutout alpha mask, but that would not translate well considering that the visible polygon is updated every frame and the mask has to be premade(?).

# Answer
> 2 votes
> I also though about overlaying a texture and using a cutout alpha mask, but that would not translate well considering that the visible polygon is updated every frame and the mask has to be premade(?).

I'd consider to dynamically build a mesh with the calculated polygons and draw it before everything else. It works occluding the rest of the scene behind (either fully opaque or semi-transparent depending on you requirements).

This way you can continuously update the mesh geometry depending on how visibility changes.

Of course some CPU work is required to rebuild the mesh on every visibility change, but from the screenshots above the vertices count seems not huge (I'll instead pay attention on using tons of raycast each fram to build it).

# Answer
> 0 votes
From your question, I understand you need to simulate object occlusion: in real life (as well as in any 3D videogame) you just can't see an object hiding behind another bigger object. I think of an easy way to accomplish this:

* Use raytracing to detect which areas the player can or can't see from current position (that's what you did in figure 2) to simulate "distance fog";
* Use simple line collision detection from player object towards any 'actor' (enemy, object, anything you need to hide if not "seen" from the player) to test if player can actually see them or not; if there's no collision along this line (thus there is no solid geometry between player and current actor) then render the actor's graphics, else don't.

This way actors will be rendered only if their origin point lies inside the 'visible' area.

Also, if you want to limit player's sight, you can check both line collision and distance from player to make sure engine doesn't render actors beyond the circumference representing player's 'field of view'.

---
Tags: unity, 2d, lighting, shadows
---


title: Where is Light in Game view

text:
# Question
Title: Where is Light in Game view
Very Basic Question.when i run the the game the game Mode is Too dark as shown below in the picture. please suggest me some Setting how to globally switch on built in light while Running the game in game mode.

Thanks.

# Answer
> 0 votes
The word you're looking for is "ambient light," and is the common term for most game engines.

You can find more information about Unity's ambient light, fog, and other global scene settings here: Unity Manual - Render Settings

---
Tags: unity, lighting
---


# Question
Title: Handling an item database with procedurally generated items?
Let's say you have an item database which has every item in your game. This works fine for regular items like a Health Potion, a normal Iron Sword etc, because these items have ItemID's so we can get an exact copy of this item. But what if we have an Iron Sword with an enchantment: '+5 Fire Damage'? (or whatever)

If you were to save that item to a player's inventory, exit the game and load the game, the item will load as a regular Iron Sword, because it still has that ID.

**Specifically,** how would you save that item to a file? I'm using Unity, so to save the Player's inventory, I use:

```
PlayerPrefs.SetInt("Inventory " + i, inventory[i].ItemId );

```

Would you create a custom item ID for every item with enchantments or is there a better way around this?

# Answer
From what you wrote I understand there is an existing Enum that represents all items.

i.e:

```
small_health_potion = 1
large_two_handed_sword = 2
// etc

```

Now, considering you already have that system in place, you wish to extend it for items that are variations of these items like enchanted versions and perhaps cursed versions and what not.

The issue is that we don't know exactly what kinds of enchantments are available in this game. In your specific scenario, I would list the enchantments of each item, after it's Enum id.

for instance, if up until now:

```
helmet = 2
shield = 4
armor = 7
sword = 8

```

and the inventory would look like this:

2,4,7,8

Then I would add a list of enhancements:

```
armor+5def = 11
weapon+8atk = 37
wepon+7speed = 49

```

and simply do this

2,4,7(11),8(37,49)

Inside a db, you can save the inventories contents as a varchar.

You can also store an enchanted item by storing a pair of item base type and enchantment type.
> 1 votes

---
Tags: unity, procedural-generation, databases, inventory
---


title: Acute corner - Collision Detection

text:
# Question
Title: Acute corner - Collision Detection
So I have set up a Swept test for AABB vs Line Collision that works fine, now the problem is that I have to deal with acute corners, where this happens:

As you can see the AABB just falls through the bottom Line, when it should stop.

I have been trying to do this for a month now, and I can't find any solution at all.

Why does this happen and how do I fix it?

# Answer
> 5 votes
(only addressing the fall-through-the-floor part, not the go-across-ceiling part which seems something different) If I understand your algorithm correctly, you do the following:

* Take your box current position t=0
* Take the target position t=1
* For all lines, find the collision time, and take the smallest one, tc.
* If tc \< 1, move the box ahead by tc times displacement vector.

What happens is that through numerical error when you move your box one of the sides moves slightly aside and passes a line (typically the ground). From there it doesn't hit anymore and can fall through.

My advice would be to keep a safety margin. Don't let your object move by col.time, in :

b.pos.add(vec.mul(b.vel, delta * col.time * facTime));

Move by (col.time - 0.01). Adjust 0.01 as needed. Don't move if col.time \< 0.01.

I'm used to doing this kind of stuff in C++, not .js, so I'm not quite ready to test it in your framework, but I'll try later and check that it works. If you can try it, just le me know whether it helps.

I'm not sure how your velocity changes as you near the object, there might still be an issue if velocity approaches zero.

---
Tags: collision-detection
---


title: How to unsmooth polygons in 3dsMax

text:
# Question
Title: How to unsmooth polygons in 3dsMax
i am creating a game using a "Low Poly Art Style". Meaning there is an effect of polygons on the model. Whilst modelling a tree, a portion somehow became smooth and i continued to model not knowing this. What i am wondering is, is there a way to unsmooth these polygons to look similar to the rest of the model. EDIT... The smoothed are is on the tree trunk in the middle.

Below is an image of the model in question.

Thanks is advance guys...

# Answer
> 1 votes
In face sub-object mode, select all your faces and then scroll down the inspector to the "Polygon: Smoothing Groups" section and click "Clear All"

(Can't embed the image from my current network, but it's step 2 from this tutorial)

---
Tags: 3dsmax, low-poly
---


# Question
Title: How does the Graphic Raycaster component work in Unity?
I'm making a small game for the first time and enjoying it thus far. The only thing that keeps bothering me is that I can't find a human explanation of what the graphic raycaster does. What's the blocking mask, what are the blocking objects etc? Should I mask the things I want clicked or the things I don't want clicked?

As an example I have the following screenshot.

The overlayCanvas has the pinkish square on the top in it and the button "Button" on the pink square. Nonetheless, the whole bloody canvas is clickable instead of just the button and the pink square. Which means that all interactions are seized because the canvas is on a "topLayer" which has its own camera.

The Square+button in the overlayCanvas are on "topLayer" as well. But I just want the button and the pink square (and what's in it) clickable because the game is relying on clicks on the background image.

# Answer
**What is a raycast? What are blocking objects and blocking mask?**
A *ray* is a mathematical device that starts at an origin point and continues on in a specific direction forever. With a *raycast* you're casting a ray, cast being used like the word throw. It's like if you threw a rock and it continued on in that direction forever, it wouldn't stop until it hit something. You're interested as to whether it hit an object and what that object was.
*Blocking objects* would be the objects that you specifically define your raycast to be able to hit.
A *blocking mask* allows you to, instead of passing tons of blocking objects, define the layers in Unity you want your raycast to be able to hit in the form of a bitmask. The bitmask is coded so each bit represents a layer. If your bitmask was `0000000000000101` represented as `(1 | 1<<2)` or `5` then your raycast will only be blocked by layers 1 and 3 and can therefore only hit objects in those layers.

If we look at Unity's Raycasters documentation, we can see there are three different kind of raycasters

> **Graphic Raycaster** \- Used for UI elements, lives on a Canvas and searches within the canvas.
>
> **Physics 2D Raycaster** \- Used for 2D physics elements.
>
> **Physics Raycaster** \- Used for 3D physics elements.

Accordingly to Andy Borrell in Oculus blog

> the GraphicRaycaster (for Canvases) and the PhysicsRaycaster (for physics objects).

The one we're interested here is Graphic Raycaster and accordingly to Unity

> The Graphic Raycaster is used to raycast against a Canvas. The Raycaster looks at all Graphics on the canvas and determines if any of them have been hit.

**Graphic Raycaster and Unity's Event System**
Unity's GraphicRaycaster was introduced in version 4.6 along with a bunch of other stuff that's all part of Unity's new events system. For that reason, the `GraphicRaycaster` was originally meant to be used through this system (same with the Physics Raycaster and its 2D counterpart, which are all different from `Physics.Raycast` which is meant for generic raycasts not necessarily originating from UI events). There are two options for the use of this component in Unity.

If you want to go the full on Unity way using Unity's EventSystem, you're going to need to place one in your scene. You can find this under `GameObject > UI > Event System`. From here you have a few methods of capturing the event and using it to your will.

* Use event triggers (found in `Component > Event > Event Trigger` and use the editor to create all your connections.
* If you would like to avoid the editor, your `MonoBehaviour` can implement a given interface depending on the event your want to capture. These are the `UnityEngine.EventSystems.I...Handler` interfaces like the `IBeginDragHandler` interface

This video shows the specific implementations of each method.
For more on the event system, triggers, and how they all work together this video might help as well.

You can also use it directly by calling the `GraphicRaycaster`s Raycast function itself instead of creating code as a response to an event. For this we need the following snippet of code where we create a `PointerEventData` object to send to the `Raycast` function.

```
//Code to be place in a MonoBehaviour with a GraphicRaycaster component
GraphicRaycaster gr = this.GetComponent<GraphicRaycaster>();
//Create the PointerEventData with null for the EventSystem
PointerEventData ped = new PointerEventData(null);
//Set required parameters, in this case, mouse position
ped.position = Input.mousePosition;
//Create list to receive all results
List<RaycastResult> results = new List<RaycastResult>();
//Raycast it
gr.Raycast(ped, results);

```

`results` will now contain all of your hit canvas objects. This is pretty much the same way that `PointerInputModule` does raycasting with EventSystem.RaycastAll in Unity (except with more caching).

**Your specific problem with the button.**
Try setting the OverlayCanvas to not be on a layer. I think the fact that it's on a layer in the first place might be breaking things because it looks like the default it for a Graphic Caster is to be blocked by "Everything" which I'm guessing your BGCanvas has it's blocking mask set to.
> 23 votes

---
Tags: unity, raycasting, unity-ui
---


title: Unity and Chartboost loading problems

text:
# Question
Title: Unity and Chartboost loading problems
I implemented chartboost in my ios game and locally it wors great.

I can receive ads.

Now my game is online but in the google analytics I get only error messages from the game, meaning the chartboost ads fail to load.

Here: https://www.dropbox.com/s/cft98lk27mt7p3s/cb.jpg?dl=0

The iage show google analytics registering only failed loads and there is no single successfull ad load?

What could be the problem here?

# Answer
> 1 votes
Try using a program like Charles Web Proxy to see what network calls your game makes to Chartboost. Your game should be sending calls at every bootup and when it caches or shows an interstitial or MoreApps page. If you're not seeing these calls at bootup and when you expect to show a Chartboost ad, look through the integration documentation to be sure you did everything right.

If those steps don't work, you may need to call Chartboosts support line and have them walk you through additional steps.

---
Tags: unity, ios, advertisements
---


title: PlayFab Custom Server Integration

text:
# Question
Title: PlayFab Custom Server Integration
I want to use PlayFab to host and manage my server instances but I'm unclear on how to implement the requirements they listed here. My server SDK is in .Net and I'm hoping I can fulfill all the requirements with plugins written in C#. How can I and make parameters available in the command line input? Am I supposed to return information by printing on the console?

# Answer
Their service would call your server executable (if it was called server.exe) like below

> server.exe -game\_id= -game\_build\_version= -game\_mode= -server\_host\_domain= -server\_host\_port= -server\_host\_region= -playfab\_api\_endpoint= -title\_secret\_key= -custom\_data= -log\_file\_path= -output\_files\_directory\_path= -batchmode

When they say,

> In designing your server, the following parameters will be available as part of your command line input:
> ... command switches ...

They're actually letting you know that these are the command line switches that will be provided to your server executable when their service calls it to start a new server instance. You would be responsible for reading all these switches in your server program and then parsing their value to do what they describe in their documentation.

For example,

> log\_file\_path - a string value for the directory where the server log file must be written, so that it can be collected by the PlayFab service upon completion of the instance

You would have to read that switch into a variable and write your logs to that file otherwise their service won't be able to handle the logs you generate properly.
> 1 votes

---
Tags: networking, server
---


# Question
Title: Drawing a continuous line with onTouchMoved callback
i'm trying to draw a continues spline on every onTouchMoved call, the functionality is supposed to be similar to the line drawing used in the iOS game - flight control.

i'm using it in the following manner:

constructor init:

```
conPointsArray = new PointArray();
conPointsArray->initWithCapacity(DEF_ARRAY_SIZE);
lineDrawer = DrawNode::create();

```

the onTouchMoved callback usage:

```
void line::onTouchMoved(cocos2d::Touch *Touch, cocos2d::Event *Event)
{
conPointsArray->addControlPoint(Touch->getLocation());
lineDrawer->drawCardinalSpline((conPointsArray), 0.5f, 100, Color4F::BLUE);
CCLOG("on touch moved x: %f y %f", Touch->getLocation().x, Touch->getLocation().y);
}

```

But the app is always crashing in a certain openGL function.

I assumed the reason for it is because the array is constantly changing and openGL is having trouble with it (and the fact i'm always sending the same array which is a bad idea, but just to see how things work), so i moved the drawing call to onTouchEnded, And indeed, The line was drawn, but only (as expected) after the onTouch action has ended.

What is the solution/best practice for this issue?

Cheers.

# Answer
I created an *drawing app for kids* and I think the `RenderTexture` is the best solution for such applications.

You can use `visit()` method of `Sprite` and draw(=`visit`) a point ( probably a circle sprite) on your canvas(=`RenderTexture`) while touch is moving(=`onTouchMoved`).

Don't forget to call `RenderTexture->begin()`/`end()` when using `visit` function.

This if for cocos2dx v2 but not so different with v3:

```
void PaintingScene::ccTouchesMoved(CCSet* touches, CCEvent* event)
{
    CCTouch *touch = (CCTouch*)touches->anyObject();
    brush->setPosition(touch->getLocation());
    RT_currentSession->begin(); //RT_currentSession : CCRenderTexture
    brush->setVisible(true);
    brush->visit();
    brush->setVisible(false);
    RT_currentSession->end();
}

```
> 1 votes

# Answer
Re:

> "It Works great, Thank you. There is one little issue i'm trying to solve, and its how to get a full line in case we have quick movements (saw some examples online, non of them work but using an array of brushes and drawing them, which kills the CPU), it's in the example i gave in the comments above. How did u solve it?"

I use a different language and software, so the code below is more psuedocode, than code. You will need to properly type the position parameter of doIt, etc. The idea should be "gettable"; if not, let me know. initialPoint is set to true in the TouchDown callback (or possibly TouchUp).

Consider:

```
void doIt(position)
{
  brush->setPosition(position);
  brush->setVisible(true);
  brush->visit();
  brush->setVisible(false);
}
void PaintingScene::ccTouchesMoved(CCSet* touches, CCEvent* event)
{
   RT_currentSession->begin(); //RT_currentSession : CCRenderTexture
   touchLocation = touch->getLocation();
   if (initialPoint)
   {
     previousTouchLocation = touchLocation;
     initialPoint = false;
   }
   dragDistance = distance(touchLocation - previousTouchLocation);
   for (i = 0; i <= dragDistance; i++)
   {
     //doIt(previousTouchLocation + ((touchLocation - previousTouchLocation) * (float)i / dragDistance)));
     //doIt(lerp(previousTouchLocation, touchLocation, (float)i / dragDistance));
     doIt(lerp(previousTouchLocation, touchLocation, i, dragDistance));
     //Linearly interpolate between previousTouchLocation and touchLocation
     //turning on each pixel along the way
   }
   RT_currentSession->end();
   previousTouchLocation = touchLocation;
}

```
> 0 votes

---
Tags: c++, cocos2d-iphone, cocos2d-x
---


title: How to get started with making textures

text:
# Question
Title: How to get started with making textures
I have Photoshop CS6 (I haven't installed it yet), and I was wondering if there was a good book or tutorial on how to get started on making my own video game textures.

**SIDENOTE:** I saw a question on this, but it was outdated and from 2011.

# Answer
This question is a bit broad and there really isn't a clear cut path in making textures as there are many different uses for textures (UI textures, UV model textures, seamless textures, etc) all depending on what you're making it for. There are a few common denominators though so I'll go over those.

**Determine Texture Attributes**
Based on how your texture is being used you'll need decide a few attributes at the start including:

* Size - Pick a size based on how closely it will be inspected by the player and the style of the game it's in. Usually has width and height as a power of two, also square (this is a requirement that depends on your engine and implementation of OpenGL)
* Seamlessness - Determine if you need your texture to be seamless for tiling over large faces if it'll be used in things like level design.
* Supporting Files - Determine if it needs a normal map, specular map, other metadata defined to be displayed properly.

**Make the albedo**
Most textures start with an albedo. This is just a fancy word for the image that defines your texture. There's three ways you can get an albedo and it depends on your use case.

* Find it on the internet - There's specific websites that have textures that you can freely use and download but be weary as images do carry copyright. You can also take an albedo that close to what you want and make it what you want using some image processing.
* Make it yourself - You can draw a texture based on your needs
* Take it yourself - You can take your favorite camera and go outside and take some photos of walls, floors, whatever else you'd like to use. If you plan on doing this there's lots of advice on the internet for taking good pictures for easy conversion later (like taking pictures when it's overcast as there isn't such harsh sun shadows).

**Seamlessness**
Some uses require your texture be seamless. This will ensure that when you apply the texture to a face and it tiles, it does so without any visual disconnect between where one part of the texture ends and the other begins to repeat.
You can get plugins for this, external applications, and do it yourself with things like the clone brush. There are also ways to preview your texture to see if it's tiling correctly before you actually use it.

**Including the supporting files**
This really depends on the application of the texture.

* Would it provide benefit with a normal map? You can generate one with a plugin or external application.
* Is it going to be reflective and only part of it should be reflecting? Make a specular map.
* Does the game need to determine what shader will be used to render your texture or other data? Write the metadata file.

There's a lot more that I could put here but I just put down some of the more common things.

**Determine your output format**
This is very application dependent (some engines a specific format you must useh when you export) but it's best to go with something lossless so if you go back to edit your texture it doesn't have artifacts. If you do need to use a lossy format, make sure to save a lossless copy.
> 1 votes

---
Tags: textures, books
---


# Question
Title: Rotating an object towards a target on the Y axis
I am attempting to rotate a 3D object on its Y-axis towards a target it is looking at. I have always struggled with rotations so I would like to try to avoid using Unity's built in functions, i.e transform.LookAt() in order to get used to using rotations. Gotta master the basics first, right?

```
Vector3 currentOrientation = transform.rotation.eulerAngles;
Vector3 directionVector3 = transform.position - target.transform.position;
float angle = Mathf.Atan2(directionVector3.z, directionVector3.x) * Mathf.Rad2Deg;
currentOrientation.y =angle;
transform.rotation = Quaternion.Euler(currentOrientation);

```

However when I do run this, the character is not looking in the correct direction at all!

Here is a screen shot with the character's parameters

The target object belongs in a hierarchy, where it's position in world space is (150,0,500)

Does atan2 somehow behave differently in 3D space vs 2D space? I ask because I've made 2D games where I would just use atan2(y,x) for a character's rotation.

# Answer
> 2 votes
**Edit:** Okay, with a little bit of testing I'm prepared to revise my answer.

Going from 2D to 3D, you must now consider that "Y" isn't always going to be up. When you try to treat 3D as 2D, you can actually make things a little more complicated. So I'll do it both ways and you can decide which way works better for you.

## 2D in 3D

As usual, we want the direction vector from our current position to the target.

```
var heading = target.transform.position - transform.position;

```

We're only interested in the planar rotation (yaw) so we'll flatten and normalize.

```
var heading2d = new Vector2(heading.x, heading.z).normalized;

```

Now the tricky bit - I'm not sure why, but when converting radians to degrees for Unity, we need to multiply the negative constant and add a quarter turn. *This seems to be where everything went wrong.*

```
var angle = Mathf.Atan2(heading2d.y, heading2d.x) * -Mathf.Rad2Deg + 90;

```

Finally, apply the rotation according to the axis:

```
transform.rotation = Quaternion.AngleAxis(angle, Vector3.up);

```

which is equivalent to (probably, Unity might have platform specific versions)

```
Quaternion AxisAngle(float angle, Vector3 axis)
{
    var sinA = Mathf.Sin(angle *0.5f);
    var cosA = Mathf.Cos(angle*0.5f);
    return new Quaternion(axis.x * sinA,
                          axis.y * sinA,
                          axis.z * sinA,
                          cosA);
}

```

# Answer
> 0 votes
I come from XNA, so I've had to psuedocode in places. Here is the same math in a different shape. The math was expanded for clarity and can be optimized.

```
Vector3 directionVector = target.transform.position - transform.position;
directionVector.Y = 0;
directionVector = Vector3.Normalize(directionVector);

//Need to flatten transform.Forward as well, if object can pitch
float directionDot = Vector3.Dot(transform.Forward, directionVector);
//directionDot ranges from -1 (opposite) to +1 (same)
directionDot /= -1; //now 1 (opposite) to -1 (same)
directionDot += 1; //now 2 (opposite) to 0 (same)
directionDot /= 2; //now 1 (opposite) to 0 (same)
directionDot *= MathHelper.ToRadians(180); //now Pi (opposite) to 0 (same)

bool clockWise = (Vector3.Dot(transform.Left, directionVector) > 0);
// >0 means target position is more like transform.Left
//<=0 means target position is more like transform.Right
if (!clockWise) directionDot *= -1;

if (Math.Abs(directionDot) > 0.00) //"Close-enough-for-now" factor
{
  //We need to rotate by directionDot instantly, or by storing it and lerping in Update()
  transform *= Matrix.CreateRotationY(directionDot);
}

```

---
Tags: unity, mathematics
---


# Question
Title: How can i Zoom and Drag The Multiple Image in RelativeLayout
i try but it did not see the effect for the zoom and Rotate the image ..Here is my code....

```
ima1 = (ImageView) findViewById(R.id.image);
    ima1.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            int x_cord = (int) event.getRawX();
            int y_cord = (int) event.getRawY();

            layoutParams1 = (RelativeLayout.LayoutParams) ima1
                    .getLayoutParams();
            switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                savedMatrix.set(matrix);
                start.set(event.getX(), event.getY());
                mode = DRAG;
                lastEvent = null;
                break;

            case MotionEvent.ACTION_POINTER_DOWN:
                oldDist = spacing(event);
                if (oldDist > 10f) {
                    savedMatrix.set(matrix);
                    midPoint(mid, event);
                    mode = ZOOM;
                }
                lastEvent = new float[4];
                lastEvent[0] = event.getX(0);
                lastEvent[1] = event.getX(1);
                lastEvent[2] = event.getY(0);
                lastEvent[3] = event.getY(1);
                d = rotation(event);
                break;

            case MotionEvent.ACTION_POINTER_UP:
                mode = NONE;
                lastEvent = null;
                break;
            case MotionEvent.ACTION_MOVE:
                if (mode == ZOOM) {
                    float newDist = spacing(event);
                    if (newDist > 10f) {
                        matrix.set(savedMatrix);
                        float scale = (newDist / oldDist);
                        matrix.postScale(scale, scale, mid.x, mid.y);
                        layoutParams1.leftMargin = x_cord;
                        layoutParams1.topMargin = y_cord;
                        ima1.setLayoutParams(layoutParams1);
                        System.out.println("=== Mode Zoom = " + mode + " == " + scale ) ;
                    }

                } else if (mode == DRAG) {

                    System.out.println("==== DRAG  " + x_cord + " - "
                            + y_cord);
                    if (x_cord > windowwidth) {
                        x_cord = windowwidth;
                    }
                    if (y_cord > windowheight) {
                        y_cord = windowheight;
                    }
                    layoutParams1.leftMargin = x_cord;
                    layoutParams1.topMargin = y_cord;
                    ima1.setLayoutParams(layoutParams1);

                } else if (lastEvent != null
                        && event.getPointerCount() == 2) {
                    /*newRot = rotation(event);
                    float r = newRot - d;
                    float[] values = new float[9];
                    matrix.getValues(values);
                    float tx = values[2];
                    float ty = values[5];
                    float sx = values[0];
                    matrix.postRotate(r, mid.x, mid.y);
                    System.out.println("=== Mode Rotate = " + mode);*/
                }
                break;

            }
            ima1.setImageMatrix(matrix);
            return true;
        }
    });
}

```

my Layout XML file is ...

```
<ImageView
    android:id="@+id/image"
    android:layout_width="50sp"
    android:layout_height="50sp"
    android:clickable="true"
    android:src="@drawable/ic_launcher" >

</ImageView>

<ImageView
    android:id="@+id/image1"
    android:layout_width="50sp"
    android:layout_height="50sp"
    android:layout_x="118dip"
    android:layout_y="30dip"
    android:src="@drawable/ic_launcher" >
</ImageView>

```

# Answer
> 1 votes
```
//Try below code custom view with having facility to add zoomview

    package <your package>;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;

/**
 * Zooming view.
 */
public class ZoomView extends FrameLayout {

    public ZoomView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    public ZoomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public ZoomView(final Context context) {
        super(context);
    }

    /**
     * Zooming view listener interface.
     *
     * @author karooolek
     *
     */
    public interface ZoomViewListener {

        void onZoomStarted(float zoom, float zoomx, float zoomy);

        void onZooming(float zoom, float zoomx, float zoomy);

        void onZoomEnded(float zoom, float zoomx, float zoomy);
    }

    // zooming
    float zoom = 1.0f;
    float maxZoom = 2.0f;
    float smoothZoom = 1.0f;
    float zoomX, zoomY;
    float smoothZoomX, smoothZoomY;
    private boolean scrolling; // NOPMD by karooolek on 29.06.11 11:45

    // minimap variables
    private boolean showMinimap = false;
    private int miniMapColor = Color.WHITE;
    private int miniMapHeight = -1;
    private String miniMapCaption;
    private float miniMapCaptionSize = 10.0f;
    private int miniMapCaptionColor = Color.WHITE;

    // touching variables
    private long lastTapTime;
    private float touchStartX, touchStartY;
    private float touchLastX, touchLastY;
    private float startd;
    private boolean pinching;
    private float lastd;
    private float lastdx1, lastdy1;
    private float lastdx2, lastdy2;

    // drawing
    private final Matrix m = new Matrix();
    private final Paint p = new Paint();

    // listener
    ZoomViewListener listener;

    private Bitmap ch;

    public float getZoom() {
        return zoom;
    }

    public float getMaxZoom() {
        return maxZoom;
    }

    public void setMaxZoom(final float maxZoom) {
        if (maxZoom < 1.0f) {
            return;
        }

        this.maxZoom = maxZoom;
    }

    public void setMiniMapEnabled(final boolean showMiniMap) {
        this.showMinimap = showMiniMap;
    }

    public boolean isMiniMapEnabled() {
        return showMinimap;
    }

    public void setMiniMapHeight(final int miniMapHeight) {
        if (miniMapHeight < 0) {
            return;
        }
        this.miniMapHeight = miniMapHeight;
    }

    public int getMiniMapHeight() {
        return miniMapHeight;
    }

    public void setMiniMapColor(final int color) {
        miniMapColor = color;
    }

    public int getMiniMapColor() {
        return miniMapColor;
    }

    public String getMiniMapCaption() {
        return miniMapCaption;
    }

    public void setMiniMapCaption(final String miniMapCaption) {
        this.miniMapCaption = miniMapCaption;
    }

    public float getMiniMapCaptionSize() {
        return miniMapCaptionSize;
    }

    public void setMiniMapCaptionSize(final float size) {
        miniMapCaptionSize = size;
    }

    public int getMiniMapCaptionColor() {
        return miniMapCaptionColor;
    }

    public void setMiniMapCaptionColor(final int color) {
        miniMapCaptionColor = color;
    }

    public void zoomTo(final float zoom, final float x, final float y) {
        this.zoom = Math.min(zoom, maxZoom);
        zoomX = x;
        zoomY = y;
        smoothZoomTo(this.zoom, x, y);
    }

    public void smoothZoomTo(final float zoom, final float x, final float y) {
        smoothZoom = clamp(1.0f, zoom, maxZoom);
        smoothZoomX = x;
        smoothZoomY = y;
        if (listener != null) {
            listener.onZoomStarted(smoothZoom, x, y);
        }
    }

    public ZoomViewListener getListener() {
        return listener;
    }

    public void setListner(final ZoomViewListener listener) {
        this.listener = listener;
    }

    public float getZoomFocusX() {
        return zoomX * zoom;
    }

    public float getZoomFocusY() {
        return zoomY * zoom;
    }

    @Override
    public boolean dispatchTouchEvent(final MotionEvent ev) {
        // single touch
        if (ev.getPointerCount() == 1) {
            processSingleTouchEvent(ev);
        }

        // // double touch
        if (ev.getPointerCount() == 2) {
            processDoubleTouchEvent(ev);
        }

        // redraw
        getRootView().invalidate();
        invalidate();

        return true;
    }

    private void processSingleTouchEvent(final MotionEvent ev) {

        final float x = ev.getX();
        final float y = ev.getY();

        final float w = miniMapHeight * (float) getWidth() / getHeight();
        final float h = miniMapHeight;
        final boolean touchingMiniMap = x >= 10.0f && x <= 10.0f + w
                && y >= 10.0f && y <= 10.0f + h;

        if (showMinimap && smoothZoom > 1.0f && touchingMiniMap) {
            processSingleTouchOnMinimap(ev);
        } else {
            processSingleTouchOutsideMinimap(ev);
        }
    }

    private void processSingleTouchOnMinimap(final MotionEvent ev) {
        final float x = ev.getX();
        final float y = ev.getY();

        final float w = miniMapHeight * (float) getWidth() / getHeight();
        final float h = miniMapHeight;
        final float zx = (x - 10.0f) / w * getWidth();
        final float zy = (y - 10.0f) / h * getHeight();
        smoothZoomTo(smoothZoom, zx, zy);
    }

    private void processSingleTouchOutsideMinimap(final MotionEvent ev) {
        final float x = ev.getX();
        final float y = ev.getY();
        float lx = x - touchStartX;
        float ly = y - touchStartY;
        final float l = (float) Math.hypot(lx, ly);
        float dx = x - touchLastX;
        float dy = y - touchLastY;
        touchLastX = x;
        touchLastY = y;

        switch (ev.getAction()) {
        case MotionEvent.ACTION_DOWN:
            touchStartX = x;
            touchStartY = y;
            touchLastX = x;
            touchLastY = y;
            dx = 0;
            dy = 0;
            lx = 0;
            ly = 0;
            scrolling = false;
            break;

        case MotionEvent.ACTION_MOVE:
            if (scrolling || (smoothZoom > 1.0f && l > 30.0f)) {
                if (!scrolling) {
                    scrolling = true;
                    ev.setAction(MotionEvent.ACTION_CANCEL);
                    super.dispatchTouchEvent(ev);
                }
                smoothZoomX -= dx / zoom;
                smoothZoomY -= dy / zoom;
                return;
            }
            break;

        case MotionEvent.ACTION_OUTSIDE:
        case MotionEvent.ACTION_UP:

            // tap
            if (l < 30.0f) {
                // check double tap
                if (System.currentTimeMillis() - lastTapTime < 500) {
                    if (smoothZoom == 1.0f) {
                        smoothZoomTo(maxZoom, x, y);
                    } else {
                        smoothZoomTo(1.0f, getWidth() / 2.0f,
                                getHeight() / 2.0f);
                    }
                    lastTapTime = 0;
                    ev.setAction(MotionEvent.ACTION_CANCEL);
                    super.dispatchTouchEvent(ev);
                    return;
                }

                lastTapTime = System.currentTimeMillis();

                performClick();
            }
            break;

        default:
            break;
        }

        ev.setLocation(zoomX + (x - 0.5f * getWidth()) / zoom, zoomY
                + (y - 0.5f * getHeight()) / zoom);

        ev.getX();
        ev.getY();

        super.dispatchTouchEvent(ev);
    }

    private void processDoubleTouchEvent(final MotionEvent ev) {
        final float x1 = ev.getX(0);
        final float dx1 = x1 - lastdx1;
        lastdx1 = x1;
        final float y1 = ev.getY(0);
        final float dy1 = y1 - lastdy1;
        lastdy1 = y1;
        final float x2 = ev.getX(1);
        final float dx2 = x2 - lastdx2;
        lastdx2 = x2;
        final float y2 = ev.getY(1);
        final float dy2 = y2 - lastdy2;
        lastdy2 = y2;

        // pointers distance
        final float d = (float) Math.hypot(x2 - x1, y2 - y1);
        final float dd = d - lastd;
        lastd = d;
        final float ld = Math.abs(d - startd);

        Math.atan2(y2 - y1, x2 - x1);
        switch (ev.getAction()) {
        case MotionEvent.ACTION_DOWN:
            startd = d;
            pinching = false;
            break;

        case MotionEvent.ACTION_MOVE:
            if (pinching || ld > 30.0f) {
                pinching = true;
                final float dxk = 0.5f * (dx1 + dx2);
                final float dyk = 0.5f * (dy1 + dy2);
                smoothZoomTo(Math.max(1.0f, zoom * d / (d - dd)), zoomX - dxk
                        / zoom, zoomY - dyk / zoom);
            }

            break;

        case MotionEvent.ACTION_UP:
        default:
            pinching = false;
            break;
        }

        ev.setAction(MotionEvent.ACTION_CANCEL);
        super.dispatchTouchEvent(ev);
    }

    private float clamp(final float min, final float value, final float max) {
        return Math.max(min, Math.min(value, max));
    }

    private float lerp(final float a, final float b, final float k) {
        return a + (b - a) * k;
    }

    private float bias(final float a, final float b, final float k) {
        return Math.abs(b - a) >= k ? a + k * Math.signum(b - a) : b;
    }

    @Override
    protected void dispatchDraw(final Canvas canvas) {

        // do zoom
        zoom = lerp(bias(zoom, smoothZoom, 0.05f), smoothZoom, 0.2f);
        smoothZoomX = clamp(0.5f * getWidth() / smoothZoom, smoothZoomX,
                getWidth() - 0.5f * getWidth() / smoothZoom);
        smoothZoomY = clamp(0.5f * getHeight() / smoothZoom, smoothZoomY,
                getHeight() - 0.5f * getHeight() / smoothZoom);

        zoomX = lerp(bias(zoomX, smoothZoomX, 0.1f), smoothZoomX, 0.35f);
        zoomY = lerp(bias(zoomY, smoothZoomY, 0.1f), smoothZoomY, 0.35f);
        if (zoom != smoothZoom && listener != null) {
            listener.onZooming(zoom, zoomX, zoomY);
        }

        final boolean animating = Math.abs(zoom - smoothZoom) > 0.0000001f
                || Math.abs(zoomX - smoothZoomX) > 0.0000001f
                || Math.abs(zoomY - smoothZoomY) > 0.0000001f;

        // nothing to draw
        if (getChildCount() == 0) {
            return;
        }

        // prepare matrix
        m.setTranslate(0.5f * getWidth(), 0.5f * getHeight());
        m.preScale(zoom, zoom);
        m.preTranslate(
                -clamp(0.5f * getWidth() / zoom, zoomX, getWidth() - 0.5f
                        * getWidth() / zoom),
                -clamp(0.5f * getHeight() / zoom, zoomY, getHeight() - 0.5f
                        * getHeight() / zoom));

        // get view
        final View v = getChildAt(0);
        m.preTranslate(v.getLeft(), v.getTop());

        // get drawing cache if available
        if (animating && ch == null && isAnimationCacheEnabled()) {
            v.setDrawingCacheEnabled(true);
            ch = v.getDrawingCache();
        }

        // draw using cache while animating
        if (animating && isAnimationCacheEnabled() && ch != null) {
            p.setColor(0xffffffff);
            canvas.drawBitmap(ch, m, p);
        } else { // zoomed or cache unavailable
            ch = null;
            canvas.save();
            canvas.concat(m);
            v.draw(canvas);
            canvas.restore();
        }

        // draw minimap
        if (showMinimap) {
            if (miniMapHeight < 0) {
                miniMapHeight = getHeight() / 4;
            }

            canvas.translate(10.0f, 10.0f);

            p.setColor(0x80000000 | 0x00ffffff & miniMapColor);
            final float w = miniMapHeight * (float) getWidth() / getHeight();
            final float h = miniMapHeight;
            canvas.drawRect(0.0f, 0.0f, w, h, p);

            if (miniMapCaption != null && miniMapCaption.length() > 0) {
                p.setTextSize(miniMapCaptionSize);
                p.setColor(miniMapCaptionColor);
                p.setAntiAlias(true);
                canvas.drawText(miniMapCaption, 10.0f,
                        10.0f + miniMapCaptionSize, p);
                p.setAntiAlias(false);
            }

            p.setColor(0x80000000 | 0x00ffffff & miniMapColor);
            final float dx = w * zoomX / getWidth();
            final float dy = h * zoomY / getHeight();
            canvas.drawRect(dx - 0.5f * w / zoom, dy - 0.5f * h / zoom, dx
                    + 0.5f * w / zoom, dy + 0.5f * h / zoom, p);

            canvas.translate(-10.0f, -10.0f);
        }

        // redraw
        // if (animating) {
        getRootView().invalidate();
        invalidate();
        // }
    }
}

```

then add your zoomable views in above custom view Note: custom view should have only one child thats why added your zoomable views in RelativeLayout

```
 <com.pkg.pie_custom_views.ZoomView
                android:id="@+id/zoomView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_above="@+id/rlBottomTitle"
                android:layout_below="@+id/rlPieTitle"
                android:layout_centerInParent="true" >

<RelativeLayout
                android:id="@+id/zoomView"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
<ImageView
    android:id="@+id/image"
    android:layout_width="50sp"
    android:layout_height="50sp"
    android:clickable="true"
    android:src="@drawable/ic_launcher" >

</ImageView>

<ImageView
    android:id="@+id/image1"
    android:layout_width="50sp"
    android:layout_height="50sp"
    android:layout_x="118dip"
    android:layout_y="30dip"
    android:src="@drawable/ic_launcher" >
</ImageView>
</RealtiveLayout>

            </com.pkg.pie_custom_views.ZoomView>

```

Feel free to ask if you have any problem to implement it

---
Tags: android
---


title: How to implement simple shadows on XNA?

text:
# Question
Title: How to implement simple shadows on XNA?
*UPDATE: See photos below the description*

I try desperately to implement shadows on my XNA games. My game is a style of games like Voxel (minecraft).

The problem is that I do not find support / help or example explaining how to add shadows on cubes (vertices and indices) with (**BasicEffect**). I just find examples to add shadows with a (**HLSL** Effect) or a "Model".

Is it possible to create shadows with the class "BasicEffect" on vertices cube ? I already try with "**Matrix.CreateShadow**(...)" but no success .

I really hope so.

The logic of my function "DrawWorld":

```
#region DrawWorld
    // Draw all cubes in the world
    public void DrawWorld(GameTime gameTime)
    {
        effet.TextureEnabled = true;
        Plane lightPlane = new Plane(Vector3.UnitY, 0);
        Vector3 lightPos = new Vector3(-10f, 10f, 10f);

        //Try to initialize shadowMatrix
        Matrix shadowMatrix = Matrix.CreateShadow(Vector3.Normalize(lightPos), lightPlane);

        // Light settings
        effet.LightingEnabled = true;
        effet.DirectionalLight0.Enabled = true;
        effet.DirectionalLight1.Enabled = true;
        effet.DirectionalLight2.Enabled = true;
        effet.DirectionalLight0.DiffuseColor = col.ToVector3();

        effet.SpecularPower = 512f;

        // Fog settings
        effet.FogEnabled = true;
        effet.FogStart = arcadia.camera.NearPlane;
        effet.FogEnd = arcadia.camera.FarPlane;
        effet.FogColor = Microsoft.Xna.Framework.Color.White.ToVector3();

        // Set World with shadow matrice
        effet.World = Matrix.Identity * shadowMatrix  ;
        effet.View = arcadia.camera.View;
        effet.Projection = arcadia.camera.Projection;

        // Set the cube vertexBuffer and indice
        arcadia.Game.GraphicsDevice.SetVertexBuffer(graphicData[regionIndex][a].VertexBuffer);
        arcadia.Game.GraphicsDevice.Indices = graphicData[regionIndex][a].IndexBuffer;

        // Apply the basic effect
        effet.CurrentTechnique.Passes[0].Apply();

        // Draw the cubes vertices
        arcadia.Game.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, graphicData[regionIndex][a].VertexPosition.Length, 0, graphicData[regionIndex][a].Indices.Length / 3);

    }
    // #END OF DRAWWORLD
    #endregion

```

**Without shadow is this :**

**When i try to add shadow with "Matrix.CreateShadow(...)" i got this bad result:**

# Answer
> 3 votes
No. BasicEffect cannot be told how to calculate the light-space coordinates, nor how to compare the depths. It is a "basic" Phong shader.

Implementing this is fairly straight-forward:
-Draw the scene from the light's perspective into a texture, recording the scene depth only.
-Draw the scene again from the camera's perspective into a different texture using a custom shader.

For each pixel, the lighting shader needs to:
-Project the world-space coordinate into both screen-space (drawing) and light-space (sampling)
-Convert the light-space coordinates into UV's and sample the depth texture to retrieve the distance from the light to the first object it struck
-Compare the sampled distance to the actual distance between the pixel's world coordinate and the light
-If the light-space distance is less than the camera-space distance, the pixel is in "shadow"; shadow could mean actually shadowed, "behind glass", etc. You can use this same technique any time you need to compare per-pixel visibility and not just for shadows; it's up to you.
-Calculate the color any way you'd like; fixed color, sampling, NDL
-Modify the "final" color by the shadow factor; pixels in shadow are dimmed or black.

Shadowed pixels usually have a much darker shade of their original color; all 3 components are reduced more or less evenly. For things like colored glass, you do slightly more specific math to reduce the intensity of individual channels; i.e. blue glass "cancels" a lot of the green and red, but doesn't necessarily modify the blue channel.

Edit:
I created this diagram for a question about colored glass and thought I'd include it here, too. Reference this diagram while stepping through the preceding algorithm.

Please refer to Reimer's or the MSDN article for further information. Reimer's has images.

---
Tags: xna, c#, directx, lighting, shadows
---


title: Valid instances not drawn

text:
# Question
Title: Valid instances not drawn
i have a problem with my code, my valid instances aren't drawn.

I'm just at the beginning so i will post the whole code(which sounds bigger than it is)..just a few lines

```
public class MyGame implements ApplicationListener {
PerspectiveCamera cam;
Environment environment;
ModelBatch batch;
AssetManager assetManager;
Array<GameObject> instances;
ArrayMap<String, GameObject.Creater> creater;

//for debugging
CameraInputController camController;
//for debugging

//////////statics
public static float fieldOfView = 67;
public static float screenWidth;
public static float screenHeight;
public static final float camNear = 1;
public static final float camFar = 300;
public static Vector3 camPosition = new Vector3(5f, 9f, 10f);
public static Vector3 camLookAt = new Vector3(0, 0, 0);
//environment
public static final float ambientLightRed = 1f;
public static final float ambientLightGreen = 1f;
public static final float ambientLightBlue = 1f;
public static final float ambientLightAlpha = 1f;
//environment
//////////statics
@Override
public void create() {
    // TODO Auto-generated method stub

    screenWidth = Gdx.graphics.getWidth();
    screenHeight = Gdx.graphics.getHeight();

    batch = new ModelBatch();

    //bullet goes here
    //Bullet.init();
    //bullet

    //cam goes here
    cam = new PerspectiveCamera(fieldOfView, screenWidth, screenHeight);
    cam.near = camNear;
    cam.far = camFar;
    cam.position.set(camPosition);
    cam.lookAt(camLookAt);
    cam.update();
    camController = new CameraInputController(cam);
    Gdx.input.setInputProcessor(camController);
    //cam

    //environment goes here
    environment = new Environment();
    environment.set(new ColorAttribute(ColorAttribute.AmbientLight, ambientLightRed, ambientLightGreen, ambientLightBlue, ambientLightAlpha));
    //environment

    //assets go here
    assetManager = new AssetManager();
    assetManager.load("dirtyhuman.g3db", Model.class);
    assetManager.load("platform.g3db", Model.class);
    assetManager.finishLoading();
    //assets

    //models go here
    Model dirtyHuman = assetManager.get("dirtyhuman.g3db");
    Model platform = assetManager.get("platform.g3db");
    //model

    //arraymap goes here
    creater = new ArrayMap<String, GameObject.Creater>(String.class, GameObject.Creater.class);
    creater.put("dirtyHuman", new GameObject.Creater(dirtyHuman, "dirtyHuman"));
    creater.put("platform", new GameObject.Creater(platform, "platform"));
    //arraymap

    //modelinstances go here

    instances = new Array<GameObject>();
    instances.add(creater.get("dirtyHuman").create());
    instances.add(creater.get("platform").create());
    //modelinstances

    for(GameObject instance : instances)
    {
        Log.e("instances","" + instance);
    }

}

@Override
public void resize(int width, int height) {
    // TODO Auto-generated method stub

}

@Override
public void render() {
    // TODO Auto-generated method stub

    //update cam
    cam.update();
    //update cam

    //clear buffers
    Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1.0f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
    //clear buffers

    batch.begin(cam);
    batch.render(instances, environment);
    batch.end();
}

@Override
public void pause() {
    // TODO Auto-generated method stub
}

@Override
public void resume() {
    // TODO Auto-generated method stub

}

@Override
public void dispose() {
    // TODO Auto-generated method stub
    Log.e("Application Dispose","true");
    batch.dispose();
    instances.clear();
    assetManager.dispose();

    for(GameObject.Creater creater : this.creater.values())
    {
        creater.dispose();
    }
}

//////////////////////class gameobject
public static class GameObject extends ModelInstance implements Disposable {
    public GameObject(Model model, String node) {
        super(model, node);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void dispose() {
        // TODO Auto-generated method stub
        Log.e("GameObject.Creater Dispose","true");
    }

    static class Creater implements Disposable {
        Model model;
        String node;
        public Creater(Model model, String node) {
            // TODO Auto-generated constructor stub
            this.model = model;
            this.node = node;
        }

        public GameObject create() {
            return new GameObject(model, node);
        }

        @Override
        public void dispose() {
            // TODO Auto-generated method stub
            Log.e("GameObject Dispose","true");
            model.dispose();
        }

    }

}
//////////////////////class gameobject

```

}

So basically i'm just loading a `dirtyHuman` and a `platform`. Everything works fine till i implemented my static `GameObject` which extends `ModelInstance`. It's Kind of a factory class because the nested class `Creater` is responsible for creating the new GameObject. After that my Screen stays empty(no human drawn, no platform drawn). I will not mention on which devices i have tested it because it's surely no device depending problem..

I hope somebody can find the fault and make it clear to me what i actual did wrong.

# Answer
Got the Problem. Looking at the `source` of `ModelInstance` this part shows why it can't work:

```
public ModelInstance (final Model model, final Matrix4 transform, final String nodeId, boolean recursive,
128         boolean parentTransform, boolean mergeTransform, boolean shareKeyframes) {
129         this.model = model;
130         this.transform = transform == null ? new Matrix4() : transform;
131         nodePartBones.clear();
132         Node copy, node = model.getNode(nodeId, recursive);
133         this.nodes.add(copy = copyNode(node));
134         if (mergeTransform) {
135             this.transform.mul(parentTransform ? node.globalTransform : node.localTransform);
136             copy.translation.set(0, 0, 0);
137             copy.rotation.idt();
138             copy.scale.set(1, 1, 1);
139         } else if (parentTransform && copy.hasParent()) this.transform.mul(node.getParent().globalTransform);
140         setBones();
141         copyAnimations(model.animations, shareKeyframes);
142         calculateTransforms();
143     }

```

It doesn't render anything because of line `132`. I thought i can give my `new GameObject` a `nodeID` which is not similar to the `nodeID` in the crreater application ( for instance `Blender`). But he fetches the node from the `nodeID` which i put to the `constructor`. So if i put a `nodeID` which doesn't exist in the `Model` he surely can't find anything.
> 0 votes

---
Tags: libgdx
---


# Question
Title: Implimenting BADLAND like Body Movement in Box2d
I am trying to make a body (character in my game) move and behave in the same way as the character in the BADLAND Game with regards to rotation.

The character does not have fixed rotation and behaves normally when colliding with objects but automatically fixes its rotation to face forward when there are no other world forces applied.

How do I go about this. is it a use of a revolute joint with a motor? if so what do I attach the joint to?

# Answer
One way to align it back is to check it's current orientation.

```
float bodyAngle = body->GetAngle();

```

Compare it with the desired angle:

```
float delta = desiredAndle - bodyAngle;

```

Then use `applyTorque` with a tiny amount to slowly increase the speed in that direction If the angular speed is too high, stop increasing the speed:

```
if (delta > SMALL_ENOUGH)
{
    float angSpeed = body->GetAngularVelocity();
    if (sign(speed) != sign(delta) || Math.abs(speed) < MAX_SPEED)
        body->ApplyTorque( sign(delta) * EPSILON); // EPSILON is some small value
}
else
{
    body->ApplyTorque( -sign(angSpeed) * computeStoppingForce()));
}

```

Now you need to check how soon you will reach the desired angle and begin to slow down.

Generally, if you are moving as velocity `v` and need to stop smoothly after a distance of `x` then you are going to travel for `t = 2 * (x / v)` time unit, then you need to slow down at a rate of `a = v / t`. You can use that to callbrate your stopping motion. `v` is `angSpeed`. When the delta is small enough, you can have it beging to slow down instead of speeding up.
> 0 votes

---
Tags: java, libgdx, box2d
---


# Question
Title: Character Models: Single Mesh vs. Individual Parts
I was looking up 3D character models from various games (Battlefield 3 and DMC to be specific), just as research work and upon importing the model into Blender3D, I found that every part of the model was a separate mesh/object (head, armor vest, legs, hands, etc.).

This got me thinking: Why didn't the artist model them as a single object?

I think that would be better because:

1. You can save a few polygons in your model \[\*\].
2. Doesn't animating separate parts \[\**\] cause clipping issues as one mesh may not deform in sync with neighboring mesh?

\[\*\] All parts were overlapping each other = the armor vest was overlapping chest polygons, which were not visible and thus wasted.

\[\**\] All polygons and edges connected to each other.

# Answer
One central reason would be that in order to assign different materials, you need different entities / meshes / sub-objects. You don't need to have an individual object for each minor element (such as the mouth or the lips of a head) if you are applying a texture later, but UV unwrapping a few not so complex object separately and applying then a material is easier than UV unwrapping a single high-complex mesh.

Also: The polygon count is not a really relevant statistic anymore in contemporary 3D. Batchable draw operations are usually much more crucial to prevent unnecessary drawcalls / state switches. See the following extract from the Unity Graphics Performance page:

> Typical bottlenecks and ways to check for them:
>
> 1. GPU is often limited by **fillrate** or memory bandwidth. Does running the game at lower display resolution make it faster? If so, you’re most likely limited by fillrate on the GPU.
> 2. CPU is often limited by the number of things that need to be rendered, also known as “**draw calls**”. Check “draw calls” in Rendering Statistics window; if it’s more than several thousand (for PCs) or several hundred (for mobile), then you might want to optimize the object count.

Regarding animation: It depends on what kind of animation one is using: If you are working with a deformation approach (think "Armature" in Blender terms or "morph-target animation" or "vertex blending animation" in general) than a single object should work. But for bone based approaches individual objects make handling it usually easier.
> 4 votes

---
Tags: game-design, 3d-meshes, character
---


title: Box2D: Making it Determinsitic?

text:
# Question
Title: Box2D: Making it Determinsitic?
From articles on the web, I found that floating point math generally has accuracy of at least 6 digits. With this in mind, is it possible to make Box2D which uses floats fully deterministic through the use of heavy rounding (i.e. 1st or 2nd decimal place)?

# Answer
The answer is an obvious **no** simply because "heavy rounding" doesn't alleviate the problem. Like you suggested the issue is with how floats behave on different architectures.

Lets say you round things up. :) What happens with very large numbers? They are still exactly the same. Large numbers behave differently too on different architectures. Fractions, are simply large numbers with a different exponent that determines the radix (floating) point position.

You would need to implement a cross-platform number. This is a known and well covered subject. Hint, there are performance issues.
> 1 votes

---
Tags: physics, box2d, synchronization
---


# Question
Title: SDL_PollEvent very slow on SDL2, but works fine on SDL1.2
I have this simple app that displays a screen and handles the quit event:

```
while( SDL_PollEvent( &e ) != 0 )
    {
        //User requests quit
        if( e.type == SDL_QUIT )
        {
            quit = true;
        }
    }

```

If I compile this with SDL1.2 it runs fine, the quit event is handled immediately. However if I compile it for SDL2, then it takes ~5 seconds to get that event. And not just quit, but other events also, like mouse.

With sdl2 it takes ~95% of the cpu, while with sdl1.2 it's ~30-40%. The cpu is dual core, 1.2 ghz (pandaboard).

I suspect something, but I'm not 100% sure: I'm running this on ubuntu 12.04 which natively supports only sdl1.2. So I had to compile sdl2 from source code, as it's not available in that ubuntu.

Could this be the reason? Or any other clues what might be wrong? Thanks!

# Answer
I did not notice any performance issue with SDL\_PollEvent, but be careful when compiling SDL2, you must have X11 dev headers and maybe some drivers headers like MESA. Without these, everything will run software and you may have performance issues, especially on low-cost hardware. So yes, you probably have to recompile SDL2.
> 1 votes

---
Tags: sdl
---


# Question
Title: Are the Minecraft animations hardcoded into the game?
I would like to know how the animation system works in minecraft. I get a feeling that all the mobs are hardcoded into the game. Did notch really sit there and create the matrices for all the animation bones by hand?

I like recreating games for fun, so I would like to know how he did this. Also, if he truly does hardcode them... is there a better way?

# Answer
> 18 votes
As others have said, yes the models as well as the animations are hard-coded. If you would like to see how this was done, go to the Minecraft Coder Pack wiki.

> The package was created to help mod creators to decompile, change and recompile the Minecraft classes. Instructions are included in the readme files which come with the package. The package contains scripts to decompile, recompile, and reobfuscate the game and the server.

The classes you will want to look at are: ModelBase, ModelBiped, and ModelRenderer.

ModelBiped contains the following functions which do the humanoid animations:

```
public void render(Entity entity, float time, float f1, ...)
{
    setRotationAngles(time, f1, ...);
    ...
}

public void setRotationAngles(float time, float f1, ...)
{
    ...
    bipedRightArm.rotateAngleX = MathHelper.cos(time * 0.6662F + 3.141593F) * 2.0F * f1 * 0.5F;
    bipedLeftArm.rotateAngleX = MathHelper.cos(time * 0.6662F) * 2.0F * f1 * 0.5F;
    ...
}

```

The arm swings are simply cosine functions. The right arm is offset by PI to make them swing in opposing directions.

I hope that answers your question =)

---

If you would like more information on how to actually mod Minecraft, then check out this question:

How do I add a custom mob to Minecraft?

# Answer
> 8 votes
Models in Minecraft are hard-coded. There is no notion of block hierarchy (only a list of blocks). This means animations are either done procedurally (in a very basic way) or hard-coded values with interpolation.

There are a few editors for Minecraft models like Techne or FMCModeler which allow importing / exporting Minecraft model code for mods, but they don't support animations since it is probably handled differently for each model.

Here's a quick sample generated with FMCModeler:

```
//variables init:
public ModelRenderer box;

//constructor:
box = new ModelRenderer(0, 0);
box.addBox(0F, 0F, 0F, 16, 16, 16);

//render:
box.render(f5);

```

A better way to do it would be to build a full block-based modeler with some notions of block hierarchy so you can animate the models with keyframes and interpolation.

I'm currently building a multiplayer game building tool which does just that (among other things, http://craftstud.io/). It already allows building complex static textured models and more is on the way.

Here's a complex model built with CraftStudio As you can see, the blocks are arranged in a tree on the right:

Each block is serialized to disk / over the network with the following data:

* Unique ID
* Parent node ID
* Position (affects descendants)
* Scale (affects descendants)
* Angle (affects descendants)
* Offset from pivot point
* Block Size
* Block texture offset (UV coordinates offset for the texturing)

I plan on adding animation support by storing a map with animation names as key and a list of keyframes as value. Each keyframe will be associated with a block and a value to animate. Between keyframes, values should be interpolated (either linearly for position or spherically for angles, search for lerp and slerp).

# Answer
> 0 votes
Minecraft block models are actually not hardcoded into the game as of 1.8 and can be edited using resource packs. The JSON modeling system is fairly easy to understand and models exist at /models/block. You can then look at the code to see how it interprets the JSON models.

---
Tags: animation, geometry, minecraft-modding
---


title: Clearing a libGDX pixmap

text:
# Question
Title: Clearing a libGDX pixmap
Is there a way to clear a libGDX `Pixmap`? Or is the only way to dispose it and create a brand new Pixmap?

# Answer
If by clear you mean set all the pixels to transparent you could do the bellow.

```
Pixmap.setColor(Color.CLEAR);
Pixmap.fill()

```

http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/graphics/Pixmap.html#fill-- http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/graphics/Color.html
> 3 votes

---
Tags: libgdx
---


title: glBufferData consuming system memory

text:
# Question
Title: glBufferData consuming system memory
I am memory profiling my game in Visual Studio and about 60% of memory usage is happening from calls to `glBufferData()`. I may be missing something but should this consume GPU memory instead of system memory? I call it using `GL_ARRAY_BUFFER` and `GL_STATIC_DRAW` I was just wondering is there a way I can force it to use only VRAM?

Visual Studio attributes the memory usage to "nvoglv32.dll"

# Answer
Some relevant notes: https://stackoverflow.com/questions/5181540/gpu-access-to-system-ram It's talking about OpenCL & cuda but the same ideas apply.

Lots of VRAM will help performance, but the OpenGL driver is always free to allocate memory as it sees fit, and move it around as needed. Your hints may help it, but you cannot "force" it to allocate only on VRAM or system RAM.

(In your particular case, perhaps you are allocating more than will fit on the graphics card at one time?)
> 3 votes

---
Tags: opengl, c++, vbo, memory
---


# Question
Title: Using QuadTree for Procedural Generation
so I've been trying to start a new project that focuses on procedural room generation similar to what is seen in Binding of Isaac.

I plan to have the code use a QuadTree to help determine where rooms should be placed. Each node in the quad tree represents any of the possible 4 directions the next room can be placed.

The problem is this. I'm not sure where to start when trying to implement the QTree and haven't found good resources on the topic. Most implementations of QuadTrees in a procedural generation context use them for partitioning spaces and placing rooms within the partitioned spaces. Not sure if that's what I want to achieve. I'm also unsure of weather I should be going in this direction or if there's a more optimal solution?

# Answer
> 3 votes
As already stated in others comments I think you might be using the quadtree concept to solve the wrong problem.

I spend most of my time managing massive amounts of data working with voxels and even I don't touch quad trees for anything related to generating my world data.

The purpose of the quad tree is to help manage and work with your rendered world so it really has no place when thinking about generating your world.

The concept of building dungeons in the way you mention though is well known ...

http://www.roguebasin.com/index.php?title=Dungeon-Building\_Algorithm

http://journal.stuffwithstuff.com/2014/12/21/rooms-and-mazes/

...

Once you have your algorithm implemented for generating the raw data that represents your maze you can start to think about rendering it, for that you may or may not need to a quad tree.

If it's a typical rogue like you could get away with not using one at all and avoid the complication of it altogether, most I've seen building these sorts of games simply uses an array of cells that they move around in a grid loading and unloading the edges as needed.

My advice: Go back to basics and only use a qudtree if you absolutely need it.

# Answer
> 0 votes
It seams like the world is not big. The benefits of qadtrees is not really what you need if it's not a big world and you want to do fast search. I would recommend using a 2D array instead. If you want it to be dynamic use a dictionary of dictionaries of rooms using x and y indexes as keys.

---
Tags: procedural-generation, quadtree
---


# Question
Title: How do I size my map in blender so it will be the right size in unity?
I am working on a fps game but I cant get the size right of my map in blender, every time I export it to a .fbx file (unity won't work if it is a .blend file) it is a super small plane floor in unity the player controller is 10 as big as the map. I don't know what to do.

# Answer
> 1 votes
When you import an FBX file in Unity, it is scaled to 0.01 of its original size. You can either put it back to 1 (or anything you want) in the Model tab of the Inspector every time you import something, or you can make a small script that will do that for you whenever you import an asset.

# Answer
> 0 votes
Either change its `scale` from the Inspector after selecting the game object or the `pixels per unit` value of the exported asset from Import Settings (the menu when you choose the exported asset in the project hierarchy).

# Answer
> 0 votes
All you need to to is just remember one rule of thumb.Although I couldn't find any documentation on this.But with little workout I found that for Cube,Cylinder and Sphere\[\*\]

> 50 Blender units = 1 Unity unit

So You can do either of these:

1.Scale Your Objects 50x in Blender "Just" before exporting (By Hitting `S` and then 50,which will uni formally scale your Object 50 times in all axes).

2.Or Import Your Objects in Unity as it is, and in Transform Panel -\> Scale, Change every Value to 50.

\[\*\] These Standard Primitives in both Programs spawn with equal Dimensions.But a Plane Does not(It is Larger in Unity)

---
Tags: unity, blender
---


# Question
Title: Problem Rendering TTF_Font Textures to one Texture with SDL2
I'm trying to render multiple lines of text to one texture so I only have to render one texture to the screen. However, when I use a dstrect argument in SDL\_RenderCopy the text doesn't show up and when I use NULL for the dstrect argument it does work, but it is stretch to the entire texture which I don't want. I've checked the values of the dstrect (x,y,w,h) and they all seem to be at the right values when I try to render.

Here is the creation of the "Font Texture"

```
void Font::setMessage(std::string textureMessage, SDL_Color textColour){

if(text != NULL){
    SDL_DestroyTexture( text );
    text = NULL;
}

//contents is a string
contents = textureMessage;

//Render text surface
SDL_Surface* loadedSurface = TTF_RenderText_Blended( fontType, contents.c_str(), textColour );

if( loadedSurface == NULL ){
    std::cout << TTF_GetError() << std::endl;
}

if( loadedSurface == NULL ){
    //Error Check
    std::cout << "COULDN'T RENDER TEXT." << std::endl;
}
else
{

    //Create texture from surface pixels
    //text is of type SDL_Texture
    text = SDL_CreateTextureFromSurface( rendererPtr, loadedSurface );
    if( text == NULL ){
        //Error Check
        std::cout << "COULDN'T LOAD FONT TO TEXTURE." << SDL_GetError() << std::endl;
    }
    else{
        //w and h are int pointers to the SDL_Rect "textBox" offsets
        w = &textBox.w;
        h = &textBox.h;
        if( TTF_SizeText(fontType, contents.c_str(), w, h) != 0){
            std::cout << "COULDN'T SIZE FONT." << SDL_GetError() << std::endl;
        }
    }

}

//Get rid of old loaded surface
SDL_FreeSurface( loadedSurface );
loadedSurface = NULL;

}

```

And here is where I'm trying to render it to another texture:

```
    dstRect->x = xTemp;
    dstRect->y = yTemp;
    dstRect->w = messageLog.at(placeCount)->getW();
    dstRect->h = messageLog.at(placeCount)->getH();

    std::cout << dstRect->x << " " << dstRect->y << " " << dstRect->w << " " << dstRect->h << std::endl;

    if (messageLog.at(placeCount)->getSelf() != NULL){
        if ( SDL_RenderCopy(rendererPtr, messageLog.at(placeCount)->getSelf(), NULL, dstRect) != 0){
            std::cout << SDL_GetError() << std::endl;
        }
    }

```

Any ideas why giving an argument would make it not work but using NULL would?

# Answer
By checking this link https://wiki.libsdl.org/SDL\_RenderCopy the reason of your problems is clear. The srcrect parameter is a portion of the surface to print, if it is set to null, it will take the entire surface and dstrect is a portion of your destination surface, if it is set to null it will be stretched to fit the destination surface. If it does not show up, it is probably because of the x and y of the srcrect, if x \> w then the portion of the source surface is out of it, therefore SDL\_RenderCopy takes nothing and prints nothing.
> 1 votes

---
Tags: sdl2
---


# Question
Title: Elegant ways to handle rendering with DirectX 11
I'm looking for a design pattern that's going to help me to elegantly handle the rendering of my game objects.

Lots of game development guides talk about how to handle the game objects themselves, like monsters and characters and all that kind of thing. Nothing talks about linking all of that to DirectX. All the DirectX guides avoid good architecture in favour of getting something simplistic working.

The problem I am essentially having (that nobody seems to want to answer or give guidance on) is how to elegantly handle the COM objects that the DirectX 11 API gives us. I want to come up with a method of controlling how my COM objects are constructed and destructed, to protect my program from wanton destruction of these objects. I want them to be safely housed. The method of housing is consistently the stumbling block. I need the device and the device context in various parts of the program, but I want to avoid coupling every aspect of my program tightly to that.

I don't, for example, want a d3d "manager" object that I'm going to be passing all and sundry into with different methods for rendering the specific type of object I'm passing in. I don't want to have to be passing raw pointers to COM objects to every single method I create.

Ideally I don't want to be building a rigid, hard coded rendering pattern into my main() function or an equivalent Render() method of a cMain class.

I'm ok with how the COM objects interact together, all the interfacing with the DirectX API to achieve rendering. What I'm looking for is someone with experience of modelling a rendering engine, the bit that actually takes objects and renders them in a certain way and order based on a number of conditions. I'm looking for more generalised information on how I should go about designing the rendering element of my game to meet my needs.

My current solution, which includes:

```
class cMain {
public:
    cMain();
private:
    void Render();
    cD3D m_d3d; //<---- this class initializes and encapsulates all my d3d com objects
};

cMain::Render()
{
    float colour[4] = {0.2f, 0.4f, 1.0f, 1.0f};
    m_d3d.GetDevCon()->ClearRenderTargetView(&m_d3d.GetRenderTarget(), colour);
    m_d3d.GetSwapChain()->Present(0, 0);
}

```

And an entire philosophy built on that. Surely there's a more elegant way of designing it? I'm running the risk of coupling cD3D to everything using this method, or having all my render work in cMain, neither of which seem particularly sensible.

Alternatively, am I thinking about this too much? Is this the kind of thing that CAN go in my main class without sacrificing too much flexibility?

TL;DR - I'm having trouble wrapping my head around how I should **approach** building a rendering engine architecture that will accept all the different types of objects I want to render, including but not limited to game units, terrain objects, particles, etc.

I figure how I handle resource loading and access will be linked relatively tightly to how I handle the rendering process, and I want to get it right early on to minimize problems encountered at later stages.

# Answer
> 5 votes
This may not be a good solution to your specific needs but I'm gonna tell you how I handled a similar problem.

I developed a c++ object oriented game and wanted to encapsulate DirectX and COM in general inside my own classes, because I didn't wanted to use COM as base for the whole game.

The COM parts of my game (at the moment direct3d, direct2d, directWrite, WIC and directInput) are all encapsulated in two main classes:

* `GraphicsEngine`: everything that has to do with 3d, 2d (direct3d) and font rendering (direct2d and directWrite) as well as image and texture loading (WIC)
* `InputEngine`: Handles user input (directInput)

Each object which wants to render or use any of the COM functionality just stores a pointer to the object of these classes (They are singleton, so only one object exists). Both classes ensure the correct usage of the components and provide easy access:

**Constructors and Destructors:**

They handle initialization as well as releasing COM objects

**Member functions:**

They delegate access to the COM functionality. However, there is generally no direct access to COM objects like `ID3D11Device` or `IDirectInput8`.

*example:*

Instead of using for instance

```
deviceContext -> VSSetShaderResources(slot, count, shaderResourceViews);

```

one would use

```
graphicsEngine -> SetShaderResources(ShaderType::VertexShader, slot, count, shaderResourceViews);

```

ShaderType beeing a enumeration of all different shader types. This reduces the amount of member functions since `XXSetShaderResources` exists for multiple shader types.

**Error checking**

Since the COM functionality is encapsulated in these classes, it is possible to automaticly check for errors (for instance `HRESULT` return type of COM functions). This reduces the code classes using COM have to write.

*example:*

```
hr = this -> device -> CreateSamplerState(samplerDescriptions[i], &samplerState);
if(!SUCCEEDED(hr)) {
    // error handler here
}

```

This code is contained inside a method called `GraphicsEngine::AddSamplerStates`.

**asynchronous object loading**

DirectX gives you the possibility to create objects e.g. `ID3D11Buffer` on a different thread as the main thread. This allows you to load objects while the game is rendering other stuff (splash screen or loading animation). However, initializing a thread and later synchronize with the thread when loading is done (even in c++11) requires quite a bit of code. My classes allow me to encapsulate this loading functionality nicely. The class holds an array of loading threads currently loading objects. Once an object is complete, a flag is set and the main thread makes the newly created object available in the public interface of the class. This ensures the correct loading of objects and prevents the use of not fully loaded objects. (See example in the next section)

**object management**

This is the most important job the wrapper classes do. All objects created using one of the public wrapper methods around COM functions are stored in the class. The class uses a sort of Key - Value mechanism to give access to objects.

*Example*

```
HashKey vertexBufferLoaderId = this -> graphicsEngine -> AddBuffers(bufferKeys, bufferDescriptions, bufferData, 5);

```

This piece of code starts an object loading job for multiple `ID3D11Buffer` objects. `HashKey` is the type used by the classes as keys (code possessing a key can use the COM object stored under that key). `vertexBufferLoaderId` will (after the method returns) contain a key to a `ObjectLoader`, a class which keeps track of the loading progress. The code which launched the loading process can get the loaded object once `ObjectLoader` affirms the completion of the loading progress. bufferKeys is an array of HashKey pointers (`HashKey**`), that's where the the keys for the loaded objects are stored after the objects are done loading. `bufferDescriptions` and `bufferData` are parameters needed by direct3d to create the buffers. The last parameter holds the amount of buffers to load.

The caller can fetch the loading progress at any time using the key to `ObjectLoader`. When the process is done, the caller can access the created objects using the keys (`bufferKeys`) he provided.

(almost) all encapsulated functions of COM which need a COM object as parameter, are implemented as follow:

*Example*

```
void SetVertexBuffer(HashKey vertexBuffer, Slot slot, UInt32 stride, UInt32 offset);

```

instead of

```
void SetVertexBuffer(ID3D11Buffer* vertexBuffer, Slot slot, UInt32 stride, UInt32 offset);

```

By using keys instead of objects, the class can check whether the passed objects is valid and make sure it has been created by the wrapper itself:

```
if(!this -> buffers.Exists(vertexBuffer)) {
    // error handling
}

```

**conclusion:**

These wrapper classes are far from finished. Whenever I need a specific functionality of COM, I add specific methods and members for it, so the classes are "evolving" with my game.

**pros of my approach:**

* (almost, there are exceptions) no COM objects visible
* automatic management of COM objects
* easy access through keys (proprietary use of objects)
* multiple function calls forming a specific task are regrouped
* easy and safe multithreaded object creation

**cons:**

* a lot of code
* additional function call for each api call (a little bit slower but not crucial)
* each time a new functionality is needed it needs to be implemented

It surely took me some time (two weeks of my free time) to code and debug but now it works fine and I never have to worry about using resources such as `ID3D11Texture` or `ID3D11SamplerState` correctly in my game.

I hope I could give you an idea of how such an implementation could be done. This is the first time I programmed a thing like that so I'm curious to know whether it helped you and what do you think of it.

# Answer
> 2 votes
Ok, so basically, I eventually went with the Service Locator design pattern as detailed in Robert Nystroms Game Programming Patterns:

http://gameprogrammingpatterns.com/service-locator.html

My main game object creates a D3D object that handles all the COM objects and exposes them through accessors, and then the game object registers this D3D object with the D3DService class, which contains a static member pointer to the D3D object. Register takes a D3D&, so it can only ever be an existing D3D object. Any classes that require access to it's functionality creates a D3DService object and then has access to the D3D object.

D3D.h:

```
#include <dxgi.h>
#include <d3d11.h>
#include <DirectXMath.h>

class D3D
{
public:
    D3D(HWND hWnd);
    ~D3D();

    ID3D11Device* GetDevice();
    ID3D11DeviceContext* GetDevCon();
    ID3D11RenderTargetView* GetRenderTarget();
    IDXGISwapChain* GetSwapChain();
private:
    D3D();
    D3D(const D3D&);

    UINT32 m_test;
    void Clean();

    ID3D11Device* m_device;
    ID3D11DeviceContext* m_devCon;
    IDXGISwapChain* m_swapChain;
    ID3D11RenderTargetView* m_backBuffer;

    static bool isInstantiated;
};

```

D3DService.h:

```
#include "D3D.h"
#include <memory>

using std::unique_ptr;

class D3DService {
    friend class Game;
public:
    D3DService();
    ~D3DService();

    D3D* GetD3D();
private:
    D3DService(const D3DService& other);
    static void Register(D3D& d3d);
    static D3D* _d3d;
};

```

---
Tags: c++, architecture, directx11, design-patterns
---


# Question
Title: Can drawing to an FBO be done purely with a depth input texture, or do I also need a color attachment?
I am trying to implement Exponential Shadow Maps and I've got it almost working. The part I am stuck on is the "optional" separable Gaussian blur of the depth map to give soft-looking shadows.

I am using an OpenGL Framebuffer Object attached to a temporary depth map, and I am trying to use a screen quad (two triangles) with the original depth map as an input texture. Then, I am doing the same for the second stage of the blur, with the input and output reversed. Unfortunately, this results in a depth buffer filled with 1.0 which suggests to me that nothing is being drawn.

In this example code I've found, they are using a color and depth attachment in order to draw to a screen quad with a blur shader. (unfortunately the only OpenGL example I could find)

I want to know if this is necessary or that they are only attaching and blurring the color buffer because they are storing their depth values in it.

In other words, I would like to know if it is actually possible to only use a depth buffer Framebuffer Object attachment in this scenario.

# Answer
> 2 votes
Specifically: blurShadowMap() uses fbo2 which has only one R32F texture set as "color".

> I want to know if this is necessary or that they are only attaching and blurring the color buffer because they are storing their depth values in it.

Correct; depth is encoded into a "color" and stored in the color buffer

> In other words, I would like to know if it is actually possible to only use a depth buffer Framebuffer Object attachment in this scenario.

Using the hardware depth-buffer is never required and you are free to attach your "depth"-buffer as the only color target. To render correct 3D depths to the depth map, you will need a "depth" buffer (color) to store the depths, as well as the actual hardware depth buffer(float) to ensure proper culling. While blurring in 2D, the hardware depth-buffer is not required.

---
Tags: opengl, glsl, shadow-mapping, fbo
---


# Question
Title: On-screen counting within a certain time-frame
In my game the player can collect a 'virtual currency' - on the main menu I display the amount the player has collected. However, instead of simply displaying it, I want to count up from 0 to the amount the player has and then stop.

So - the logic would look something like this:

```
if (coinsToDisplay<=coinsPlayerHas){
    coinsToDisplay++
}

```

And then I would simply render the amount to the screen.

The problem is that obviously the more coins the player has the longer it takes to count.

I need to find a way make sure the counting **always** takes an arbitary amount of time (lets say 2 seconds).

My logic is called 60 times per second. I know that I can introduce a delay to *slow down* the couning if the user has a very small amount of coins. The time to wait between each count would be:

```
delay = 2000/coinsPlayerHas;  //2000 being 2 seconds expressed as milliseconds

```

I then wouldn't update the amount until the delay had passed.

```
if (delayHasExpired()){  //Only run this once our timer passed

    if (coinsToDisplay<=coinsPlayerHas){
        coinsToDisplay++
        resetDelay();
    }

}

```

But what if the player has thousands of coins? At 60 Ticks Per Second the most I could count when incrementing 1 per tick is 120 max in 2 seconds. Therefore I need to find a way of counting more than 1.

I just can't figure it out, so any pointers would be appreciated.

# Answer
> 1 votes
Change your counting to be more than one at a time:

Instead of:

```
coinsToDisplay++

```

Do something a bit more dynamic like:

```
coinsToDisplay += coinsPlayerHas/100;
if(coinsToDisplay > coinsPlayerHas)
    coinsToDisplay = coinsPlayerHas;

```

In this case (if the player has more than 100 coins) it'll always take around 100 ticks to count to the total.

You can modify it further by using a `float` for the amount to add, and only displaying an integer amount. That'll make it so the time from 0 to `coinsPlayerHas` will always be the same.

---
Tags: java
---


title: Aligning Camera to Rectangle

text:
# Question
Title: Aligning Camera to Rectangle
I'm working on a game in Java, and I'm having some trouble with finding the correct camera position. I've already made a Rectangle that shows exactly where I want the camera to be, and at what scale:

However, whenever I actually try to adjust the camera so it fits with the rectangle, I get weird results. The camera goes in weird places when I get to a point where the scale isn't 1: (The blue rectangle shouldn't be visible in the above gif, because that's where the camera's edges should be.) Right now I have a camera class, where I set the position with:

```
x=-((leftX+Math.abs(leftX-rightX)/2)-Main.WINDOW_WIDTH/2/scale);
y=-((topY+Math.abs(topY-bottomY)/2)-Main.WINDOW_HEIGHT/2/scale);

```

Where `leftX`, `rightX`, `topY`, and `bottomY` are the topmost, rightmost, topmost, and bottommost points of the rectangle. Those two lines of code are where the problem lies. I simply need to figure out where to move the camera based on the scale.

For translating and scaling, I have this:

```
g.translate(cam.getX(), cam.getY());
g.scale(cam.scale, cam.scale);

//Render in-game objects

g.translate(-cam.getX(), -cam.getY());
g.scale(1/cam.scale,1/cam.scale);

```

What I'm asking is, how can I move the camera so that it's perfectly aligned with the rectangle?

# Answer
I managed to figure it out. The answer was actually extremely simple, and I was overthinking it. I just changed

```
x=-((leftX+Math.abs(leftX-rightX)/2)-Main.WINDOW_WIDTH/2/scale);
y=-((topY+Math.abs(topY-bottomY)/2)-Main.WINDOW_HEIGHT/2/scale);

```

to

```
x=-rect.x*scale;
y=-rect.y*scale;

```

where rect is that blue rectangle shown in the original post.
> 2 votes

---
Tags: java, graphics, camera, scale
---