title: Strategic AI in turnbased games?

text:
# Question
Title: Strategic AI in turnbased games?
I'm interested in how strategic AI engines work, e.g. how to evaluate where to place troops in a turnbased strategy game etc.

I do get how goal based AI works, and I guess that is a good approach to decide what to build or research in a game like Civilization.

But tactical/strategical positioning of troops/units. What algorithms/strategies are used to evaluate those things? any reference papers/articles?

# Answer
> 3 votes
You might find reading the book "Artificial Intelligence for Games" very helpful. It gives you insight in the AI implementation of various kinds of games. (e.g. troop placement/movement, path finding, decision trees, ..)

See http://www.amazon.com/Artificial-Intelligence-Games-Second-Millington/dp/0123747317

# Answer
> 2 votes
Possibly not the best solution, but decision trees, specifically a minimax tree may be a good approach to take. See http://en.wikipedia.org/wiki/Minimax

You would need to create a heuristic function which can determine how good/bad a world state is. But this can become a bit more complicated if you are working with a large number of possible world states.

# Answer
> 2 votes
Artificial Intelligence is, unfortunately, an entire subsection of Computer Science. It's truly huge - something you can take a couple of semesters of in college just to get you warmed up.

There are a lot of common options - Decision Trees, Rules Engines, Neural Networks - the latter of which most people tend to find extremely interesting when they first hear about them (and invariably prove to be a horrible idea in the kind of scenario you're describing - look out for that). I recommend you look up some topics or books on basic AI development in general - it may not seem directly relevant to games specifically at first, but you'll appreciate understanding the fundamentals.

# Answer
> 0 votes
Have a look at Monte Carlo Tree Search (like min max but prunes the kind of large trees you see in games these days with large branching factors).

http://en.wikipedia.org/wiki/Monte\_Carlo\_tree\_search

http://aigamedev.com/open/coverage/mcts-rome-ii/

http://www.aot.tu-berlin.de/fileadmin/files/lehre/diplomarbeit/BA\_Barbara\_Konz.pdf

---
Tags: ai, strategy, turn-based-strategy
---


title: Shader that draws just vertex points

text:
# Question
Title: Shader that draws just vertex points
The game I am developing is in unity and I want to make a shader which can be put on a mesh that only 'draws' color on each vertex point. I am not proficient with shaders, and out of all my searching I have come up empty handed; I unfortunately don't even know how to look up this question (I seem to only find results about point clouds, which only serves to confuse and scare me more ;P).

Any help or if you can point me in the right direction on what to search, I would be very much greatful.

# Answer
If you're writing shaders, you should know a bit about the world, view, and projection matrices. I'm assuming you do, so if you don't, either read up on it or let me know. For every vertex, you can determine its position on the screen by creating a float4, with the first 3 parameters being the vertex position, and the last being 1. When you have this float4, multiply it by the world, view and projection matrices. You will now end up with another float4. Divide this one by its own w value, and you'll get a float4 with the following:

The x value will be between -1 (left edge of the screen) and 1 (right edge of the screen), the y value will be between -1 (top edge of the screen) and 1 (bottom edge of the screen), and the z value will be between -1 (camera's far plane) and 1 (camera's near plane). If any value is out of those bounds, the vertex is not on screen.

With this float4, and knowing the game's resolution, you can determine the exact pixel location of the vertex (I'm going to leave that up to you because it's quite a simple division of the resolution and the x and y coordinates, and I believe you can do that.) When you have the x,y coordinate of the vertex on screen, you can just draw a circle at that point (use a sprite and you can draw whatever you want there, little stars, pacmen, anything)
> 1 votes

---
Tags: unity, shaders, vertex, cg
---


# Question
Title: How to pass content through the project's structure efficiently?
so following situation. I have a project which is structured something like this.

**Game1** -\> **GameManager** -\> **Module** (multiple instances)

During runtime units are being spawned in each instance of the Module class. Those Units require spritesheets for animation. Let us say each unit has a "Move", "Attack" and "Die" state, each using a individual spritesheet. This makes three Texutre2D instances per unit and with 5 different units this adds up to 15 different Texture files. Those are being passed to the unit's constructor on creation.

As I am loading those textures in Game1's LoadContent method I have to pass them the entire way to the Module class which then uses those textures to instaciate units.

**Game1.LoadContent**(15x textures) -\> **GameManager**(15x textures) -\> **Module**(15x textures) -\> **Unit**(3x textures)

Imo this has several disadvantages:

1. As far as I can judge all those 15 textures are being held in memory of the Module classes the entire time. I would like to avoid that.
2. Also passing 15 textures through the project's entire structure makes the classes unreadable and ugly.
3. I've got the overall feeling that this is not the way things should be done here.

In order to avoid problem #2 I created a class, its only purpose is to hold all textures that are needed in Module.cs. I called the class AnimationCollection. It holds Texture2D variables and the according getters and setters. So now my Project looks like this.

**Game1.LoadContent**(new AnimationCollection(15x textures)) -\> **GameManager**(AnimationCollection) -\> **Module**(AnimationCollection) -\> **Unit**(AnimationCollection)

While this does seem to solve problem #2 the other problems remain. Are there other options on how to handle this problem? I could think of something like loading all content in the Module Class itself, but I never saw this before. I always load my stuff in Game1.LoadContent().

Any ideas, suggestions or expert knowledge is highly appreciated.

Thanks in advance!

# Answer
> 2 votes
It is possible to just pass the Content Manager to your modules, and have them load their own textures/data. Its also tidier, as the Module is responsible for loading its own textures, and doesn't have to depend on its resources being loaded elsewhere.
I do something similar - my data objects have a string specifying a texture/model, and my rendering code uses that string to load the corresponding texture/model via the ContentManager when an object is being drawn. Essentially, my rendering class uses the textures/models, so its responsible for loading them. The data objects just tell it what ones to load.

Also, Texture2D is a class, which means its passed by reference by default. Only the ContentManager actually holds the Texture2D itself, and your modules hold a pointer which refers to the memory location the Texture2D has been loaded into. So despite having 15 pointers across your unit classes, there is only one instance of each texture through your program (unless you have 2 identical textures which different filenames loaded individually). The ContentManager also caches all content files it loads, so trying to load an already loaded file returns the one it loaded earlier.
Sadly, there is no way to remove individual textures from the ContentManager - you unload all content, or none.

The above summarized & answering your questions:

1. The ContentManager loads all your textures into memory, your modules just have a pointer which references the loaded texture. There isn't duplicates unless you load 2 identical but differently named files.
2. Yep. Its easier to just have your modules load there own textures, not to mention its tidier and your modules don't have to rely on something else loading its textures - it has control when it comes to loading.
3. Yep. What you current have is not the best way to do it in my opinion. You can do it what way, but I feel there are better ways. In the end it boils down to what you're comfortable using, and what you feel is best.

---
Tags: xna, textures, xna-content-pipeline
---


title: Drawing 3D cubes with xna

text:
# Question
Title: Drawing 3D cubes with xna
I managed to draw a 3d cube using triangles like this:

```
    protected override void LoadContent()
    {
        basicEffect = new BasicEffect(GraphicsDevice);
        VertexPositionColor[] vertices = new VertexPositionColor[8];
        short[] indices = new short[36];
        vertexBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPositionColor), vertices.Length, BufferUsage.WriteOnly);
        indexBuffer = new IndexBuffer(graphics.GraphicsDevice, typeof(short), indices.Length, BufferUsage.WriteOnly);
        Color Color1 = Color.DarkRed;
        Color Color2 = Color.Pink;
        float width = 2;
        float height = 1;
        float depth = 0.5f;

        vertices[0] = new VertexPositionColor(new Vector3(0, 0, 0), Color1);
        vertices[1] = new VertexPositionColor(new Vector3(width, 0, 0), Color1);
        vertices[2] = new VertexPositionColor(new Vector3(width, -height, 0), Color1);
        vertices[3] = new VertexPositionColor(new Vector3(0, -height, 0), Color1);
        vertices[4] = new VertexPositionColor(new Vector3(0, 0, depth), Color1);
        vertices[5] = new VertexPositionColor(new Vector3(width, 0, depth), Color1);
        vertices[6] = new VertexPositionColor(new Vector3(width, -height, depth), Color1);
        vertices[7] = new VertexPositionColor(new Vector3(0, -height, depth), Color1);

        indices[0] = 0; indices[1] = 1; indices[2] = 2;
        indices[3] = 0; indices[4] = 3; indices[5] = 2;
        indices[6] = 4; indices[7] = 0; indices[8] = 3;
        indices[9] = 4; indices[10] = 7; indices[11] = 3;
        indices[12] = 3; indices[13] = 7; indices[14] = 6;
        indices[15] = 3; indices[16] = 6; indices[17] = 2;
        indices[18] = 1; indices[19] = 5; indices[20] = 6;
        indices[21] = 1; indices[22] = 5; indices[23] = 2;
        indices[24] = 4; indices[25] = 5; indices[26] = 6;
        indices[27] = 4; indices[28] = 7; indices[29] = 6;
        indices[30] = 0; indices[31] = 1; indices[32] = 5;
        indices[33] = 0; indices[34] = 4; indices[35] = 5;

        vertexBuffer.SetData<VertexPositionColor>(vertices);
        indexBuffer.SetData(indices);
    }

```

I have two questions:

* As you can see i am using `float width = 2; float height = 1; float depth = 0.5f;` but why "width = 2" looks like 80 pixels instead of 2? I want the cubes to be **72x24x12**, i can't figure out how to **calculate the pixels** from the field of view / aspect ratio. To draw the cube on **different positions** i am using `world = Matrix.CreateTranslation(10.0f, 10.0f, 0.0f);`, is that the correct way to do this ?
* How can i draw each face of the cube a different color? (Right now i know how to give color to each vertice, see Color1 variable). Right now i am using 2 different `BasicEffect`s, is there any better way perhaps ?

# Answer
> 1 votes
So , as already was sad there are no pixels in 3D spcae at all. There are usints that dont have any relations with 2D pixels. Pixel are also units, but they have fixed size couse screen have have fixed resolution. For example if your monitor is 12 inches in width and 9 inches in height and resolutins is set to 800x600 one pixel will have real size 0.015x0.015 inches^2.

But 3D's units is not pixels. Theare are no relations with hardvare and screen resolution. If you want create rectahgle with size 72x24x12 than do it. Next you need to create camera with distance, aspect rations and angle of view that allows you see all you scene. If scene if too big than move camera farther, or scale down the scene.

You can do tree types of transformation with matrices: translation, rotation, scaling. Most important thing you should now that if you apply few transformatins that every next will be applyind for all that was applyid before. For example if you do

```
transform = translate(10,8,10) * scale(2,3,5) * translate(4, 5, 10)

```

it means that you translate your first model at(10,8,10) units, but then scale ALL distances to (2,3,5). So, your model's size will be scaled, as far as distance of applyed translation and translate(10,8,10) will means translate(20,24,50). Then you translate model again at translate(4, 5, 10), and this translations will NOT be scaled. So, you can create all scene withoud scaling and then just scale it before drawing.

This article was very helpfull for me. If you don't understand russian click at "**часть 1, часть 2, часть 3 и часть 4**" links int top of article.

# Answer
> 1 votes
Like dustin said, the size of a 3d object isnt measured in pixels. But if you wish to scale it, change "world = Matrix.CreateTranslation(10.0f, 10.0f, 0.0f);" to "world = Matrix.CreateScale(2) * Matrix.CreateTranslation(10.0f, 10.0f, 0.0f);". Notice that I put the scale factor matrix BEFORE the translation. Otherwise, the translation would also get scaled. Matrix multiplying works from left to right.

And for your second question: if you want all faces to have a different color, you will have to place differently colored vertices at every point of the cube/block. This is because as you said, you can assign one color per vertex.

# Answer
> 0 votes
For: why "width = 2" looks like 80 pixels instead of 2?

Pixels are gone in 3d space, but you still use them in your UI canvas.

Your distances are in "units". How large something looks depends on if you put the camera 1 unit away from the object or 20, 100, etc.

---
Tags: xna, c#, xna-4.0, monogame
---


title: How animate objets seperately?

text:
# Question
Title: How animate objets seperately?
I've set up a simple scene with some triangle and quads. With `glPushMatrix()` and `glPopMatrix()` i achieved to move an object to a new position, relative to another object in my render scene, but what i want is, for example, that the first triangle translates every render() call -2 units on the z axis, but the other triangle translates only -1 unit. I couldn't find any information how to manage this. As yet every `glTranslatef()` affects all objets. So what I have to do?

# Answer
First stop using the fixed function pipeline. It's deprecated and removed from new versions; shaders is the new kid on the block.

With shaders you have a Matrixes stored in each object and you only need to set the applicable uniform to it and use it in the vertex shader.

Using the old fixed function the solution is push and pop the matrix for each object separately:

```
glPushMatrix();
    glTranslatef(...);
    renderTriangle();
glPopMatrix();

glPushMatrix();
    glTranslatef(...);
    renderTriangle();
glPopMatrix();

```
> 1 votes

# Answer
To add onto ratchet freak's answer, the modern way to do this now is to use a vertex buffer object.. Basically, you create a buffer which stores the vertex data and can be modified every frame with the new vertex data, which is then drawn with `glDrawArrays` or `glDrawElements`. This way is also fast because you're drawing all the vertex data in a single draw call (which changes once you have to bind multiple textures). You can then easily modify the vertex data in any way you desire. The downfall is that it's a bit hard to set everything up and get it running, but the end result is definitely worth it.

I recommend Lazyfoo's tutorial on the subject, it's what I used when I was learning about it (as well as general googling).
> 0 votes

---
Tags: opengl
---


# Question
Title: Mix multisample and non multisample rendering in Directx11
is there a way to mix multisample and non multisample rendering in Directx11? It seems that when I create a multisampled render target I always get a multisampled rendering, regardless of the value of the MultisampleEnabled flag of the RasterizerDescription.

Microsoft says:

"To use multisampling, set the enable field in the rasterization description, create a multisampled render target, and either read the render target with a shader to resolve the samples into a single pixel color or call ID3D11DeviceContext::ResolveSubresource to resolve the samples using the video card."

and also

"There are no restrictions for mixing multisampled and non-multisampled rendering within a single render target."

But then in the rasterizer description page it says:

" For feature levels 10.1 and higher, the setting of MultisampleEnable has no effect on points and triangles with regard to MSAA and impacts only the selection of the line-rendering algorithm as shown in this table...

"

So, how can I temporarily turn multisampling off on a multisampled render target, in order to draw part of the scene without multisampling?

# Answer
> 1 votes
As far as I know you cant.

You will have to create another render target without MSAA and do one of two things:

* Copy the MSAA target into the non-MSAA, resolving the subsamples, and keep rendering in the non-MSAA for your alpha geometry (wild guess that this is why you need MSAA off)
* Render non-MSAA to the non-MSAA target and merge the two render targets, that only works for opaque passes unless you use depth peeling (http://en.wikipedia.org/wiki/Depth\_peeling).

In theory you could use the pixel shader and render a 1-pixel larger triangle and kill pixels outside of the intended triangle boundaries but in reality rounding errors will likely create a mess and discarding fragments in the shader has a small performance impact compared to non-discarding shaders on some hardware.

(If anyone knows a better solution that would be very much welcome.)

---
Tags: directx11, multisampling
---


# Question
Title: What's the fastest way checking if two moving AABBs intersect?
I have two AABBs that are moving, what's the fastest way to check if they will intersect under a frame?

By moving I mean not just to check with the usual rectangle intersection method, I mean some kind of simple easy swept test that only returns a boolean, no hit time or anything else.

What I think is to simply do it like this:

But that Hexagon is quite complex and I don't know how to calculate an AABB - Polygon intersection, is there maybe an easier way?

Any programming language that you like the most, I can easily port it.

Thanks.

# Answer
> 10 votes
**Use the Minkowski sum**

A good way to solve this problem is to consider the intersection between a line of motion (*v*) translated to the origin (*v'*) and the Minkowski sum of *A* rotated 180 degrees at the origin (*A'*) and its obstacles (just *B* in this case): *A'**B*.

In the following picture I place *A* smack-dab in the origin of an arbitrary coordinate system. This simplifies understanding as rotating A by 180 degrees results in *A'*, and *v* translated to the origin equals *v'*.

The Minkowski sum is the green rectangle, and the intersection points of a moving *A* and a stationary *B* can be found by doing line-AABB intersection. These points are marked with the blue circles.

In the following picture a different origin was used and the same intersection points are found.

**Multiple moving AABBs**

To make this work for two AABBs that move in a linear fashion during a specific period of time you would subtract *B*'s velocity vector from *A*'s velocity vector and use that as the line segment for the line-AABB intersection.

**Pseudo code**

```
def normalize(aabb):
    return {x1: min(aabb.x1, aabb.x2), x2: max(aabb.x1, aabb.x2),
            y1: min(aabb.y1, aabb.y2), y2: max(aabb.y1, aabb.y2),

def rotate_about_origin(aabb):
    return normalize({x1: -aabb.x1, x2: -aabb.x2
                      y1: -aabb.y1, y2: -aabb.y2})

# given normalized aabb's
def minkowski_sum(aabb1, aabb2):
    return {x1: aabb1.x1+aabb2.x1, x2: aabb1.x2+aabb2.x2,
            y1: aabb1.y1+aabb2.y1, y2: aabb1.y2+aabb2.y2}

def get_line_segment_from_origin(v):
    return {x1: 0, y1: 0, x2: v.x, y2: v.y}

def moving_objects_with_aabb_intersection(object1, object2):
    A = object1.get_aabb()
    B = object2.get_aabb()

    # get A'⊕B
    rotated_A = rotate_about_origin(A)
    sum_aabb = minkowski_sum(rotated_A, B)

    # get v'
    total_relative_velocity = vector_subtract(object1.get_relative_velocity(), object2.get_relative_velocity())
    line_segment = get_line_segment_from_origin(total_relative_velocity)

    # call your favorite line clipping algorithm
    return line_aabb_intersection(line_segment, sum_aabb)

```

**Collision response**

Depending on the gameplay you would either perform more fine-grained collision detection (maybe the AABB's contain meshes), or move forward to the next phase: collision response.

When there is a collision the line-AABB-intersection algorithm will return either 1 or 2 intersection points depending on whether A ends its movement inside B or passes through it, respectively. (This is discounting the degenerate cases where A grazes B along their sides or along one of their respective corners.)

Either way, the first intersection point along the line segment is the collision point, you'd translate this back to the correct position in the world coordinate system (the first light-blue circle in the second picture along the original *v*, call it *p*) and then decide (e.g., for elastic collisions by reflecting *v* along the collision normal at *p*) what the actual position for *A* at the end of the frame will be (*At+1*).

If there are more than just 2 colliders this will get a little more complex, as you'd want to do collision detection for the second, reflected, part of *v* as well.

# Answer
> 5 votes
OBB - Oriented bounding box. Here's a tutorial

Effectively, a bounding box aligned with the Velocity vector of object A as the y-axis (up). It's width and height can be calculated by the starting and ending points of object A. You then compare this with the AABB of object B (treating it as an OOBB), and your golden.

If you're just looking for a quick intersection test to see IF they COULD possibly intersect, you could create an AABB that surrounds object A's AABB in both the starting and ending positions. If an AABB does-not intersect with this all encompassing AABB, then there is no intersection; However, this could lead to false positives, so you should only use it as a preliminary test.

# Answer
> 4 votes
You don't need OOBs and you don't need to use time-stepping collision detection. Just use the normal AABB swept test, see this link. In essense it does exactly what you have in your diagram: the moving AABB is "swept" from start point to end point and then that is used for collision detection against other, static AABBs.

If you are worried that this swept test is more expensive because it returns an "impact time", I think you prematurely optimizing.

More in-depth information about swept tests can be found in the excellent book: Real-Time Collision Detection by Christer Ericson.

# Answer
> 3 votes
You will need to first decompose the movement into smaller steps and use that information to calculate a high-level AABB. If the large AABB's intersect, you can then check the smaller steps to be more accurate.

Estimating whether or not there may have been a collision by checking AABB (or OOBB) using just the starting and ending positions can miss collisions if either object is rotating quickly and is longer in one dimension than another.

To calculate a more accurate estimate AABB, decompose the movement into smaller steps, and using only the initial AABB (not the object mesh), rotate the AABB (now just a box, not axis aligned) as the object would rotate and move at each step. The max and min points for each axis will give you the AABB that encloses the entire movement of the object.

If there is an intersection with the larger AABB, you can then use the smaller AABBs that were already calculated to determine where the collision may have been. For each of the smaller AABBs that intersect with the other object, you can then do the more expensive mesh intersection detection.

# Answer
> 2 votes
You will have to decompose the movement into smaller steps of movement. For example:

You want to decompose the movement using the greater componen (in this case, X-axis), and then check for collision in each step.

This might look too expensive, but take into account that an object moving faster than it's own width each cycle will be EXTREMELLY fast, so this scenario is not as common as you first might think.

# Answer
> 2 votes
You should also use relative speeds for the collision check so one AABB is "static" and the other move at a speed of its own speed minus the speed of the "static" one.

The fastest way to see if they *may* intersect is to just expand the moving AABB with the speed.

for example the AABB is moving right with 0.1 x/frame, then you extend it so the left edge remains the same and the right edge is 0.1 further. Then you can check with the new AABB. If false then there is no collision. (early return and accurate for small speeds).

Then you can check if the end and start AABB of the moving object intersects. if true then return true.

Otherwise you need to check whether the diagonal intersects the static ABB.

This involves getting the coordinates of the diagonal where x= left edge of the static and the right edge see if the y is inside the bottom and top. (repeat the other way around)

---
Tags: collision-detection, geometry, computational-geometry, motion
---


# Question
Title: How can I update a sprite sheet without affecting the sprites already being used?
Every time I overwrite my sprite sheet with additional or updated sprites, I have to reattach the textures to all of my Animations and Sprite Renderers. How can I update a sprite sheet without affecting the sprites on that sheet which are already being used?

During the development of even a small game, hundreds of textures are being used. And new textures are being added and updated every day. This results in many hours spent reattaching textures which could otherwise be used being productive. What strategy can I use to prevent this?

This is an example of what I mean:

I have a sprite sheet with 40 textures. All of its sprites are attached to their relative GameObjects. I decide I want to change the color of one of my sprites' hat. I go into gimp and load the sprite sheet. I change the color of the hat. I overwrite the old sprite sheet.

Back in Unity, all of the textures are no longer attached to their respective GameObjects. I go in and splice the sprite sheet again and manually reattach all of the textures. Then I decide I like the old hat better. I go back into gimp, change the sprite sheet, and am then forced to reattach all of the textures...again. There has to be a better way! (Also would like to be capable off adding new sprites in addition to editing old ones.)

# Answer
> 2 votes
Be sure you open the Sprite sheet from the path of the asset. You can achieve this either opening the sheet within the project window or going thru your documents to the asset folder of the project location.

You can open it with your editor of choice and can then update and apply the changes to the project file "your sprite sheet"

doing this will update it rather than overwrite it with a whole new file.

---
Tags: unity, textures, sprites, spritesheet
---


title: Normalizing a homogeneous 3d point

text:
# Question
Title: Normalizing a homogeneous 3d point
As I've seen corruption in geometry, why is it a bad idea to normalize a homogeneous (divide by w) the vertex position returned from vertex shader?

**Update**

Vertex shader:

```
// float4 pos : SV_POSITION;
output.pos = mul( mvpMatrix, float4(input.pos, 1) );
output.pos /= output.pos.w; // this line causes the visual corruption below

```

Three images as I move to the right of a sphere in wireframe. As I get closer the geometry starts corrupting. It seems the geometry immediately around the camera gets the most corrupt.

# Answer
> 2 votes
It's hard to make out exactly what you mean, but it sounds like you are dividing the vertex position by `w` as part of your computation in your vertex shader. This is incorrect, the division by `w` is actually done for you by the graphics processor. Consider the standard transformations here:

(Original image from: http://www.c-jump.com/bcc/common/Talk3/Math/Matrices/Matrices.html )

If you were to divide by `w` yourself it would just end up happening twice which will naturally yield strange results. The vertex shader can safely write the vertex position as the result of

```
gl_Position = Proj * View * Model * in_vertex;

```

EDIT: My answer is in the context of OpenGL, but the same would apply to DirectX.

---
Tags: mathematics, shaders, hlsl, vertex
---


title: Opengl Quad Tessellation Control Shader

text:
# Question
Title: Opengl Quad Tessellation Control Shader
I have the generic tessellation evaluation shader for triangles but I need to make it work for quads. Is there any chance someone could explain what is happening here and point me in the right direction?

```
layout(triangles, equal_spacing, cw) in;
in vec3 tcPosition[];
out vec3 tePosition;
out vec3 tePatchDistance;
uniform mat4 Projection;
uniform mat4 Modelview;

void main()
{
    vec3 p0 = gl_TessCoord.x * tcPosition[0];
    vec3 p1 = gl_TessCoord.y * tcPosition[1];
    vec3 p2 = gl_TessCoord.z * tcPosition[2];
    tePatchDistance = gl_TessCoord;
    tePosition = normalize(p0 + p1 + p2);
    gl_Position = Projection * Modelview * vec4(tePosition, 1);
}

```

I understand that they're multiplying the control points (the original patch vertices) by the components of the new vertex (I guess relative to the patch verts?) and then normalizing the sum of these vectors to get the actual position of the new vertex which conforms to a nice unit sphere when applied to a cube of patches. I want to extend this to work on quads: `layout(quads, ...) in` and add the `tcPosition[3]` vector but I don't really know how to get the same behavior with the fourth vertex.

# Answer
Quad tessellation is similar to trianlges. The difference is that instead of barycentric coordinates *gl\_TessCoord.xyz* which define point on a triangle (*tcPosition*) you have 2-component coordinate *gl\_TessCoord.xy* (they also span in \[0-1\] range).

Hull shader (or Tessellation Control Shader in OpenGL terminology) looks pretty straightforward:

```
#version 430
layout (vertices = 4) out;
void main(void)
{
    if (gl_InvocationID == 0) // to not do same stuff 4 times
    {
        // calculate A, B, C, D,E, F - based on your algorithm, or just set constants
        // set 2 innner tess. levels
        gl_TessLevelInner[0] = A;
        gl_TessLevelInner[1] = B;
        // set 4 outer tess. levels (for each edge)
        gl_TessLevelOuter[0] = C;
        gl_TessLevelOuter[1] = D;
        gl_TessLevelOuter[2] = E;
        gl_TessLevelOuter[3] = F;
    }
    gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;
}

```

As you've, probably, noticed. For quads we have 4 outer tessellation levels and 2 inner. Because, surprisingly :-), we have 4 edges and 2 dimensions to subdivide inside quad. If you calculate tessellation levels dynamically (e.g. based on distance from camera) care should be taken to set correct index in gl\_TessLevelOuter/Inner. Otherwise, your mesh might not be watertight. OpenGL uses next convention (which, by the way same as DirectX uses):

* gl\_TessLevelOuter\[0\] - for edge defined by u=0 (i.e. edge 0-1)
* gl\_TessLevelOuter\[1\] - for edge defined by v=0 (i.e. edge 0-3)
* gl\_TessLevelOuter\[2\] - for edge defined by u=1 (i.e. edge 2-3)
* gl\_TessLevelOuter\[3\] - for edge defined by v=1 (i.e. edge 1-2)
* gl\_TessLevelInner\[0\] - tess. in horizontal (u) direction
* gl\_TessLevelInner\[1\] - tess. in vertical (v) direction

Orientation of quad vertices is clockwise. Note that zero vertex (u=0, v=0) is located in left bottom corner, that is different from DirectX, just in case you are porting code).

Basically, your UV space looks like this:

```

Y (V)   1-----2
^       |     |
|       |     |
|       0-----3
|
+-------> X (U)

```

Now, it is completely up to you how many control points to pass! One may think that quad uses 4 and triangle uses 3, but you may e.g. have 4x4 grid and evaluate vertex position using Bezier curves.

Lets move on to domain (Tessellation Evaluation) shader. One example could look like this:

```
#version 430
layout (quads) in;
in vec3 tcPosition[];
out vec3 tePosition;
out vec2 tePatchDistance; // 2 components now!
uniform mat4 Projection;
uniform mat4 Modelview;
void main(void)
{
    // interpolate in horizontal direction between vert. 0 and 3
    vec3 p0 = mix(tcPosition[0], tcPosition[3], gl_TessCoord.x);
    // interpolate in horizontal direction between vert. 1 and 2
    vec3 p1 = mix(tcPosition[1], tcPosition[2], gl_TessCoord.x);
    // interpolate in vert direction
    vec3 p = mix(p0, p1, gl_TessCoord.y);
    tePatchDistance = gl_TessCoord.xy;
    tePosition = normalize(p); // project on unit sphere
    gl_Position = Projection * Modelview * vec4(tePosition, 1);
}

```

You can, of course, interpolate in vertical direction first. tcPosition indices depend on your control points positions. I've provided case for the picture drawn above. I suggest, you to disable back face culling for the beginning to minimize frustration in case you suddenly generate triangles with winding different from stated.

Hope this helps.

You can also look up this link for more info.
> 1 votes

# Answer
For the sad weary soul a decade from now who stumbles upon this question wishing for it to be answered:

```
void main(void){
    vec3 p1 = mix(tcPosition[0], tcPosition[3], gl_TessCoord.x);//may have to rearrange these numbers depending on your implementation
    vec3 p2 = mix(tcPosition[1], tcPosition[2], gl_TessCoord.x);

    vec3 pos = normalize(mix(p1, p2, gl_TessCoord.y));

    gl_Position = Modelview * vec4(pos, 1);//Also, porjection
}

```
> 4 votes

---
Tags: opengl, shaders, vector, tessellation
---


# Question
Title: Binding an Instance Matrix with an InputLayout
If I want to bind an instance matrix to a vertex shader, how do I go about it?

For example, here is a super-simple VS input:

```
struct VS_IN {
    float4 Position : POSITION;
    row_major float4x4 WorldMat : INSTANCE_TRANSFORM;
};

```

How would the corresponding bindings look when creating the `ID3D11InputLayout`?

I figured it would be something akin to:

```
D3D11_INPUT_ELEMENT_DESC[] bindings = ...;
bindings[0] = {
    "POSITION", // SemanticName
    0U, // SemanticIndex
    DXGI_FORMAT::DXGI_FORMAT_R32G32B32A32_FLOAT, // Format
    0U, // InputSlot
    0U, // AlignedByteOffset
    D3D11_INPUT_CLASSIFICATION::D3D11_INPUT_PER_VERTEX_DATA, // InputSlotClass
    0U // InstanceDataStepRate
};
bindings[1] = {
    "INSTANCE_TRANSFORM", // SemanticName
    0U, // SemanticIndex
    DXGI_FORMAT::DXGI_FORMAT_R32G32B32A32_FLOAT, // Format
    1U, // InputSlot
    0U, // AlignedByteOffset
    D3D11_INPUT_CLASSIFICATION::D3D11_INPUT_PER_INSTANCE_DATA, // InputSlotClass
    1U // InstanceDataStepRate
};
bindings[2] = {
    "INSTANCE_TRANSFORM", // SemanticName
    0U, // SemanticIndex
    DXGI_FORMAT::DXGI_FORMAT_R32G32B32A32_FLOAT, // Format
    2U, // InputSlot
    0U, // AlignedByteOffset
    D3D11_INPUT_CLASSIFICATION::D3D11_INPUT_PER_INSTANCE_DATA, // InputSlotClass
    1U // InstanceDataStepRate
};
bindings[3] = {
    "INSTANCE_TRANSFORM", // SemanticName
    0U, // SemanticIndex
    DXGI_FORMAT::DXGI_FORMAT_R32G32B32A32_FLOAT, // Format
    3U, // InputSlot
    0U, // AlignedByteOffset
    D3D11_INPUT_CLASSIFICATION::D3D11_INPUT_PER_INSTANCE_DATA, // InputSlotClass
    1U // InstanceDataStepRate
};
bindings[4] = {
    "INSTANCE_TRANSFORM", // SemanticName
    0U, // SemanticIndex
    DXGI_FORMAT::DXGI_FORMAT_R32G32B32A32_FLOAT, // Format
    4U, // InputSlot
    0U, // AlignedByteOffset
    D3D11_INPUT_CLASSIFICATION::D3D11_INPUT_PER_INSTANCE_DATA, // InputSlotClass
    1U // InstanceDataStepRate
};

```

In the example above, I'm increasing the `InputSlot` value with each 'row' of the instance matrix, because I would expect that each row of the matrix would take up the next 128-bit input register.

However, in other examples I've seen on the internet, people seem to increase the `SemanticIndex` with each row instead. I thought that might because they declare the input as four `float4` fields instead of a matrix, but then I looked at this question, and that doesn't seem to be the case.

Anyway, to cut to the point, **if I want to use `VS_IN` in the format I've provided, what is the correct way to lay out the input elements?**

# Answer
If you use same semantic for **SemanticName**, then you need to increase number for **SemanticIndex**.

I also see that you are increasing **InputSlot**. This may be correct or not depending on how your data is layed out. If you really have 4 vertex streams (vertex buffers) then it's fine, but I assume that your instance transform is stored in one vertex buffer. Then you need to set same stream number to **InputSlot** in every instance binding.

assume that:

```
stream_number = 4;

```

You'll also need to set this stream:

```
//  most probably offset_in_vertices will be 0 in your case
// vert_buf - contains your instrancing data
IASetVertexBuffers(stream_number, 1, &vert_buf, &stride, &offset_in_vertices);

```

Also while AlignedByteOffset is optional i suggest at least use D3D11\_APPEND\_ALIGNED\_ELEMENT to specify that data go sequentially one after another.

so, setup code will look like this:

```
bindings[0] = {
    // nothing changed
};
bindings[1] = {
    "INSTANCE_TRANSFORM", // SemanticName
    0U, // SemanticIndex
    stream_number, // InputSlot
    0, // AlignedByteOffset: zero because start of a matrix
    // ...
};
bindings[2] = {
   "INSTANCE_TRANSFORM",
    1U, // SemanticIndex
    stream_number, // InputSlot
    D3D11_APPEND_ALIGNED_ELEMENT, // or 16 (4 float32)    AlignedByteOffset
    // ...
};
bindings[3] = {
    "INSTANCE_TRANSFORM",
    2U, // SemanticIndex
    stream_number, // InputSlot
    D3D11_APPEND_ALIGNED_ELEMENT, //or 32, AlignedByteOffset +4 float32
    // ...
};
bindings[4] = {
    "INSTANCE_TRANSFORM", // SemanticName
    3U, // SemanticIndex
    stream_number, // InputSlot
    D3D11_APPEND_ALIGNED_ELEMENT, // or 48 AlignedByteOffset +4 float32
    // ...
};

```

Then your vertex shader input structure will look like this:

```
struct VS_IN
{
    float4 Pos          : POSITION;
    float4 r0           : INSTANCE_TRANSFORM0;
    float4 r1           : INSTANCE_TRANSFORM1;
    float4 r2           : INSTANCE_TRANSFORM2;
    float4 r3           : INSTANCE_TRANSFORM3;
};

```

Or like this:

```
struct VS_IN
{
    float4 Pos                  : POSITION;
    row_major float4x4 inst_mat : INSTANCE_TRANSFORM;
};

```
> 1 votes

---
Tags: directx11, hlsl, matrix, instancing
---


# Question
Title: How to write a good functional spec for a game?
I am basically (shamelessly) copying a question that has appeared on SO few years ago. The answers are good, but I would like to get more on this topic, so I'm trying a more specialized subreddit substackexchange. What I'm secretly hoping for is an answer from Byte56, I wonder if he has wrote a spec for AoG? :)

I'm trying to write a functional spec for a game according to Joel's article series (who wouldn't love anything this genius guy writes) and I'm not happy with my current approach. It's much easier to write a functional spec for a web application, or a website (my full-time job is still web app development) where I can describe every possible screen in a separate chapter, and also scenarios are easier to come up with.

The game is a turn-based logic/puzzle game, but it's fast and fun enough to play for many audiences, so:

* Should I write scenarios based on various gamer types (e.g. nervous FPS players, macro-obsessed strategy guys, solitaire loving housewives, etc.) and try to describe what will they expect from the game and how will they use it?
* What should represent "screens" in the spec; the game screens (e.g. menu, loading screen, main game screen, etc.) or should I rather describe all different possible in-game situations as screens (e.g. my turn, waiting for opponent's turn, possible turns, what happens if I make a invalid move, etc.)?

Just writing this question helped me to settle my thoughts about the spec, but I'm submitting it to see if I can get any good answers from this great community.

# Answer
> 6 votes
Videogames are very different from the kind of software that Joel is talking about. In several ways.

For example, Joel talks about taking the "spec" to "the customer". Yeah, that's not how videogames work. When was the last time you heard of Shigeru Miyamoto taking a design document out to the public and asking if a feature filled their needs? Game developers don't communicate with their customers the way that software engineers communicate with people who buy their software.

It's an artistic work; when you make art, you generally don't have a lot of interplay between the maker and those who might buy it. You *can*, but certainly not on the level of a "functional specification".

Another problem with a "functional specification" for a game is that it is, well, inflexible. Game development is obviously functional, but it is also *artistic* as well. So you need to be flexible. You might *think* that some aspect of your game will work like X. But when you actually code it, it doesn't have the intended effect. You therefore need to be flexible in your development; you need iteration time to smooth out the play experience. And I'm not just talking about UI.

A "functional specification" doesn't help here. You have to adopt a "guess and check" methodology. Change stuff, see if it plays better, change more stuff, etc. Your development needs to be flexible.

That being said, is a "functional specification" of value in game development? To varying degrees yes. It does still have its uses as a means for communicating software development issues across a software team. And the most important task is that it makes you do is *think about what you're doing **before** doing it*.

In game development, a "functional specification" is really just a "game design document," with some exploration of the technical sides of the implementation. If you're working on a team, then it's probably important to use that as a way to get everyone on the same page.

The key thing is to not get too attached to things. Your game design document may say X, but ultimately, you must decide if X is good for your game when you try it. A design document should be a start point, not an end point.

# Answer
> 4 votes
A spec doesn't prevent issues, it just creates them at a different point, but you probably still won't recognise them until the implementation.

Writing a specification only serve two purposes, helping you remember your thoughts and sharing those thoughts with your team mates.

Writing down your thoughts is not going to make them better, it may force you to think about them some more, it may make it easier for you to share those thoughts with other people, but the same thoughts don't grow any better just because they are put on paper.

Ultimately specifications in a game design process are for throwing away. First you implement them, then you know how they are wrong, then you do something different.

Write the specifications for a prototype, they won't last any longer than that, so no reason to write more than what is needed for a prototype in the first iteration.

# Answer
> 1 votes
The mere act of writing a spec will clarify, illuminate, and "make better" an idea. The first person you are attempting to communicate your idea to is yourself. "Putting it down" is the first step. A designer who thinks "it's all in my head" is only fooling themselves. Start writing it down and s/he will find out exactly how much they were fooling themselves. Docs may be a necessary evil, but they are more necessary than evil.

---
Tags: game-design, documentation
---


# Question
Title: Loading images using their bytes in Unity
If you import an image into the Unity inspector, the image will be encoded in Unity's own format. Usually the resulting image is much bigger than the original (from 100kb to 1MB). Of course, you can do stuff like compress and change the texture max size to reduce the image's size, but at the end it will almost always be bigger.

I noticed that you can create a `Texture2D` if you got the necessary bytes. As an experiment, I took my 100kb image and imported it to Unity as a `.bytes` file. Then I read the bytes and created my `Texture2D`:

```
    Texture2D texture = new Texture2D(100, 100);
    texture.LoadImage(myTextAsset.bytes);
    Sprite sprite = Sprite.Create(texture, new Rect(0,0,350, 288));

```

And it works. And it is smaller (100kb).

So my question is: what's the difference between Unity's builtin way of handling images and my way of loading them using their bytes? Because I'm saving tons of memory with this method. I *imagine* that it is a bit slower. But if that's the only difference, I can live with that.

# Answer
> 1 votes
Unity is a black box. Nobody outside Unity can tell how it really works without doing a lot of reverse engineering.

My educated **guess** is that Unity saves some sort of metadata along with the raw bytes in a file, and then loads that data straight to GPU memory. I did this with my own engine, with addition that I gzipped the binary data before saving, and then unzipped it when loading. I do that for all assets regardless if they are textures or anything else, so it is not really texture-spesific thing.

Loading compressed data will be quite a bit faster than reading larger amount of data. If Unity do not apply some sort of compression on the raw binary data, then it surely will be slower to read the data from a disc drive. But if the compression algorithm is too complex uncompressing might take more time, and usually it will always take more memory than just copying the raw bytes straight to the GPU. Choosing between these is a design decision they have made.

As it says in the documentation of Texture2D.LoadImage() the function takes PNG or JPG compressed bytes. Loading these images will prbably be faster, but it will get more complicated since you have to set the texture parameters every time you load the images. Also if you want to store compressed image in the GPU memory, you'll have to call Texture2D.Compress() on each texture you want to compress, which will probably make the process slower. That is a tradeoff that you might want to consider; using compressed textures will usually make your frames render faster since less texture reading is needed, but the image quality is then also a little bit lower.

Also mipmapping should be taken in to account, but I did not find any API calls regarding to manually controlling them. So I have to make another **guess** that unity generates mipmaps for the texture when you use Texture2D.LoadImage(), you wanted them or not. If you did not want them, then it is about 1/3 wasted texture memory. Loading textures using the standard pipeline of Unity, you can control mipmaps a lot better.

---
Tags: unity
---


# Question
Title: Why does this simple if-statement that checks my main characters state never get called (Java/LibGDX)?
Been working on this for a while - basically I want my player to perform a front flip when he jumps (screen tap -\> player jumps). I wrote the animation class **Animator** (extends **Player** implements **ApplicationListener** and my plan is to initialise it in Player (main character class) whenever his state becomes ***JUMPING***. I did a few tests using System.print and found that when the screen is tapped (i.e. whenever **touchDown()** is called) the Player's state IS modified (using stateModifier("jumping").

However, the code inside if(state == playerState.JUMPING) in update() for some reason is never called. I know this is the case because the System.print I wrote never gets outputted. I'll throw my code in here since you will probably need to see the big picture:

```
public class Player extends GameObject implements InputProcessor {
private Animator jumpAnimation; // the class where the animation takes place
private playerState state; // enum of player states
private float gravity;
private boolean allowJump;
private float accelerationJump;
private Texture img;
private Sprite sprite;

public Player(float xPos, float yPos) {
    super(xPos, yPos);
    img = new Texture(Gdx.files.internal("JUMP1.png"));
    sprite = new Sprite(img);
    setxPos(xPos);
    setyPos(yPos);
    setxSpeed(4.6f);
    setySpeed(0);
    sprite.setX(getxPos());
    sprite.setY(getyPos());
    setType("player");
    gravity = 0.34f;
    accelerationX = 0.02f;
    accelerationJump = 14f;
    allowJump = true;
    Gdx.input.setInputProcessor(this);
    state = playerState.NORMAL;
}

// change the player state
public void stateModifier(String modify) {
    if (modify.equalsIgnoreCase("jetpack")) {
        state = playerState.JETPACK_MODE;
    } else if(modify.equalsIgnoreCase("normal")) {
        state = playerState.NORMAL;
    } else if(modify.equalsIgnoreCase("jumping")) {
        state = playerState.JUMPING;
        System.out.println(state);
}
}

public void update() {

    // Player's speed in the y plane is affected by gravity
    setySpeed(getySpeed() - gravity);
    // Player constantly moving
    moveBy(getxSpeed(), getySpeed());
    // Don't allow Player to fall below the ground due to gravity
    if (belowGround()) {
        moveTo(getxPos(), groundY);
    }
    // If Player is on the ground then he can jump, so set allowJump to true
    if (onGround()) {
        allowJump = true;
        setySpeed(0);
    }
    // if the player is in a jumping state, run the jump animation
    if (state == playerState.JUMPING) {
        // this print statement should get called when a player jumps but never does
        System.out.println("should animate right now");
        jumpAnimation = new Animator(getxPos(), getyPos());
    }
}

public void jump() {
    setySpeed(getySpeed() + accelerationJump);
}

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    // if the player is in a normal state (i.e. not jumping) and he is allowed to jump
    if (state == playerState.NORMAL && allowJump) {
        // set player state to playerState.JUMPING
        stateModifier("jumping");
        jump();
                    // set player state to playerState.NORMAL after the jump
        stateModifier("normal");
        allowJump = false;
    }
    return true;
}

```

}

Any help is highly appreciated, thank you very much.

tl;dr when screen is tapped, touchDown() is called, which changes the Player's state to JUMPING. however when i write an if statement in update() to check for this, it never gets executed. why is this the case?

# Answer
It is never called because in the touchDown function you are calling `stateModifier("normal")` right after `stateModifier("jumping")`, so the state will be set to NORMAL when the function ends. In the update function you are testing if the state is equal to JUMPING, but is not, it will be NORMAL.
> 1 votes

# Answer
I guess you're switching to "normal" state too early. In fact, you're doing it right after you switch to "jumping" state, with just one instruction inbetween, so actually its like continuos "normal" state, "jumping" is to short to ever get noticed by render method. Jumps should last some time, and then you should switch back to "normal" state after you land on the ground again.
> 1 votes

---
Tags: java, 2d, libgdx, physics, animation
---


# Question
Title: Mirroring a game object to create symmetry
I have a GameObject with a primitive shape that I call "body". I want to create and add a child to it with another primitive shape. I call it 'mutation'. But i want to duplicate the 'mutation' and mirror the duplicate. So they become symmetrical to the 'body'. This way it could resemble wings or legs or eyes.

I've tried to create two children to the mutation called "LeftSide" and "RightSide". I duplicated the new primitive and put one copy in each. I set the Left Side's scale to -1 for the X, Y and Z hoping that it would mirror and create a symmetry with the right side. But its not working out.

So I'm hoping for some tips on ideas on how to achieve this?

# Answer
Mirroring an object happens only across one plane; it's not a global -1 scale, as you've done here.

You only want to set the scale to -1 for **one** of the X, Y, or Z axes (Which one depends on which direction you want it to be mirrored). Leave the other two axes with a scale of 1.
> 1 votes

---
Tags: c#, unity, scale
---


title: Unity3D Strafing Left & Right

text:
# Question
Title: Unity3D Strafing Left & Right
I am trying to set my character up to strafe left and right and have 2 different animations, on for left and one for right, so far what i have written allows me to strafe left or right but it only ever plays the right strafe animation. What am i doing wrong?

```
private void Strafe() {
    if (Mathf.Abs (Input.GetAxis ("Strafe")) > 0) {
        animation.CrossFade ("strafeRight");
        _controller.SimpleMove(_myTransform.TransformDirection(Vector3.right) * Input.GetAxis ("Strafe") * strafeSpeed);
    } else if (Mathf.Abs (Input.GetAxis ("Strafe")) < 0) {
        animation.CrossFade ("strafeLeft");
        _controller.SimpleMove(_myTransform.TransformDirection(Vector3.right) * Input.GetAxis ("Strafe") * strafeSpeed);
    }
}

```

# Answer
Right after i posted this i realized i was using MathF.Abs... No Need for that lol. here is correct code and works fine now!

```
private void Strafe() {
    if ((Input.GetAxis ("Strafe")) > 0) {
        animation.CrossFade ("strafeRight");
        _controller.SimpleMove(_myTransform.TransformDirection(Vector3.right) * Input.GetAxis ("Strafe") * strafeSpeed);
    } else if ((Input.GetAxis ("Strafe")) < 0) {
        animation.CrossFade ("strafeLeft");
        _controller.SimpleMove(_myTransform.TransformDirection(Vector3.right) * Input.GetAxis ("Strafe") * strafeSpeed);
    }
}

```
> 1 votes

---
Tags: c#, unity
---


# Question
Title: Sharpdx DirectX11 MapSubresource is failing trying to map a staging texture
I'm trying to render to a texture and then pull the image data out. I've created one texture as a render target and another as a staging texture. After rendering to the render target, I use CopyResource to copy from the render target texture to the staging texture. So far, so good. However, when I use DeviceContext.MapSubresource to get the data from the staging texture, I get E\_INVALIDARGS exception, and I can't figure out why.

Here is how I create the staging texture:

```
        textureDesc = new Texture2DDescription()
        {
            ArraySize = 1,
            BindFlags = BindFlags.None,
            CpuAccessFlags = CpuAccessFlags.Read,
            Format = Format.B8G8R8A8_UNorm,
            Height = 256,
            MipLevels = 1,
            SampleDescription = new SampleDescription(1, 0),
            Usage = ResourceUsage.Staging,
            Width = 256
        };
        _renderStaging = new Texture2D(_dev, textureDesc);

```

Here is how I populate the staging texture and then try to map it:

```
            DataStream stream;
            _con.CopyResource(_renderTarget, _renderStaging);
            // The following is the line that fails
            box = _con.MapSubresource(_renderStaging, 0, MapMode.Read, MapFlags.None, out stream);

```

I have the same code working in C++, so I know I have the general idea right. This is the working C++ code:

```
textureDesc.Width = 256;
textureDesc.Height = 256;
textureDesc.MipLevels = 1;
textureDesc.ArraySize = 1;
textureDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
textureDesc.SampleDesc.Count = 1;
textureDesc.MiscFlags = 0;
textureDesc.Usage = D3D11_USAGE_STAGING;
textureDesc.BindFlags = 0;
textureDesc.CPUAccessFlags = D3D10_CPU_ACCESS_READ;
hr = dev->CreateTexture2D(&textureDesc, NULL, &renderStagingTexture);

devcon->CopyResource(renderStagingTexture, renderTargetTextureMap);
D3D11_MAPPED_SUBRESOURCE mappedResource;
devcon->Map(renderStagingTexture, 0, D3D11_MAP_READ, 0, &mappedResource);

```

# Answer
The error was due to \_con being the deferred context while in the equivalent C++ code I was using the immediate context. When I switched the SharpDX code to use immediate context, it worked just as expected.

Unfortunately, the problem was not illustrated by the code I posted.
> 0 votes

---
Tags: directx11, sharpdx, rendertargets
---


# Question
Title: Java, Crashing with a Shader on Intel HD Graphics
I just got a new computer (Acer Aspire ES1-311) which has an integrated Intel HD Graphics card, and I noticed that this fisheye shader crashes my game (LibGDX game, VM Crash):

```
varying vec2 v_texCoords;
uniform sampler2D u_texture;
uniform vec2 pos;
uniform float radius = 100;
uniform float scale = 1;
void main()
{
    vec2 textureCoordinateToUse = v_texCoords;
    float dist = distance(pos, v_texCoords);
    textureCoordinateToUse -= pos;
    if (dist < radius)
    {
        float percent = 1.0 + ((0.5 - dist) / 0.5) * scale;
        textureCoordinateToUse = textureCoordinateToUse * percent;
    }
    textureCoordinateToUse += pos;
    gl_FragColor = texture2D(u_texture, textureCoordinateToUse);
}

```

I've tried to update the drivers from the official site, but the driver application says that they might be incompatible with my computer!

However, does anyone spot anything "wrong" in the shader that might cause the crash?

Thanks.

# Answer
Try running the java VM with the option -Xss8M to set it to 8 Megabytes. You only have 9 Threads so you should be fine with 9x 8M stacks. Then reduce the amount until it crashes again, bring it back up a bit, then document in your FAQ that this option is needed for some video drivers.

```
java -Xss8M -jar myjarfile.jar

```

The crash logs points to the Intel driver needing a larger stack:

From the pastebin we can see that the stack allocated for the main thread is only 320KiB (327,680 Bytes, that's the default value)

```
=>0x15997000 JavaThread "LWJGL Application" [_thread_in_native, id=5440, stack(0x161c0000,0x16210000)]

```

And the stack pointer (ESP) is very near the bottom of the stack with only 73,364 bytes left *(0x161d1e94 - 0x161c0000)*

```
ESP=0x161d1e94 is pointing into the stack for thread: 0x15997000

```

And EAX is at the bottom:

```
EAX=0x161c0000 is an unknown value

```

We can also see some recursion inside the Intel driver with these code addresses appearing a few times in the call stack:

```
C  [ig7icd32.dll+0x36349f]

C  [ig7icd32.dll+0x119d42]

C  [ig7icd32.dll+0x119d31]

```

All these are strong hints that it is not a ""bug crash"" but simply that the stack is too small.

The main thread of a native applications usually have much larger stacks (8MB is not uncommon) so it's quite possible the driver needs a stack larger than 320KB.
> 2 votes

---
Tags: java, libgdx, glsl, virtual-machines
---


# Question
Title: Is it legal to sell or monetize games created with the Unity 3D free edition?
Is it okay to use Unity 3D programming and gaming software to create mobile game apps for Android and iOS? I am using a free version of Unity 3D and planning it to sell my current game app I've created by publishing it to Google Play. I also use this method for earning money by setting as a free app with ads on it.

I saw some developers relied on using free version of Unity 3D to create games and published it via App Store or Google Play. If it does, should I have to pay or share contribution to the Unity development team for earnings since I use the free version in order to rely for producing several game apps for business?

# Answer
> 23 votes
From the Unity FAQ:

> ## Can we sell games and make money with the free version of Unity?
>
> Yes you can create and sell a game with the free version of Unity, without paying royalties or any revenue share. However, the free version of Unity may not be licensed by a commercial entity with annual gross revenues (based on fiscal year) in excess of US$100,000, or by an educational, non-profit or government entity with an annual budget of over US$100,000.
>
> Please also be aware that the feature set of the free version is not intended for the production of professional games and interactive content. Lastly, games made with our Pro trial licenses may not be distributed nor used for commercial purposes.

---
Tags: unity, legal, google-play, business-model
---


# Question
Title: Unity IOS game restart when you press the home button
Why does my unity IOS game restart when i press the home button on the device? The same game worked fine on Android device and did not restart on pressing the home button. Thanks

# Answer
When the app is in the "multi-task tray" as you call it in the comments, it is NOT running. It is only showing you a screenshot of the last state the game was in before it got suspended.

As Peethor suggests in the comments you do need to understand and learn the life cycle of an iOS app...

https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/TheAppLifeCycle/TheAppLifeCycle.html

When the user hits the home button the app will send a message that this is about to happen and then the app will be suspended. (Assuming that it's not a true background app like a music playing app). When you get that message you need to save off the game state. While suspended if the app quits, like say you swipe it up in that background task tray, it will quit without notifying you again.

Then on the reverse of that, if the game is coming out of suspended you'll get another notification. There you can restore this data if necessary and get the game back to where it was. Also if the app just starts up the normal way you could check this as well.

But it's important to realize that generally (in most cases) iOS manages "background" apps by not having them actually running. Which is a very good thing that you must embrace as an iOS developer.

You also might want to look at this: http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnApplicationPause.html

So you could do this:

```
void OnApplicationPause(bool paused)
{
    if (paused)
    {
      // Save off your game state in case it never comes back
    }
}

```
> 1 votes

---
Tags: unity, ios
---


# Question
Title: How to calculate rect-moving-in-a-curved-path collision detection
I'm trying to find the best way to use collision detection for a rect moving in a curved path: here is example of what i have I found few methods and I have hard time to find what is the best way.
I have the pure calculation method that is here:
http://devmag.org.za/2009/04/13/basic-collision-detection-in-2d-part-1/
and I also have the pixel perfect method that is here:
http://blog.muditjaju.infiniteeurekas.in/?p=1

I'm using cocos2d-x but it can be in any engine or language. What is the best method for this?

# Answer
Of the methods you listed, the pixel perfect is the only one which can solve your exact problem. That is, unless:

* The curved line is defined by an exact formula you can use in checking
* You create a series of boundary lines that Approximate the curved line, and check for the crossover of any vector.

Hope that helps! :)
> 3 votes

---
Tags: collision-detection, curves
---


# Question
Title: Do I have to compile Unreal 4's source myself in order to make games with it?
Now I understand the need for this if people want to make modifications to the engine itself, but if I want to use the engine as is and just program games with it, do I need to do all this?

I figured I needed to build the Engine because a UE4 programming tutorial said "I assume you have already downloaded the engine source from GitHub and compiled it in VS2013", nobody says why, nobody clearly states whether or not this is required to make a game in C++ using Unreal Engine 4.

Can anyone help?

# Answer
You don't need to build the the engine / editor yourself. There are several iterations of the engine (current is 4.4), since they released it earlier this year (4.0), are you sure that you used the same one as in the tutorial? You can select the version you want to use in the launcher. The only source you have to build are your own classes, you want to add to the project.
> 5 votes

# Answer
If you use the monthly subscription option, you are given access to the private GitHub repository and must compile the editor before you can use it. The wiki has an excellent walkthrough of the current process.

It's getting easier - the upcoming 4.6 release has a setup script that does everything for you in one step - but subscribers don't get prepackaged binaries yet.

It is my understanding that a custom license may give you access to pre-built binaries.
> 2 votes

# Answer
Is that possible duplicate of your original post on stackoverflow?

But I want to give to you the same answer here:

> No you dont need the whole engine. There is a difference between the code which builds the editor and the code which builds your game. If you only want to program your game you should create a new "code project" and modify the code you're getting after creating the new project.
> 0 votes

---
Tags: unreal
---


title: A* pathfinding in 3D

text:
# Question
Title: A* pathfinding in 3D
I've looked through some A\* pathfinding algorithm examples, but as far as i know they work with grids e.q -\> http://qiao.github.io/PathFinding.js/visual/

But how can I use this algorithm in my 3D Engine(I'm using Unreal Engine 4)?

# Answer
> 15 votes
Actually A\* does not use dimensions.

A\* works with **nodes** and each nodes have paths to other nodes.

In the case of a 2D grid every cell is a node and every boundary is an **implicit path** (left, right, up, down, and/or diagonals), the key here is that it is implicit.

This is a trick to reduce the memory footprint, but A\* itself does not require a 2D or 3D grid. You can use A\* with **explicit paths/connections** between the nodes such as a country road map.

In the case of a 3D grid, you apply the same method as a 2D grid but now you can move in the 3rd dimension as well.

But this is not how most 3D games use A\* because the memory needed for a usable 3D grid becomes too large very quickly. Instead they use **navmesh**es.

Search the web for "**navmesh**"

Blue part is the navmesh:

A\* works on those: each triangle is a node, each edge is a path.

There isn't an up-down-left-right, there are neighboring triangles through edges A-B-C.

---
Tags: 3d, path-finding
---


title: MonoGame in GTK#

text:
# Question
Title: MonoGame in GTK#
I was wondering if it's possible to embed a MonoGame instance not in the standard window, but rather in a GTK# widget. If yes, how could I do it? Do I have to write a custom widget? Is it even better to switch to OpenTK even though it seems quite counter-productive to me?

# Answer
it's possible, but a little trickier than vanilla winforms MonoGame. There's a good tutorial here : http://www.oldschoolpixels.com/?p=390

Switching to OpenTK is not advisable. MonoGame has *a lot* of things that aren't in OpenTK when it comes to texture loading, entity management, etc.

Think of OpenTK as a relatively barebones way to talk to OPENGL from .NET
> 1 votes

---
Tags: c#, monogame, mono
---


# Question
Title: Runescape Private Server - How does it work?
I've seen a lot of Runescape private servers lately. How do they work? Most of them are based on the old Runescape, but a few look exactly like the real Runescape.

How do they make the servers? Has the source code of the game been leaked on several occasions, and is that used to make Runescape servers? Or have some people just replicated Runescape, and tried to make the same game themselves (and "stolen" the 3D objects and texture from Jagex to make it look the same, and written the code to be able to replicate most functions of Runescape)?

# Answer
> 7 votes
Most Runescape Private Servers are coded in the Java language. For the most part, it's been a community effort. From the early days of Runescape classic, there was some leaked source, and from there it's been mostly the community reverse engineering updates as they come. Textures and images are found through URL-Manipulation, and some source code can be found to this day through such methods. Until late, a lot of the game could be analyzed through making a client, and then reading what gets sent to the client by the real Runescape server. Nowadays, you can get a lot of good source code for making your own, from large Runescape Private Server communities. You can get source ranging from a fully developed engine, all the way down to just a simple construct that needs to be fully scripted.

# Answer
> 2 votes
The way they work is based on creating private clients from decompiled (which has deobfuscated & renamed classes) source code of the the original client from Runescape's website. Those who made custom clients can read what kinds of signals are sent to the client and with the knowledge of knowing what is recieved, can replicate similar data from their own server.

Since this method is reverse-engineering the client in order to create a server the algorithms of Jagex's servers are not replicated exactly.

# Answer
> 0 votes
The code it self is Java. Some use a little mysql for rankings, player highscores and mostly for voting rewards. If you do a simple search like "runescape source and client" you will find a lot of code releases. You should start with basics, the early version 317 PI. That is good to get used to the code. Second, you need a good game client, compiled as .jar so everyone can download to play directly from their PC. It's a good practice to make a webclient also, some prefer to play the game directly on browser. To have success you could do some interesting topics on social networks such as Facebook, Twitter and get some decent priced advertising. I would recommend topsites like this RSPS List or similar. You reward your players for voting, rise ranking on top and get some traffic and new players.

---
Tags: java
---


# Question
Title: Command Ordering Architecture of Dwarf Fortress
What is the most elegant way to implement a command ordering system for AI? for example in dwarf fortress when you mark a forested area for wood cutting, the dwarfs then would do the following sequence:

1. Go to the tree
2. Chop the tree
3. Deliver wood to the stockpile
4. Go to another tree
5. and so on..

I already have a stack command working no. 1 which goes from idle state to reaching the destination tile of the tree.

What I'm afraid of is how this would get messy when I create more orders like this:

Build a house

1. Go to stockpile
2. bring wood to construction area
3. go back to stockpile
4. Bring stone to construction area
5. animate building sprite

Planting

1. Go to stockpile
2. bring seed to farm plot

Brewing

1. Go to stockpile
2. Bring plant to still
3. animate brewing sprite

So my question is, how do I implement a command ordering system like dwarf fortress and avoiding spaghetti code at the same time? are there any data structures that I need to study? Do I need to put the command sequence on a separate xml file?

# Answer
At first you see that your commands are in the form of a **list**, so your first instinct might be to recreate that structure, and each dwarf will run through that list in sequence. What I suggest though is to **break the list into steps**, with each step having **prerequisite(s)**, and then you run the entire command **in reverse**. Let me demonstrate with an example:

**Wood cutting**

* Am I carrying wood, and at a stockpile? **Yes**: drop it off
* Am I carrying wood? **Yes**: go to a stockpile
* Am I at a tree? **Yes**: chop it
* **No to all above**: go to a tree

The advantages of this is:

* Very simple to implement
* Flexible - you can freely decompose this list, add items, remove items, combine items
* No state - you can run this list from the top for any dwarf in any state, and the dwarf will just Do the Right ThingTM

Disadvantages:

* It's easy to get stuck in loops, since there is no state and no awareness of being stuck

Logically, you can represent these commands as a flow chart, that is run from the top each time, and what you do depends on whether you answer yes/no at each step. Whether you implement this in code or in an external file like XML is up to you.
> 27 votes

# Answer
If you can make sequences pretty general, there's not much of a spaghetti code.

In case of deliveries e.g.: WorkTask operates with a WorkPlan. Workplan says what kind of resource unit must pick, from what kind of house, using which walk animation, using which work animation, time to work and all such details. So in the end WorkTask might look like:

1. Find %resource1% on map
2. Go to that location using %animation\_1%
3. Work on place using %animation\_2% for %time%
4. Take %req\_resource1% in %req\_count1% count
5. Go to %home% using %animation%
6. Start %animation\_6% inside for %time\_2%
7. etc..

We successfully use described approach. We have ~15 tasks in our game. Some highlights:

* Tasks give unit actions (go there, enter, exit, go here, stay, work, go)
* Action ends with either Done or Aborted state and passes it to the Task
* Everything is hardcoded (no need to write parser, interface methods, backwards compability)
* Each task implements abstract Task class with just a few common methods (create, execute, save, load)
* Generally one task per module, but similar tasks are in one module
* Very similar tasks are within one class and ruled by few IFs (deliver to house or deliver to unit)
* Each task needs a proper locking and unlocking of resources (f.e. if unit dies at ANY step, the resource he locked must be released)
> 11 votes

# Answer
So this is basicaly topographical sorting problem.

You have a graph, each node is a task that needs to be done, and some nodes depend on some other nodes (this is represented by an edge in the graph from depending node to the node it depends on). You want to do all the tasks, so you need to produce SOME ordering of the nodes that is topographicaly OK (the depending nodes are after the nodes they depend on).

Now, there are many such orderings usually (because some nodes have no dependences and can be put anywhere, and some nodes have the same dependences and aren't dependent on each other so they can be in any order between themselves, and any node can be put in any place after it's dependencies are done, and before nodes depending on it are done ).

It's also possible that there are no way to sort a graph topographicaly - this happens when there are cycles in the graph (you have no wood, to get wood you need to chop a tree, to chop tree you need axe, to make axe you need wood). In such case the algorithm should probably indicate to the player that these tasks can't be done.

You can also add priorities to nodes, and the task may be to find such ordering, among all orderings that fullfil the dependencies, that has the bigger priority nodes performed first.

You can also add recuring tasks - the easiest way will probably be to just add the task with timeout again to the graph each time it is done.

Now how to solve it - http://en.wikipedia.org/wiki/Topological\_sorting
> 5 votes

---
Tags: architecture, ai, design-patterns, data-structure, strategy
---


title: XNA SoundEffect won't stop playing

text:
# Question
Title: XNA SoundEffect won't stop playing
For my HND I've got to re-create Frogger, and everything was going swell until I tried adding some collision detection and sound. Whenever my player intersects a vehicle, the sound file just starts playing with every game update instead of just once.

Here is my code from the update method:

```
            if (vehicles[count].bbox.Intersects(playerSprites[lives].bbox))
                playerSprites[lives].isDead = true;
        }

        if (playerSprites[lives].isDead)
        {
            deathSound.Play();
        }

```

The sound is declared as a SoundEffect, loaded as a SoundEffect, and the content processor is set to Sound Effect, and as far as I can tell, Sound Effects in XNA are only meant to be played once. What am I doing wrong??

# Answer
> 1 votes
Notice that you are launching a sound effect **while** the player is dead, not **when** the player died. The obvious solution would be to call your soundEffect.Play here:

```
if (vehicles[count].bbox.Intersects(playerSprites[lives].bbox)){
  playerSprites[lives].isDead = true;
  deathSound.Play();
  //and also disable further intersection tests with player bbox to launch this function
  //only once. You could modify it so that its area becomes zero
}

```

---
Tags: xna, xna-4.0, audio, bounding-boxes, sound-effects
---


# Question
Title: Algo for Minimum no of solving in a level like Bubble Blast2
Is their any way to make a algo to know minimum no of way to solve in Bubble Blast 2. I am trying to make a clone of it. My real problem is only to determine the minimum no of tap to finish the game. I can play and find them but if level are more then 100 , it is time consuming . In Bubble Blast 2 there are 10000+ levels. So is there any way to solve this problem?

# Answer
> 1 votes
One way to do it with puzzle games is to start from the end and create the level in reverse.

This has the added bonus that all your puzzles are guaranteed solvable.

Finding the absolute minimum number of steps might be good for a university paper but you don't need to find it for a good game. Players love finding better ways to solve the puzzle. The ego boost adds to the fun.

Sounds like I'm dodging the question but since this is game development rather than computational science (https://scicomp.stackexchange.com/) the most important thing for games is "Is it going to be fun?" over "Is this the perfect solution?".

Cheers,

# Answer
> 1 votes
It seems to me that you could simply have your program brute-force this at level creation time, and save the answer with the level description.

If your grid is 5 x 6 as in Bubble Blast, there are at most 30 choices for the first tap, and the number of options drops rapidly past that (outside of pathological cases, that is). No chain can possibly use more than 30 taps, and in practice most will take far fewer. So you can try every sequence of valid taps (ie. taps on non-empty cells) and note the shortest sequence to an empty board.

Once you have a sequence of length x, you can abandon any sequence of length x that is still ongoing - it can't possibly give you a shorter path.

You can gain a bit of efficiency by taking a recursive dynamic programming approach, caching recently used game states. Each time a tap from state A would result in a particular game state B, you check to see if state B is already in your cache. If so, the number of taps for completion of A is the number for B + 1. If not, you recurse on B and add it to your cache with the number you find. This way you avoid repeated work for game states that appear frequently in the game tree.

You can also optimize this cache by aliasing similar states. eg. every state with only a single item, or up to three items of the same colour in a row/column, can always be cleared in one tap, so they can be treated as one. Similarly, the orientation/reflection of the board or particular colour identities don't matter, only colour differences, so you can make your cache indexing insensitive to these irrelevant details.

The maximum cache size could still theoretically exceed your total memory (depending on how varied your levels are), so you'll want to throw out entries that haven't been referenced recently.

If you run this program as a batch over all your levels at once, and persist the cache from one to the next, you'll get additional savings anytime a group of levels shares some intermediate states.

---
Tags: algorithm, level-design, levels
---


# Question
Title: Calculate slope for linear interpolated movement
I want to move rectangles to their targets the "smooth" way with linear interpolation. I hope this is right.

```
float slope(float x1, float x2, float y1, float y2) {
    return std::abs((y2 - y1)) / std::abs((x2 - x1));
}

int s = slope(x, target->x, y, target->y);

if(x > target->x) {
    x -= s * speed * delta;
} else if(x < target->x) {
    x += s * speed * delta;
}

if(y > target->y) {
    y -= s * speed * delta;
} else if(y < target->y) {
    y += s * speed * delta;
}

```

The result is that they barely move. But when they move it is very slow or fast as hell. I would also apreciate any suggestions on how to reach the target better. Thanks in advance.

# Answer
> 3 votes
simple solution using a uniform vector:

```
float dx = target->x - x;
float dy = target->y - y;
float dist = std::sqrt(dx*dx+dy*dy);
if (dist > speed * delta) {
    dx /= dist;
    dy /= dist;
    x += dx * speed * delta;
    y += dy * speed * delta;
} else {
    x = target->x;
    y = target->y;
}

```

---
Tags: c++, mathematics, vector, sdl
---


# Question
Title: Z axis for player movement is being incremented, but i don't know how
I'm currently learning and developing a 2D plataform game in Unity, but now i'm having some errors that i can't solve.

When I press the arrow keys to make my character move right and left, the Z axis is being incremented somehow,and the player is "getting into the screen", even though I didn't write anything about it in my script.

I read about the "Apply Root Motion" in the Animator segment, and I unmarked it as they said, but I think the error might still be there, but i'm not sure.

Does anyone know about it?

Here is a snippet of my code:

```
void Movement() {
    anim.SetFloat ("speed", Mathf.Abs (Input.GetAxis ("Horizontal"))); //Makes it record a value of speed between -1 and 1, so that the trigger of the animation can work.

    if (Input.GetAxisRaw ("Horizontal") > 0) {
            transform.Translate (Vector3.right * speed * Time.deltaTime);//speed * Time.deltaTime makes things smoother, it updates frame by frame, so that it does not jump all around
            transform.eulerAngles = new Vector2 (0, 0);
    }

    if (Input.GetAxisRaw ("Horizontal") < 0) {
            transform.Translate (Vector3.right * speed * Time.deltaTime);
            transform.eulerAngles = new Vector2 (0, 188);
    }

```

# Answer
I'm gonna make a wild guess that you are using 3D colliders.

Check out the colliders of your character and make sure you froze rotation and Z transformation so that your character will not rotate or bounce in Z direction upon a collision.
> 1 votes

---
Tags: c#, unity, game-mechanics, platformer
---


title: Java JBullet Mesh collsion problem

text:
# Question
Title: Java JBullet Mesh collsion problem
I have a problem with JBullet mesh collsion. Everything works fine when I create a mesh from my object without scaling, but the problem starts when I want to scale the object. I also tried scaling in Blender, but it has the same problem. Here is my code for creating a mesh from an object:

```
    int numtriangles = mesh.vertices.length / 3;
    int numverts = mesh.vertices.length;

    ByteBuffer indexBuffer = BufferUtils.createByteBuffer(numverts * 3 * 4).order(ByteOrder.nativeOrder());
    indexBuffer.clear();
    for(int i=0;i<numtriangles;i++) {
       indexBuffer.putInt(i);
       indexBuffer.putInt(i);
       indexBuffer.putInt(i);
    }

    ByteBuffer geometry = BufferUtils.createByteBuffer(numtriangles * 3 * 4).order(ByteOrder.nativeOrder());
    geometry.clear();
    for(int i=0;i<numtriangles;i++) {
       geometry.putFloat(mesh.vertices[i].getPos().x);
       geometry.putFloat(mesh.vertices[i].getPos().y);
       geometry.putFloat(mesh.vertices[i].getPos().z);
    }

    geometry.rewind();
    indexBuffer.rewind();

    TriangleIndexVertexArray trimesh = new TriangleIndexVertexArray(numtriangles, indexBuffer, 3 * 4, numtriangles, geometry, 3 * 4);
    BvhTriangleMeshShape shape = new BvhTriangleMeshShape(trimesh,true);
    return shape;

```

My scaling was something like this:

```
    for(int i = 0; i < vertices.length; i++) {
        Vertex acc = vertices[i];

        Vector3 pos = acc.getPos();
        pos.x *= scale.x;
        pos.y *= scale.y;
        pos.z *= scale.z;
        acc.setPos(pos);

        Vector2 tex_coord = acc.getTexCords();
        tex_coord.x *= scale.x;
        tex_coord.y *= scale.z;
        acc.setTexCords(tex_coord);

        vertices[i] = acc;
    }

```

The problem is when I scale the object, it no longer collides with other objects.

# Answer
> -1 votes
The scaling looks fine, but the calculation of indices doesn't look correct. I think it just happens to somewhat work by accident when the objects are small enough. This code:

```
for(int i=0;i<numtriangles;i++) {
   indexBuffer.putInt(i);
   indexBuffer.putInt(i);
   indexBuffer.putInt(i);
}

```

adds the same vertex index three times for the triangle meaning that only the first 1/3 of the vertices are referenced. As you are not sharing vertices between triangles, perhaps the code should be:

```
for(int i=0;i<numverts;i++) {
   indexBuffer.putInt(i);
}

```

Note that you probably don't want to scale the texture coordinates, although that doesn't matter for physics. Also the scaling code redundantly assigns the modified vertex back to the array even though in Java the variable is just a reference and you are modifying the original data. This should be enough:

```
for(int i = 0; i < vertices.length; i++) {
    Vertex acc = vertices[i];

    Vector3 pos = acc.getPos();
    pos.x *= scale.x;
    pos.y *= scale.y;
    pos.z *= scale.z;
    //acc.setPos(pos); // This is not needed either if getPos() doesn't create a copy. Most likely it doesn't.
}

```

---
Tags: java, lwjgl, bullet-physics
---


title: Resizing D3D Buffers within a frame

text:
# Question
Title: Resizing D3D Buffers within a frame
I have a particle system. So far it worked like this: I have a dynamic vertex buffer for a system, which is created with a size that can hold for example 100 000 particles. I map/unmap this and write the new data into it every frame.

But what if the particle count gets bigger than the buffer can hold? I thought of recreating the vertex buffer with the double of its previous capacity (then map/unmap into it). Is this the right direction for this or should I solve it in a different way?

A short example:

```
ID3D11VertexBuffer* buffer;
ID3D11Device*       graphicsDevice;
//...
D3D11_BUFFER_DESC desc;
buffer->GetDesc(&desc);
if(dataSize>(int)desc.ByteWidth){ //data can't fit, so destroy and recreate
    buffer->Release();
    desc.ByteWidth*=2;
    graphicsDevice->CreateBuffer( &desc, nullptr, &buffer ); //returns S_OK
}

```

Update:

I want to use it for other things, not just particles but for example instanced meshes. If I spawn a couple of instances, I'd only like to resize a buffer, without creating an other one.

# Answer
> 1 votes
If your particle count is bigger than the buffer can hold then your best option is to draw in two batches:

* Draw a first batch of particles that fill the buffer
* Draw a second batch of anything left over

That can extend to any arbitrarily high particle count (just add more batches) and avoids the overhead of runtime resource destruction and creation (which can be expensive since D3D11 performs validation at creation time).

---
Tags: directx11
---


# Question
Title: How to compute the forward facing direction from three angles and then translate along it?
Given:

```
float yaw, pitch, roll;

```

How does one compute the forward direction:

```
vec3 forward = computeForwardFromEulers(yaw, pitch, roll);

```

Next, I would like to use this information to translate an object along this axis / heading / forwardDirection.

```
// move 1 unit forward
forward.?? = 1.0f?

```

# Answer
https://stackoverflow.com/questions/1568568/how-to-convert-euler-angles-to-directional-vector

This should answer the first part of your question. A simple google search gave me this result.

For translating, you want to multiply the *direction* you want to move by the *length* you want to move. So, if you want to move forward by 5.0 units, you would write:

```
position = position + forward * 5.0

```

This will move you towards forward by 5.0 units. You can do this with any directional vector:

```
position = position + GlobalUpVector * 2.0

```
> 1 votes

---
Tags: camera, rotation
---


# Question
Title: JavaScript THREE.js webgl spotlight rendering
I'm playing with webgl/JavaScript/THREE and a spotlight. And I see unexpected results. And I don't understand what's going on, and I'm hoping you can point me in the right direction. In my particular case, the bizarre behavior is when the spotlight is behind the character, but the light is rendered as it's coming from the front. I apologize, I think it's best if you take a look here to see what I mean

http://dhkgames.com/games/redshifted

. Please note that in my tests This website worked in chrome and Internet Explorer, but for some reason not in Firefox. Also, please be patient, the test website is hosted in Singapore, so it may take up to one minute onto the character is downloaded and rendered in the middle of the screen

. What I'm interested in is to understand if the spotlight works as designed, or maybe I can update vertex/fragment programs. As a secondary goal, in the spotlight The pants and the jacket material renders somehow differently, and once again I'm not sure why, so if you have some pointers for this as well It would be much appreciated!

. Lastly, I apologize for misspellings, my arms and eyes don't work very well, and I use voice recognition software to interact with my computer…

. Thanks!

# Answer
> 0 votes
it seems that I was missing the following line in my code

```
player.scale.set(1,1,-1);

```

---
Tags: javascript, webgl, three.js
---


# Question
Title: Methods to remove horizontal world slices of voxels in a 3D voxel world
I've recently been working on a hobby voxel world recently.

I'm currently interested in ideas or solutions which would enable me to basically step up and down the Y-axis 1 horizontal block slice at a time, effectively making all upper horizontal slices transparent so that I can see objects/terrain/units under the earth.

\[A quick visual attempt at describing the problem\] I've done a bit of googling on the subject but perhaps I'm not describing the problem set correctly because I'm unable to find anything satisfactory.

Goals :
1.) I dont' want to have to recreate the chunk meshes across the entire world everytime I step up and down the Y-axis blocks. It would destroy performance and probably crash Unity.
2.) Reasonably optimized quick stepping up and down the Y-axis i.e. no perf drops.

I know that a few options must be out there as I've seen examples in other engines and games (Byte56's Age of Goblins tech demo and Gnomoria etc). I'm guessing an algorithm via some magic shader math would be perfect.

All ideas greatly appreciated!

# Answer
When I implemented this, I had hoped to do it all via the shaders. I planned on just passing a global Y coordinate into the shader and having the geometry shader just flatten all the terrain geometry above that Y coordinate to flatness. This works great if your game doesn't have any overhangs or caves, though this is unlikely with a voxel terrain.

What I ended up doing was a combination of shader and new geometry. I used the shader to remove all the vertices above the "slice level". This leaves a hole in the terrain wherever terrain has been removed, which is where the new geometry comes in. Like you I didn't want to have to rebuild chunks, so I just built a cap. Each chunk was responsible for building a terrain cap at the slice level. This was much faster than recomputing and building a whole chunk since it only needs to happen at one layer.

The two steps are:

1. Use geometry shader to discard all geometry vertices above your slice point.
2. Build a new mesh for each chunk that caps the sliced terrain.

Additionally, in my case I didn't want the player to see caves that hadn't been discovered yet. I implemented a feature where only 'air' cubes that were connected to the outside world would be visible. This was done at terrain generation time. I'd walk all the cubes connected to sky and mark them as 'found' along with any solid cubes touching that air. Whenever mining happened I'd start a new walk from that location to see if it reviled any 'hidden' pockets (like caves).

Any cubes that were not found show up as a black void texture. Where the found cubes would have the texture appropriate to their material type.

This was all done with a custom build engine. I haven't used shaders in Unity so I'm not sure what pointers to give you for implementing this in Unity.
> 1 votes

---
Tags: c#, unity, game-design, voxels
---


# Question
Title: How to increase the selectable size of an object for dragging
I am currently dragging a gameobject like this.

```
   Vector3 screenSpace;
   Vector3 offset;
   void OnMouseDown(){

 //translate the cubes position from the world to Screen Point
 screenSpace = Camera.main.WorldToScreenPoint(transform.position);
 //calculate any difference between the cubes world position and the mouses Screen position converted to a world point
 offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y, screenSpace.z));
 }

  private float speed = 7.5f;

  void OnMouseDrag(){
     Vector3 curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y,    screenSpace.z);
     Vector3 curPosition =  Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;
     transform.position = curPosition;
 }

```

Sometimes a user doesn't click directly on an object so is there a way that if a user is between 3-7 pixels off, it still counts as a click and drag? Any help is appreciated.

# Answer
> 0 votes
The `OnMouseDown` method works when Unity casts a ray into the scene from the camera position towards the cursor position when mouse button is pressed. If the ray hits a collider, like the one attached to your object, it will call the `OnMouseDown` method for that object.

This means there's no way to buffer the click radius of the object in relation to its size on screen. The click detection is controlled by the collider of the object. So, if you want to increase the clickable area around the object, without changing the visual size of the object, you need to increase the size of the collider.

---

There is another alternative. You can implement your own click system, and use the `SphereCast` method instead of the build in ray cast that Unity uses behind the scene. The sphere cast is similar to a ray cast except it is larger than a ray. Any object inside the sphere's cast radius will be returned as a hit object. I created a video course for Unity, and the ray casting video is one of the free videos to watch.

That'll give you an idea how the casting works. The Mouse Input video also covers casting a ray from the camera into the world.

---
Tags: c#, unity
---