title: Creating a hostile Mob

text:
# Question
Title: Creating a hostile Mob
So I'm currently developing a 2D top down view java game. I have a mob called "Mutant" that currently does nothing. It generates a random number and depending on that number moves a few pixels in that direction. I"m trying to figure out how to make the mutant follow the player's x & y coordinates when the player comes near.

Here is what my mutant does currently:

```
    int xa = 0;
    int ya = 0;
    move = generator.nextInt(50) + 1;

    if(move == (50))
        ya = (random.nextInt(3) - 1) * random.nextInt(2);
        if (!hasCollided(xa, ya))

    if(move == 40)
        ya = (random.nextInt(3) - 1) * random.nextInt(2);
        if (!hasCollided(xa, ya))

    if(move == 30)
        xa = (random.nextInt(3) - 1) * random.nextInt(2);
        if (!hasCollided(xa, ya))

    if(move == 20)
        xa = (random.nextInt(3) - 1) * random.nextInt(2);
        if (!hasCollided(xa, ya))

    if(xa != 0 || ya != 0) {
        move(xa, ya);
        isMoving = true;
    } else {
        isMoving = false;
    }

```

Does anyone know how to make the mob simulate hostility towards the player? I haven't implemented a health system yet, I've only worked on the mob's A.I.

# Answer
> 1 votes
A very simple solution might be to compare the mutant's x and y position to the x and y position of the player.

```
Example: Player at {10, 10}, Mutant at {0, 0}

if (mutant.x < player.x)
    mutant.x += amountToMove;
else if (mutant.x > player.x)
    mutant.x -= amountToMove;

if (mutant.y < player.y)
    mutant.y += amountToMove;
else if (mutant.y > player.y)
    mutant.y -= amountToMove;

```

This would always move the monster towards the player, but you may need to split the amount to move between the x and y axis so it doesn't move more quickly in a diagonal direction than in a pure vertical or horizontal motion.

```
totalDistance = xDistance + yDistance;
xSpeed = amountToMove * (xDistance / totalDistance); //uses proportion of xDistance to set proportion of speed.
ySpeed = amountToMove * (yDistance / totalDistance); //same for yDistance

```

# Answer
> 1 votes
The mutant can acquire a reference to the player at a certain range. For example, every frame (or less frequently) the range between the mutant and the player can be checked. When the mutant is within a specific range, the mutant can acquire the player as target.

How to represent that is up to you, but a short version could be:

```
bool isHostile = true
Entity target = player

```

or maybe a temporary solution:

```
int targetX = player.x  // needs updated every frame, as player moves
int targetY = player.y

```

After the mutant has the player as a target, the mutant can movement can head towards the player. A piece of math called a "normalized vector" is useful for figuring out how much to move in a given direction. Without a normalized vector, you'll run into the classic problem of having a game where diagonal movement is significantly faster than left/right or up/down movement. Here is some pseudocode for determining the direction to move, and how much to move:

```
  // xDiff and yDiff would be the length of the line between mutant and player
  var xDiff = target.x - npc.x
  var yDiff = target.y - npc.y

  // unitVector is a line which is 1.0 units long and points from mutant to player
  var unitVector = math.normalizeVector(xDiff, yDiff)

  // move along the line from mutant to player
  npc.x += unitVector.x * npc.speed * delta
  npc.y += unitVector.y * npc.speed * delta

```

In the above code, target would be the player, and npc would be your mutant. You can ignore/remove the delta for now, and also type in some test numbers for speed -- but it may be something for later, a topic called "frame independent movement."

The approximate math for normalizeVector is:

```
  length = Math.sqrt((x * x) + (y * y))
  var xComponent = x / length
  var yComponent = y / length

```

This will convert an x,y movement of \[+1, +1\] into something like \[0.707106781186547, 0.707106781186547\] which is an ugly set of numbers but carries the correct amount of movement. I'll note that this particular equation will hit an error if x and y are both 0 (it'll divide by zero). If you're using a math or game library it may already have a function like this.

# Answer
> 0 votes
As DoubleDouble said, then you can layer more complex behaviours on top, for example:

* Limited sense range, e.g. only attacks the player if they are nearby or ahead of the mob.
* Play a sound, animation and/or change the movement style when the player is seen to give feedback to the player.
* Predict the player's future position based on their current velocity.
* A simple state machine, e.g. monster patrols or acts randomly until the player is seen.

---
Tags: java, software-engineering, ai
---


# Question
Title: How to properly handle attacks in an 2D Platformer?
I am building an 2D Engine in JavaScript and if my actor attacks an enemy, a hitbox appears for a certain amount of time and then disappears. If the target keeps standing inside of the hitbox he gets drained down for each frame. So for example if the hitbox does 3 points damage and the target only has 9 HP he will be dead after 3 frames. That's too fast.

I've come up with two solutions, both of them are not ideal:

1. Set the enemy as unattackable for a certain amount of time after each hit.
2. Save an reference to the enemy that gets deleted after the hitbox disappears.

My explanation is pretty bad but posting my code would be worse since it's way too much.

# Answer
Your option 1 (invulnerability timer) is what many classic (and even modern) games do.

A variant of your option 2 is a better approach in some respects, though "better" depends on your desired gameplay (some games actually depend on the invulnerability timer mechanics for puzzle solving or the like, though IMO that's horrible). Especially if you have multiple players or the like, letting each damage the enemy simultaneously can be nice. The basic gist is for each attack state to simply store a list of objects it hit and the times. You can then ignore all further collision detections for that attack or have a per-attack timer (for attacks that are supposed to do damage over time). This list could be per-attacker rather than per-attack if that makes it simpler.
> 1 votes

# Answer
Depending what you consider ideal and the nature of your engine / update loop, the actor's attack hitbox could be present for exactly one frame. After the actor attacks, it could then be subject to a period of recovery before attacking again.

This method would come with the following behavior:

* player attacks once when hitting a key or clicking the mouse
* any or multiple creatures within the player's attack are hit
* the player then must wait for stamina or attack cooldown (or whatever) before attacking again

Some things to consider about this method:

* by default, the attack would be calculated at the beginning of the attack animation
* to make the attack appear to have duration, the attack animation would need to begin, and then a few frames later the attack hitbox would be placed and used
* this form of attack cannot 'move' across the screen like a projectile (though it would be fine for something like a laser)
> 0 votes

---
Tags: collision-detection, javascript
---


# Question
Title: Why do I get an exception when accessing my sprite members in this fashion?
I'm getting a `NullReferenceException` error on the line where I do `new Vector2(...)`.

I think the problem is with the variables I'm using even though they're working to control the player sprite, so surely they can't be null, right? That is, however, in a different class and is initialized at the top of this one.

Here is the method in question:

```
public void Shoot()
{
    //if bullet delay resets then shoot
    if (bulletDelay >= 0)
        bulletDelay--;

    //if bullet delay is 0 then create a bullet at player bulletPosition
    if (bulletDelay <= 0)
    {
        //Here I create the new bullet passing in the texture and then modifying the bulletPosition were the bullet will appear from
        bullets newBullet = new bullets();
        bulletPosition = new Vector2(mySprite.imgX, mySprite.imgY);

        newBullet.isVisible = true;
        //These two lines mean that you can have no more that 20 bullets on screen at once
        if (bulletList.Count < 20)
        {
            bulletList.Add(newBullet);
        }
    }

    //reset bullet delay
    if (bulletDelay == 0)
        bulletDelay = 10;
}

```

`bulletDelay` is so the player can't spam the shoot button and have it be too easy. I tried to add a breakpoint on that line, when I run the program and hit the space bar that runs the `Shoot()` method the program stops and tells me about the error. When I hover over though it still says they are null.

I had the instances of the classes in the following code below. I've changed it so they are in the Shoot() method and all seems to well however I'm curious as to why the below code wasn't the correct way to do it:

```
public void Initialize()
{
    mySprite = new PlayerSprite();
    bulletList = new List<bullets>();
}

```

# Answer
> 1 votes
The only possible sub-expressions on the line in question (`bulletPosition = new Vector2(mySprite.imgX, mySprite.imgY)`) are in the access of `mySprite`, which means that when that expression is executed, `mySprite` is null.

Even though you might see code elsewhere in your program that initializes a variable called `mySprite`, that may not fix the problem for any of the following reasons (and more):

* That `mySprite` may be a complete different variable than the `mySprite` you are currently accessing.
* That variable might be the same class member, but you might be initializing one instance of the class and not another, and the crash is occurring when `Shoot` is called for the latter instance.
* The code might be initializing the proper variable for the proper instance, but is never called for one reason or another.

And so on. There are really several reasons this can happen, and walking through all possibilities isn't really viable here.

The *correct solution* is to ensure that `mySprite` is non-null before you access it. The way to arrive at that solution is to learn how to use your debugger to do things like set breakpoints and examine the state of variables, as well as to understand the context of your code and the differences between objects and their types.

---
Tags: xna, c#, 2d
---


# Question
Title: Why would a borderless full-screen window stutter occasionally?
I want to be able to allow players to switch between full-screen, windowed, and full-screen-with-a-borderless-window rendering modes. The last mode, borderless is an important one lots of players, myself included.

I have noticed that my game will stutter a little bit in borderless windowed mode. It's not terrible, but choppy gameplay can get slightly annoying and I want to it to be as smooth as it is in full-screen. I know other games have always had some issue with being borderless. I just figured since my game isn't that intensive I shouldn't see much of problem.

I am using David Amador's "XNA 2D Independent Resolution Rendering" code. The trouble comes when I create my gameplay screen and use the following code to create a borderless window:

```
Form gameForm = (Form)Form.FromHandle(curGame.control.Handle);
gameForm.FormBorderStyle = FormBorderStyle.None;

```

If I have it set to fullscreen through Amador's `Resolution` class then this borderless code doesn't seem to do anything at all. If I have it set to windowed it does work as expected and creates a borderless window. The only problem is that strange choppy behavior.

In full screen it doesn't lag one bit so I'm wondering if there's some issue with how the borderless code works. Is how I'm doing a borderless window correct? Am I just going to have to deal with a little bit of stuttering in that mode?

# Answer
You are seeing a performance difference due to the fact that in *actual* full-screen mode, you get exclusive access to the GPU for that adapter, so you won't have to content with any other process for that particular resource.

This may be slightly faster, but mostly it is just more predictable (and thus smoother), since nothing else will be allowed to make requests of the GPU that would cause it to hold any kind of lock on any resource or any kind of pipeline stall.

Those sorts of unpredictable, out-of-your-control demands are the cause for your occasional stutters when in full-screen windowed mode. It's akin to how loading all your game data from your disk will take longer if there is also another program (like a virus scanner) poking around at all those same files at the same time.
> 2 votes

---
Tags: xna, c#
---


# Question
Title: Algorithm for continuously generating a tile map for a topdown 2D game?
In essence, what I'm looking for is a procedural 2D tilemap continuously generated in a fashion like Minecraft - which is to say generated as the player approaches the edges of the already explored parts of the map. Map is going to be for a topdown 2D-shooter and the purpose of the map is mostly just for background and determining types of enemies and loot to spawn, so it really doesn't need to be very complex.

I've already researched some into the topic, but most of the answers have honestly been a bit too complicated or seemingly made for pregenerated maps. Voronoi Diagrams and Simplex Noise, while impressive, I don't really understand how to implement in a continuous fashion in realtime. Or at all, really.

What I'm imagining with the generator would be to create simple biomes, composed of two values determining its 'artificiality' (i.e. how man-made the biome is) and 'life' (which is how populated it is). An example would be a city, with high values of life and artificiality both. The values for each would be skewed towards that of its neighbour to ensure that you don't have completely random values. It'd probably be a good idea to ensure that a 'biome' doesn't get too large too, by limiting the amount of tiles?

My question is, are there any better or simpler algorithms to use for something like this beyond Voronoi and Simplex? The game is programmed in C#, I feel I should mention.

# Answer
> 3 votes
Maybe Midpoint Displacement might work for you? The algorithm is a bit simpler than simplex, but you might have to tune it a bit to get rid of artifacts in the result.

The linked article does the full explanation better than I could, but the general idea behind it is this:

1. Assign random values to the four corners
2. In the middle between those, average the neighbor values and add/substract some "error" for randomness
3. Repeat for new midpoints until the map is filled.

This should give you a good map of random values, and with some tinkering you should be able to connect several chunks of it by using the values of one edge to start the next chunk and so on. If you need to, you could create two maps, one for "life" values and one for "artificiality" values and combine them.

# Answer
> 1 votes
Simplex noise is pretty much the standard in this scenario. If it seems too complex for you, you have two options:

**1. Find the time and put some effort into understanding it,**

**2. Look for an existing implementation and adjust it to your needs.**

I would really suggest the first one, but I can understand that it seems overwhelmingly difficult at first glance.

So let's talk about option 2. There's a project on code.google.com: simplexnoise project The noise generation itself is in the Noise.cs file. Indeed, it looks complex. There's a test application also (see Form1.cs), which shows you how to use the `Noise` class to generate an output in real-time.

Since **there is no existing solution for your exact needs** (biomes, cities etc.), you should play with this test application, poking it, to see what happens if you change certain constants. I'd suggest even creating multiple layers of noise, applying them over each other, adding filters and so on. This way you could simulate environmental variables that are independent from each other (for example, terrain elevation vs. population density).

I know from my own example that learning while 'playing' is very effective. You will eventually learn how this whole noise thing works, and you will get a clearer idea of how to implement it in your own game.

---
Tags: c#, 2d, procedural-generation, tilemap
---


# Question
Title: How can I improve the rendering speed of procedurally-generated curved shapes (while keeping them smooth)?
I'm trying to render a large, procedural-generated shape with OpenGL, but I'm having some issues. I'm rendering the shape by composing it from many cubes, as follows:

```
int TRACK_MIDDLE2 = 107;
for (GLdouble i=0.00; i<2*M_PI;i+=0.001) {
    x = TRACK_MIDDLE2 * sin(i) + 0.5;
    y = TRACK_MIDDLE2 * cos(i);
    glPushMatrix();
    glTranslatef(x, y, -size - 0.4);
    Cube c2(size);
    c2.render(grey, dgrey);
    glPopMatrix();
}

```

The `Cube` render code looks like this:

```
glBegin(GL_POLYGON);
glColor3fv(c1);
glVertex3f(-size, -size, size);
glVertex3f(size, -size, size);
glVertex3f(size, size, size);
glVertex3f(-size, size, size);
glEnd();

glBegin(GL_POLYGON);
glColor3fv(c2);
glVertex3f(-size, size, size);
glVertex3f(size, size, size);
glVertex3f(size, size, -size);
glVertex3f(-size, -size, -size);
glEnd();

glBegin(GL_POLYGON);
glColor3fv(c2);
glVertex3f(-size, -size, -size);
glVertex3f(size, -size, -size);
glVertex3f(size, -size, size);
glVertex3f(-size, -size, size);
glEnd();

glBegin(GL_POLYGON);
glColor3fv(c2);
glVertex3f(-size, -size,-size);
glVertex3f(-size, -size, size);
glVertex3f(-size, size, size);
glVertex3f(-size, size, -size);
glEnd();

```

This is the result image:

It looks visually correct, but it renders very slowly. If I decrease increment of `i` in the for loop, I loose out on the "smoothness" of the shape, which is undesirable.

How can I improve the rendering speed of this mesh?

# Answer
> 7 votes
Your performance problems are likely coming from the shear number of draw calls you are making. Each "step" in your track parameterization is a distinct draw call (of a cube) using old, inefficient `glBegin`/`glEnd` "immediate mode" pairs to render each face.

This in efficient first because of your use of immediate mode, but also because you are just submitting tons of redundant geometry in very tiny batches. It's better to make fewer draw calls with larger batches of geometry, because that will balance the load on your CPU and GPU more evenly and avoid much of the overhead associated with state transfer in each draw call.

Modern OpenGL uses buffer objects. You will want to modify the parameterization of your track slightly so that instead of making a new cube for every step of the parameterization you generate the final vertices directly (so you won't be using the matrix stack manipulation functions either) and write those into the memory buffer that will back your vertex buffer object.

Then you render that vertex buffer object in a single draw call.

To familiarize yourself with buffer objects (in addition to the documentation I linked above), there are several tutorials online. A quick search turns up this one and this one, for example. A good read on modern OpenGL can be found here, as well.

---
Tags: opengl
---


title: Effectively drawing dynamic primitives

text:
# Question
Title: Effectively drawing dynamic primitives
Okay, so this is where I am now. My game largely consists of textures drawn through spritebatch. Now I have to draw a dynamic number of triangles. I cannot say in advance where or how many I have to draw, because I have to generate their positions on the fly. The number will never top 3-400 though, and is often much lower.

When testing though, I noticed that at random moments the game became a bit laggy. I'm quite confident the vertex-drawing was the problem, if I commented it out, the lag was gone.

This is the code I have currently (I removed as much clutter as possible):

```
// loop through the grid
    VertexPositionColor[] vertices;
    int vertexcounter = 0;

    RasterizerState state = new RasterizerState();
    state.CullMode = CullMode.None;

    for(int i = startx; i < endx; i++)
        for (int j = starty; j < endy; j++)
        {

            //////
            vertices = new VertexPositionColor[3];
            vertexcounter = 3;
            vertices[0] = new VertexPositionColor(Vector3.Zero, Color.Black);
            vertices[1] = new VertexPositionColor(new Vector3(width / 2, 0, 0), Color.Black);
            vertices[2] = new VertexPositionColor(new Vector3(0, height / 2, 0), Color.Black);
            //////

            // Create a buffer to use
            vertexBuffer = new VertexBuffer(device, typeof(VertexPositionColor), vertexcounter, BufferUsage.WriteOnly);
            vertexBuffer.SetData<VertexPositionColor>(vertices);

            // Draw the triangles
            basicEffect.World = world;
            basicEffect.View = view;
            basicEffect.Projection = projection;
            basicEffect.VertexColorEnabled = true;

            device.SetVertexBuffer(vertexBuffer);
            device.RasterizerState = state;

            foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
            {
                pass.Apply();
                device.DrawPrimitives(PrimitiveType.TriangleList, 0, vertexcounter / 3);
            }

            vertexcounter = 0;
            vertexBuffer.Dispose();
        }

```

Again, I removed as much clutter as possible. The basicEffect and matrices are created in the constructor. The for loop doesn't really make sense probably, but the part between the ////'s used to be for retrieving the vertices from objects in a grid (which is what the coordinates were for).

As you can see I removed that part and instead draw one single triangle. The game still lags though, so I think I'm doing something else wrong. Are you not really supposed to create VertexBuffers on the fly? Or am I forgetting to dispose of certain data?

Also, maybe it is worth noting that this is done in the Update part of the object. This is because the image is drawn to a RenderTarget, and in my project it's just more convenient to do it in the Update method.

Thanks in advance :)

# Answer
> 3 votes
You are generating a lot of garbage and doing a lot of excess driver calls in those loops.

Things like `new VertexPositionColor[3]` has to perform a heap allocation that the GC must then clean up. Ensure that every type you call `new` on in a loop is a struct. Be aware that things like `foreach` have to create a new enumerator object which may be a class type and heap-allocated (I don't know about the specific types you're using in your loop here; you have to check yourself, or just use integer indices).

If you need a temporary bit of heap-allocated memory, pre-allocate it and store it in a class member for reuse rather than re-allocating every time. For instance, that small array you create inside your loops could easily just be a member of the containing class on only `new`'d up once.

You're also wasting a lot of driver and hardware time creating new vertex buffers inside of an inner loop. You don't need to recreate vertex buffer (especially one with a fixed size). Create once and reuse it.

You can also combine those draw calls. The draw code you have now likely won't cause intermittent pauses but it will be generally slow as molasses. You're using the same shader and material properties for every triangle. Instead of drawing one triangle at a time, push them all into one single buffer and draw them in one pass. You can have a `List<VertexPositionColor>` (remember to only create it once and to clear/reuse it each time you need to draw a set of tris) and your loops can just push vertices onto that. Then at the end copy it into a vertex buffer and call draw.

---
Tags: xna, c#, graphics, vertex
---


title: Marching cubes and LoD

text:
# Question
Title: Marching cubes and LoD
I have and octree based world constructed (on the start) via marching cubes with certain density function to make a terrain (variations on noises). The terrain is rater smooth, it is not like minecraft blocky terrain at all. The deepest level of LoD is 12 and on this level (let's say) player is moving. The player have an ability to place blocks (just like in minecraft) and dig holes (block-like) in terrain. The blocks are stored as an overrides to density function so that the rendering algorithm looks if there's an override for each point of the certain marching cube block, and if there is, it constructs solid block, or hole there. Pretty simple.

The question is, what technique of LoD do you recommend, when I move away from the certain place where I have put my blocks to sustain details on lower LoD levels as much as possible?

I can see two ways there:

1. Render the terrain separately on each LoD and custom geometry (blocks) leave as they are. What this means is that my terrain will contain all blocks I placed rendered on LoD 12 while the terrain will be on appropriate LoD. This will lead to resource drain because all my custom blocks need to be rendered with maximum detail not depending how close I am to them, but on the other hand my house I built will look as house from the distance.
2. Just interpolate weights when switching to lower LoD level. This will be fast, but it will change how my blocks look (or should I say it will change a lot how looks whole my construction) drammatically - if I make a house from blocks and move away, my house won't look as house anymore.

# Answer
> 5 votes
From what I can tell there are two major requirements for your terrain that Marching Cubes (MC) simply cannot fulfill:

1. Sharp edge rendering
2. Chunked LOD

I'd recommend the Dual Contouring (DC) algorithm, which handles both cases quite gracefully, and as a bonus is able to optimize chunks with fewer features to use fewer triangles. There is an often-cited paper on the subject here.

http://www.cs.rice.edu/~jwarren/papers/dualcontour.pdf

The main difference between MC and DC is that DC operates on *Hermite data*. In the context of terrain rendering, there are two different sets of data that comprise Hermite data, usually based around a uniform 3D grid.

1. Signs (for one material) or indices (for multiple materials) at each corner
2. Surface intersections and normals at each edge that exhibits a sign or index change

The paper explains how the algorithm operates on the Hermite data and how to adapt it for an octree instead of just a uniform grid. Some other sources that may prove useful are:

http://upvoid.com/devblog/2013/05/terrain-engine-part-1-dual-contouring/

http://upvoid.com/devblog/2013/07/terrain-engine-part-2-volume-generation-and-the-csg-tree/

https://stackoverflow.com/questions/6485908/basic-dual-contouring-theory

---
Tags: terrain-rendering, level-of-detail, marching-cubes
---


# Question
Title: How can I create the correct player object based on a type in a network message?
I am using lidgren as a networking library for a small XNA game. I am using a client/server architecture for the game. Currently, I have the client and server connecting but I would like to be able to pass an enum with a character type when the client requests to join the server. Here is a sample of my code:

```
while ((inMsg = networkManager.ReadMessage()) != null)
        {

            switch (inMsg.MessageType){
                case NetIncomingMessageType.StatusChanged:
                    switch ((NetConnectionStatus)inMsg.ReadByte()){
                        case NetConnectionStatus.Connected:
                            if (!this.isHosting)
                            {
                              //Extract player info from message and create a local player
                            }break;
                        case NetConnectionStatus.RespondedAwaitingApproval:
                            pType = (PlayerType)inMsg.ReadByte();
                            playerManager.AddPlayer(pType);
                            //Then I will send the player information to the client
                            inMsg.SenderConnection.Approve();
                            break;
                    }
                    break;

            }

            this.networkManager.Recycle(inMsg);
        }

```

When server gets a message with `RespondedAwaitingApproval` flag, I would like to be able to read the message, extract the type and create an instance of a player of that type. How can I accomplish that?

# Answer
What's wrong with the simple approach? Something like:

```
Player CreatePlayerOfType (PlayerType type) {
  switch (type) {
    case PlayerType.Red:
      return new RedPlayer();
    case PlayerType.Blue:
      return new BluePlayer();
    default:
      throw new InvalidOperationException("Unexpected player type.");
  }
}

```

It's not clear from your question whether different player type enum values correspond to actual different player *classes* or just instances with different *data* (which is probably the approach I'd vote for, but I don't know anything else about the nature of your game). However, whichever it is, the above approach will work fine.

If construction of your players becomes complicated or you have a lot of player types or permutations, the above code can present a maintainability problem as it scales. To handle that, you can build your implementation towards an abstract factory pattern, which can afford you some interesting options for data-driving your player creation, or at least keeping the maintenance overhead down.
> 1 votes

# Answer
I have just solved the question by doing the following:

I pass in the player type with the netClient.Connect() method.

```
NetOutgoingMessage hailMsg = netClient.CreateMessage();
hailMsg.Write((byte)playerType);
netClient.Connect(ipEndPoint,hailMsg);

```

Then, on the server side, I did the following:

```
case NetConnectionStatus.RespondedAwaitingApproval:
     PlayerTypesTypes playerType = (PlayerTypes)inMsg.SenderConnection.RemoteHailMessage.ReadByte();
     //Do whatever you want with the playertype
     inMsg.SenderConnection.Approve();
     break;

```

Basically, I just realised that you could send additional information along with the clients hail message in the netClient.Connect method and that you can extract that from the hail message by specifying SenderConnection.RemoteHailMessage.
> 0 votes

---
Tags: xna, networking
---


# Question
Title: Percentages for different platform generation
I have a level manager, which creates levels and levels create platforms.

Levels can contain a variety of platforms.

I dont really understand how I can say:

> I want a 10% of one platform being made, 30% chance of another, and 70% chance for anotgher and so on...

At the moment I have a method that looks like this:

```
   private void creationManager(float moveChance, float breakableChance, float superJumpChance)

```

I'm not sure how I can use these values and probabaility to determine which type of paltform is created.

Any ideas?

# Answer
Another possible algorithm. This is easily expandable as well and does not have to use % of 100:

```
//assuming rand() returns integers
#define numberOfPlatformTypes 3
int platform[numberOfPlatformTypes];
platform[0] = 10;
platform[1] = 30;
platform[2] = 70;

int total = 0;
for(int i = 0; i < numberOfPlatformTypes; ++i)
 total += platform[i];

int r = rand()%total;
for(int i = 0; i < numberOfPlatformTypes; ++i)
{
 if(r < platform[i])
  return i;
 r -= platform[i];
}

```
> 1 votes

# Answer
Use random numbers! :) Here is a bit of pseudo code to get you started.

```
// Assuming rand() returns a value between 0 and 1.
float r = rand();

if(r <= 0.1f)
 /* create platform type 1 */
else if (r <= 0.3f)
 /* create platform type 2 */
else if (r <= 0.7f)
 /* create platform type 3 */

```

It is amazing what you can achieve with just random numbers.
> 0 votes

---
Tags: xna, c#, mathematics, probability
---


# Question
Title: Behave Plugin : Behavior Tree Perpetually "Running" actions Prempting problem
I am using the Behave Plugin to make behavior trees for my game

So, I have a behavior tree that looks like this : http://imagebin.org/278510

The Actions marked in Red are basically Perpetually Running actions once reached, they make my guard perpetually rotate in 360 degree circles or 180 degree scans.

This works as expected and everything is fine, however, when a higher priority subtree is introduced things get hairy, So, suppose my higher priority subtree chases the player when he is seen, the guard chases the player eventually loses him, now, I want the patrolSubtree to be completely Re-evaluated (i.e. starting from goToWayPoint) , it will however , come to the patrolSubtree sequence and see that a chain leading to doScanFull is "Running" and will start to rotate the guard "in place" wherever it was when it lost the player.

I believe there should be some way to resolve this, as even in the case of non "Perpetually" running actions, this may cause unexpected behavior when a "Running" action is interrupted by a higher part of the tree.

Can anyone suggest a way to do this ?

I think there should be a way to reset the entire subtree at whim, so that all "Running" actions are cleared, or is there some better way ?

Furthermore, What if I dont want my Top level Selector to be affected by the "Running" state on any Action ? i.e. I want that selector to check every possibility underneath it to see which one to run , that way , if the guard is doing a HalfScan and he sees the player , the "Chase Subtree" will actually evaluate. If the Top level Selector was affected by the Running state of stuff under it though, then the higher priority actions may never evaluate because some stuff was in the "Running" state.

Thanks a lot, Nik

# Answer
> 0 votes
So, it seems I figured out a solution to this problem, I had to go through many many texts to figure this out. So, here goes, the solution is basically to use 'Interrupts'.

Interrupts are basically decorators that have check for preconditions every AI frame when control goes through them, so if a low priority action has an interrupt on the way to it, the interrupt will be evaluated every time the low priority action is actually executed.

So, the interrupt basically checks for preconditions that would mean that a higher priority subtree must be evaluated, if these preconditions are ever true, then the interrupt breaks out of the current subtree and forces a re-evaluation on the entire tree, which would result in higher level actions being executed, since the top level selector would actually go to higher priority actions.

The attached image will probably explain the solution much better than any wall of text.

http://imagebin.org/280408

---
Tags: unity, ai, behavior
---


# Question
Title: implementing collision detection and handling for tiled 2D world with smooth wall sliding
Im using SFML 2.1 for graphics and my game structure follows SFML book quite closely (SceneGraph implementation etc) My world consists mostly of characters (around 1-400, moving around) and tiles (3600, stationary) and I'll check for collisions everytime something moves

In worst case scenario with ~400 characters moving around and ~3600 tiles, I have 4000 possible entities with collision and 800 collision check calls (separate X and Y movement) each frame -\> 3.2M collision checks in total.

Almost all my entities have size of 16x16 pixels and I've been looking into implementing either quadtree or simpler grid for collision detection, which should bring number of collision checks down quite a bit. By grid I mean http://conkerjo.wordpress.com/2009/06/13/spatial-hashing-implementation-for-fast-2d-collisions/

But I have no idea how I should implement simple grid for example. All help is welcome. There's propably even a lot better ways to bruteforce this.

**Entity update step.** I do X/Y-axis movement separately. Because I want to slide against entities when colliding diagonally.

1. Move entity horizontally
2. Check and handle collisions
3. Move entity vertically
4. Check and handle collisions
5. Repeat 1-4 for all entities

.

```
void Entity::updateCurrent(sf::Time dt, CommandQueue& commands)
{
    setPreviousPosition(getPosition());
    move(sf::Vector2f(mVelocity.x, 0) * dt.asSeconds());
    handleCollision();
    setPreviousPosition(getPosition());
    move(sf::Vector2f(0, mVelocity.y) * dt.asSeconds());
    handleCollision();
}

```

I've had the following problem before when I tried to handle both X and Y movement at the same time:

I had no idea if I should reset X or Y position after collision.

**Collision handling.** I'll handle collisions only when entities are moving (currently only character entities, later projectiles and some special tiles)

1. if entity is tile -\> do nothing
2. if entity is character -\> check collisions with characters and tiles and reset movement if collision happened

.

```
void Entity::handleCollision()
{
    if (getCategory() & Category::Tile)
        return;
    if (getCategory() & Category::Character)
    {
        std::set<SceneNode::Pair> collisionPairs;
        checkCollision(*mSceneGraph, collisionPairs);

        for (SceneNode::Pair pair : collisionPairs)
        {
            if (matchesCategories(pair, Category::Character, Category::NonPassableCharacterOrTile))
            {
                resetPreviousPosition();
                break;
            }
        }
    }
}

```

I'll check collision simply by using SFML's intersects-function. This is propably good enough for this?

```
bool collision(const SceneNode& l, const SceneNode& r)
{
    return l.getBoundingRect().intersects(r.getBoundingRect());
}

```

If I were to implement grid or quadtree for collision detection, when should I populate it, when update? Should I update it every time I move one entity, or should I try to come up with a way to move all entities at once, then build grid/quadtree and only after that try to handle all collisions.

**So my questions are**: **(1)** In this scenario how and when should I do collision handling? My current implementation works, but I think I do it too often and all examples I looked into grids/quadtrees assumed that I do first all movement and do collision detection and handling after.

and **(2)** When do I clear/populate/update my grid/quadtree. For example if I have 3600 tiles and 3 moving characters. Should I seek for entity each time one moves in the grid and try to move it to different grid cell / tree branch?

*Edit:*

What I'll propably try next unless anyone gives better advice

**Updated update step.** Is this smart or in anyway reasonable way to do this?

1. Remove entity from grid/quadtree
2. Move entity horizontally
3. Add entity to grid/quadtree
4. Check and handle collisions
5. Remove entity from grid/quadtree
6. Move entity vertically
7. Add entity to grid/quadtree
8. Check and handle collisions
9. Repeat 1-8 for all entities

.

```
Entity::move()
{
    grid.getCell(getPosition()).remove(this);
    ... move x
    grid.getCell(getPosition()).add(this);
    ... if collision, reset x

    grid.getCell(getPosition()).remove(this);
    ... move y
    grid.getCell(getPosition()).add(this);
    ... if collision, reset y
}

Entity::checkCollision()
{
    list<Entity*> possibleColliders;

    possibleColliders = grid.getEntitiesInRectangle(x - s, y - s, x + s, y + s);

   ... now only check collision against possibleColliders
}

```

# Answer
> 1 votes
Assuming I'm correctly understanding that you have (or intend to have) a grid, a large number of the collisions become far more trivial. This would entail having one collision check versus the map, and another collisions check between entities. The reason to do this is that the static nature of a grid makes for some easy collision checks.

Pretending that you have a grid called map, a few functions can be implemented like:

```
bool map.isPassableAt(x, y)

```

The underlying implementation of such a function depends on the game a bit, but will be something along these lines:

```
if (!boundsCheck(x, y))
   return false

return map.getTileAt(x, y).passable
// or some function that uses the tile data to say if it can be
// passed through or not

```

How does the collision against these tiled map elements work? Well I think your approach of checking the x and y components of movement separately is a good approach for allowing the slide effect that you desire. More specifically, an entity can be moved by its x and y component at the same time, and if no collision occurs, great. Otherwise... rewind that entity and move it just by x, if that collides rewind that and move it just by y, if that collides rewind that, and the end result is either partial (slide) or no movement.

The actual collision can be discerned from rectangles (or bounding boxes, as libraries like to call them), or you can see if any of the four corners of the entity are in an impassable area of map.

As far as collisions amongst entities goes, I think this is the realm where the quadtree becomes an option. I've been working on an HTML5 (javascript) and canvas games, so my performance concerns may differ from yours. In my experienced I was surprised at how far plain old brute force took me... truly into the millions of collisions per frame before the calculation was consuming anywhere near 16 ms (my threshold for "too laggy").

When I did make it to using a quadtree, I favored an approach that seems far from perfect, but I'll share it anyways.

1. player inputs are processed, and player is moved (inputs come from the previous frame)
2. all npcs are moved
3. a quadtree is created with the position of all of the above entities (yes, a new quadtree every frame)
4. collisions are checked (is a hostile npc colliding with a player? do damage! is a player colliding with an aggro circle of a hostile npc? set npc to aggro! etc)

That's how I've been doing it, with fairly good results. These entities do not experience "hard" collisions with one another however.

---
Tags: c++, collision-detection, sfml
---


# Question
Title: Improving performance of perlin/simplex noise calculations
I'm using perlin noise to calculate different values for 3d block-world terrain. I calc roughly six (at most) noise values for various terrain features for every 4 blocks in a chunk. The missing values are then filled in by a linear interpolation method. I've built most of this from looking at how existing games like minecraft, terasology, etc do it.

The terrain I've finally wound up with is exactly where I want it - it looks great. However, the game FPS drops heavily any time a new set of chunks are loaded as the player walks.

Each chunk is 16x16x128 blocks. At max settings, the player may have 10 chunks in every direction visible, so if you walk sixteen blocks forward, roughly 10 new chunks are loaded and ten unloaded.

Even with calculating noise for only 1/4 the blocks in a chunk, the performance hit is too much. I've run some profiling and it's the `noise` calculation method that's the culprit.

Obviously, I need to address this. I just need some advice.

* Are there any specific perlin/simplex implementations that are known to be tuned for performance?
* Would it be possible/advisable for me to run all of the noise calculations asynchronously and then pass those back to the main thread for actual block-fill and rendering?

# Answer
Moving the chunk generation into another thread can keep the fps relatively constant while the terrain continues generating. In my limited attempts to create voxel engines, there was a significant benefit to moving the creation of block faces (in addition to the noise generation) into a different thread. Something like a 'chunks to generate queue' can be made, and chunks can be added to this todo list as the player moves around. A chunk in this sense is both the noise-generated data, and a mesh or collection of vertices. Chunks nearest the player can be prioritized. Also, having cube chunks (e.g. 32x32x32) is an option for worlds that don't want specific limitations on their height.

I can't speak to specific noise generation implementations in java, but simplex noise is faster than perlin noise as more dimensions are introduced. Your lerp technique, as well as resampling an existing section of noise are other tricks to reduce the total number of calls to a noise.generate(x,y,z) function. Reducing the octaves can also affect speed significantly at the expense of some detail.

Some elements of some generation themes can also avoid new calls to noise altogether. As an example, I've created a temperature gradient for a hemisphere of a hypothetical world by mixing a gradient with a small section of existing noise. A seeded pseudodrandom number generator and varying types of automata algos can also produce some interesting results.
> 3 votes

# Answer
Have you considered moving your terrain generation to the GPU? I have had huge performance increases since I started creating height maps in shaders rather than on the CPU. A good way to do this, if you're interested, is to implement Perlin noise as describe here and render the result to a texture using a framebuffer object. Good luck.
> 2 votes

---
Tags: java, performance, procedural-generation
---


title: How do I get my game on Facebook?

text:
# Question
Title: How do I get my game on Facebook?
I am trying to upload my game to Facebook. However, the game does not appear. Why is this and how can I fix it?

# Answer
You can't upload a game on Facebook. You need to host the game on your own server with SSL capabilities, and then Facebook will show the game from your server to the players.

You seem to be using Construct 2. There is a great tutorial for publishing a Construct 2 game on Facebook. Just follow the tutorial and you should be all set.
> 4 votes

---
Tags: facebook, construct-2
---


# Question
Title: How can I generate natural-looking tree leaves in a Minecraft-like world?
I'm moving from working on 3D block-world terrain to more specific features like tree leaves and ore veins (the ore veins will likely be done with my existing Perlin noise for the terrain). One thing I'm having with is properly generate clusters of blocks (for example, leaves for trees).

I've tried looping through a radius and randomly skipping blocks so it seems more natural but this still doesn't look natural enough and also makes it based on a cube shape to start. I want some trees to have more of an overall sphere-shape to the leaves, or some to have a cone shape. I haven't really found helpful info on how to loop through coordinates of shapes other than a cube.

What technique(s) should I employ to generate natural looking clumps of tree leaf blocks?

# Answer
Would it make sense to generate a tree structure using an L-system, initially ignoring the cube grid, and then clamp the resulting leaf positions to the grid? (ignoring duplicates where multiple leaf nodes map to the same grid cell)

Another possibility: You could randomly generate points within a sphere (some approaches here, if your environment doesn't provide a convenience function for this), and then add a leaf block at each grid cell in a line between that point and the center of the sphere. This will ensure you don't have floating leaves with no neighbours, and the boundary will still be rough rather than looking like a perfect sphere.
> 2 votes

---
Tags: procedural-generation, block-world
---


# Question
Title: Can I my iOS-based editor save .plist files that my Mac game can read?
I want to make an editor on iOS which will record touch positions into a file. That file (in the `.plist` format) will eventually be used for positions in my Mac connect-the-dots game.

Can I save one `.plist` file to my Mac from an iOS app?

# Answer
> 1 votes
No, you cannot do this directly.

You can, however, rely on a standard method of transporting data between machines: the internet. Probably the most straightforward option would be to use either iCloud storage containers or Dropbox's API. Both APIs provide a way you can save files on one device and access them later from another device.

If you want something more "real-time" you could establish manual socket connections between your editor and game and transfer the data that way (at that point you probably don't want to bother sending a whole `.plist` file, just send the position updates you need).

---
Tags: ios, macos
---


# Question
Title: Solving banding with additive blended particles
I needed to implement particles for my 2D game, written in C++ with OpenGL for graphics, so I went ahead and created a nice geometry container to batch particles together and then implemented the basic stuff on them. So far so good, my particles work fine as intended, with a decent performance.

However, even tho my particles appear, animate and die the way they are supposed to, I am experiencing banding in the particles. All particles are drawn in a single draw call with additive blending. When I render a single particle I don't seem to get any noticeable banding, but the more particles I stack on top of each other, the more clear the banding becomes, giving unacceptable results.

I am doing nothing fancy with the rendering, it should work but here 's some more info. Blend mode: glBlendFunc(GL\_SRC\_ALPHA, GL\_ONE); (for particle textures with varying alpha) Context: 32 bit color depth and nothing seems to be banding anywhere else, there isn't anything using low-precision Fragment shader output: gl\_FragColor = texture2D(texture, texUV) * outColor;

Also, I developed this system inspired in HGE particle editor. I am using the same particle texture that this program uses successfully, with no visible banding at all, but it doesn't work for me for some reason. Link: http://hge.relishgames.com/

Thanks

# Answer
As a variant. Render particles in translucent off-screen buffer in normal mode. Then render this buffer to screen in additive mode.

If you want better result. Render particles in normal mode, but self-illuminated, i.e. they must not be affected by lighting (if you using lighting at all). Ideally they must also emit some light.
> 1 votes

---
Tags: opengl, c++, graphics
---


# Question
Title: Directx 11 , problem positioning a 2D quad , center starting at bottom left and not top left
I'm following some tutorials of directx 11,and i was able to draw a quad, but my problem began when i was applying transforms , for some reason, my quad at position 0,0, start at bottom left of my screen, but i want to it starts at Top Left , i don't figure out why

this happend when i used XMMatrixOrthographicOffCenterLH , but if i use XMMatrixOrthographicLH , it start at the center of the screen, im doing something wrong?

here is some screenshots:

using XMMatrixOrthographicOffCenterLH : http://troll.ws/image/27213361

using XMMatrixOrthographicLH : http://troll.ws/image/ebf0dbc8

SpriteTest.h

```
#pragma once
#ifndef JDX_SPRITE_TEST_H
#define JDX_SPRITE_TEST_H

//DX Includes
#include <DirectXMath.h>
using namespace DirectX;

class SpriteTest{
public:
    void    Draw();
private:
    struct ShaderParameters {   XMMATRIX worldMatrix; };
    struct VERTEX           {   XMFLOAT3 Position; XMFLOAT4 Color; };
...
...
};
#endif

```

SpriteTest.cpp

```
#include "SpriteTest.h"
using namespace DirectX;

void SpriteTest::Initialize(){

    // load and compile the two shaders
    ID3D10Blob *VS = NULL, *PS = NULL;

    m_pRenderManager->CompileShader("Shaders/SpriteBatchVS.hlsl","main","vs_5_0",&VS);
    m_pRenderManager->CompileShader("Shaders/SpriteBatchPS.hlsl","main","ps_5_0",&PS);

    // encapsulate both shaders into shader objects
    m_pDevice->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), NULL, &m_pVertexShader);
    m_pDevice->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), NULL, &m_pPixelShader);

    // set the shader objects
    m_pDeviceContext->VSSetShader(m_pVertexShader, 0, 0);
    m_pDeviceContext->PSSetShader(m_pPixelShader, 0, 0);

    // create the input layout object
    D3D11_INPUT_ELEMENT_DESC ied[] =
    {
        {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
        {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0},
    };

    m_pDevice->CreateInputLayout(ied, 2, VS->GetBufferPointer(), VS->GetBufferSize(), &m_pInputLayout);
    m_pDeviceContext->IASetInputLayout(m_pInputLayout);

    // __________ Init Vertex Buffer

    // create a triangle using the VERTEX struct
    /*
    1__3
    |\ |
    | \|
    0--2

    struct VERTEX { XMFLOAT3 Position; XMFLOAT4 Color; };
    */
    VERTEX QuadVertices[] =
    {
        { XMFLOAT3(-1.0f, -1.0f, 0.0f), XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f)},
        { XMFLOAT3(-1.0f,  1.0f, 0.0f), XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f)},
        { XMFLOAT3( 1.0f, -1.0f, 0.0f), XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f)},
        { XMFLOAT3 (1.0f,  1.0f, 0.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f)},

    };

    // create the vertex buffer
    D3D11_BUFFER_DESC bd;
    ZeroMemory(&bd, sizeof(bd));

    bd.Usage = D3D11_USAGE_DYNAMIC;                // write access access by CPU and GPU
    bd.ByteWidth = sizeof(VERTEX) * 4;             // size is the VERTEX struct * 4
    bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;       // use as a vertex buffer
    bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;    // allow CPU to write in buffer

    m_pDevice->CreateBuffer(&bd, NULL, &m_pVertexBuffer);       // create the buffer

    // copy the vertices into the buffer
    D3D11_MAPPED_SUBRESOURCE ms;
    m_pDeviceContext->Map(m_pVertexBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms);    // map the buffer
    memcpy(ms.pData, QuadVertices, sizeof(QuadVertices));                                // copy the data
    m_pDeviceContext->Unmap(m_pVertexBuffer, NULL);                                      // unmap the buffer

    // __________ Init Index Buffer

    WORD indices[] =
    {
        0,1,2,
        2,1,3,
    };

    D3D11_BUFFER_DESC indexDesc;
    ZeroMemory( &indexDesc, sizeof( indexDesc ) );

    indexDesc.Usage = D3D11_USAGE_DEFAULT;
    indexDesc.ByteWidth = sizeof( WORD ) * 6;
    indexDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
    indexDesc.CPUAccessFlags = 0;

    D3D11_SUBRESOURCE_DATA indexData;
    ZeroMemory( &indexData, sizeof( indexData ) );
    indexData.pSysMem = indices;

    m_pDevice->CreateBuffer( &indexDesc, &indexData, &m_pIndexBuffer );

    // __________ Init Constant Buffer
    D3D11_BUFFER_DESC constDesc;
    ZeroMemory( &constDesc, sizeof( constDesc ) );

    constDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    constDesc.ByteWidth = sizeof( XMMATRIX );
    constDesc.Usage = D3D11_USAGE_DEFAULT;

    m_pDevice->CreateBuffer( &constDesc, 0, &m_pCostantBuffer );

}

void SpriteTest::Draw(){
    // select which vertex buffer to display

    UINT stride = sizeof(VERTEX);
    UINT offset = 0;
    m_pDeviceContext->IASetVertexBuffers(0, 1, &m_pVertexBuffer, &stride, &offset);

    // select which primtive type we are using
    m_pDeviceContext->IASetIndexBuffer( m_pIndexBuffer, DXGI_FORMAT_R16_UINT, 0 );
    m_pDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    XMMATRIX view           = XMMatrixIdentity();
    //XMMATRIX projection       = XMMatrixOrthographicLH( 1024, 768, 0.0f, 100.0f );
    XMMATRIX projection     = XMMatrixOrthographicOffCenterLH( 0.0f,(float)m_pRenderManager->GetWidth(),0.0f,(float) m_pRenderManager->GetHeight(), 0.0f, 100.0f );
    XMMATRIX worldMatrix    = XMMatrixMultiply( view, projection );

    ShaderParameters shaderParameters;

    // __________ Sprite World Coordinates
    float spriteWidth   = 32.0f,
          spriteHeight  = 32.0f,
          spritePosX    = 0.0f,
          spritePosY    = 0.0f;

    XMMATRIX l_translation  = XMMatrixTranslation(spritePosX, spritePosY, 0.0f );
    XMMATRIX l_rotationZ    = XMMatrixRotationZ( 0.0f );
    XMMATRIX l_scale        = XMMatrixScaling( 1.0f * spriteWidth,1.0f * spriteHeight, 1.0f );
    XMMATRIX l_spriteWVP    = l_translation * l_rotationZ * l_scale;

    // __________ Prepare World Coordinates to send to the shader
    XMMATRIX l_worldMatrix = XMMatrixMultiply( l_spriteWVP, worldMatrix );
    l_worldMatrix = XMMatrixTranspose( l_worldMatrix );

    shaderParameters.worldMatrix = l_worldMatrix;

    m_pDeviceContext->UpdateSubresource( m_pCostantBuffer, 0, NULL, &shaderParameters, 0, 0 );
    m_pDeviceContext->VSSetConstantBuffers( 0, 1, &m_pCostantBuffer );

    m_pDeviceContext->DrawIndexed( 6, 0, 0 );

}

```

vertex shader:

```
cbuffer cbParameters : register( b0 ) {
    float4x4 worldMatrix;
};

struct VOut
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};

VOut main(float4 position : POSITION, float4 color : COLOR)
{
    VOut output;

    output.position = mul(position,worldMatrix);
    output.color = color;

    return output;
}

```

pixel shader:

```
float4 main(float4 position : SV_POSITION, float4 color : COLOR) : SV_TARGET
{
    return color;
}

```

# Answer
> 3 votes
i was able to fix the problem with help of other forums, just in case somebody has this same issue this is how to fix it

swaping the viewBottom and viewTop values for the orthographic matrix should get 0,0 at the top-left of the viewport.

```
XMMatrixOrthographicOffCenterLH( 0.0f,(float)m_pRenderManager->GetWidth(),(float) m_pRenderManager->GetHeight(), 0.0f, 0.0f, 100.0f );

```

other issue i had was the sprite world matrix multiplication that should be **scale * rotation * translation**

```
XMMATRIX l_spriteWVP    = l_scale * l_rotationZ * l_translation;

```

and i had to set the culling mode to CULL\_NONE

```
D3D11_RASTERIZER_DESC rasterizerState;
ZeroMemory(&rasterizerState, sizeof(D3D11_RASTERIZER_DESC));

rasterizerState.AntialiasedLineEnable = false;
rasterizerState.CullMode = D3D11_CULL_NONE; // D3D11_CULL_FRONT or D3D11_CULL_NONE D3D11_CULL_BACK
rasterizerState.FillMode = D3D11_FILL_SOLID; // D3D11_FILL_SOLID  D3D11_FILL_WIREFRAME
rasterizerState.DepthBias = 0;
rasterizerState.DepthBiasClamp = 0.0f;
rasterizerState.DepthClipEnable = true;
rasterizerState.FrontCounterClockwise = false;
rasterizerState.MultisampleEnable = false;
rasterizerState.ScissorEnable = false;
rasterizerState.SlopeScaledDepthBias = 0.0f;

result = m_pDevice->CreateRasterizerState( &rasterizerState, &m_pRasterState );
m_pDeviceContext->RSSetState(m_pRasterState);

```

i also realized the quad was mirror-like (all inverse), after i applied those changes, but i was able to fix it changing the vertex position when i create the vertex buffer

```
VERTEX QuadVertices[] =
{
    { XMFLOAT3( 0.0f,  1.0f, 0.0f), XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f)},
    { XMFLOAT3( 0.0f,  0.0f, 0.0f), XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f)},
    { XMFLOAT3( 1.0f,  1.0f, 0.0f), XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f)},
    { XMFLOAT3 (1.0f,  0.0f, 0.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f)},

};

```

---
Tags: c++, 2d, directx11
---


# Question
Title: Divide rectangular image into fixed number of random sized rectangles + 1 fixed size rectangle
I'm trying to divide a rectangular image into a fixed number of smaller rectangular image parts (of random **but bounded width / height**), with the exception of 1 rectangle which is predefined in position and size.

So, for example:

My first thought was:

* Generate list of possible points
* From this list remove all points in the fixed size rect
* From this list remove all points that can't possibly meet the other requirements (e.g. points close to the image edges that wouldn't meet the required bounded min / max rect size)
* Then randomly pick a point, generate a random bounded width / height, see if this intersects any current rect, until we find one that doesn't
* Record rect, remove all points in rect from list
* Repeat

However this seems slow, overly-complex and still results in holes because sometimes there's no more room for the minimum size of rect to fill the last bit of space.

I've looked into algorithms involving squaring the square, packing routines and such like, but nothing I've found helps with the additional constraint that *one rectangle is predefined and the rest can be random*.

Not looking necessarily for a full algorithm, but hints at an approach would be appreciated.

# Answer
I would say... start with the fixed rectangle. Extend either the vertical or horizontal sides to the edges of the area; this gives you 5 rectangles (including the fixed one). Randomly choose any of the N non-fixed rectangles, cut it in half vertically or horizontally, giving you N+1 rectangles. Repeat until you have the number of rectangles you want.
> 3 votes

# Answer
I suspect that positioning rectangles completely randomly could let to a lot of failed solutions, and no clear idea why a solution failed.

My suggestion would be to start at the fixed rectangle and randomly generate adjacent rectangles. In a similar manner to a search such as A\*, you would end up with a closed list and an open list, e.g. closed contains rectangles which are completely surrounded and open contains rectangles with at least one free edge. Because they would be generated adjacently, there would be readily available data on potential clashes that may lead to no solution, and at that point you could backtrack. You may also find some heuristics that help the search, e.g. process the open list in order of shortest free edge.
> 1 votes

# Answer
I would suggest a sweep approach. Starting from the origin, choose one axis (for example y, which I will consider as the columns axis) and generate random sizes for the rects until you reach the end of the axis. This will setup `column[0]`. For each `rect[i]` in `column[j]`, you should save `rect[i].finalX` as the final x coordinate of this rect.

To generate the next `column[j + 1]` you should, `for each rect[i] in column[j]`, create new rects starting from `column[j].rect[i].finalX` until you fill all y interval of `column[j].rect[i]`. The algorithm finishes when one column cannot insert more rects.

It is important to note that this algorithm will create rects with smaller y size as the sweep proceeds. To fix that you could randomly create adjacent rects with same `finalX`. In the next column you can consider these adjacent rects as one, boosting the y size to work on.

If the procedure is not clear, ask me and I edit the answer with a formal algorithm.
> 1 votes

---
Tags: mathematics, algorithm, geometry
---


# Question
Title: Separate shader programs or branch in shader?
I have a bunch of point lights and directional lights. Instead of checking the light type in the fragment shader and then branch for either point light calculation or directional light calculation, is it more efficient to use two separate programs, one for point lights and one for directional lights?

(Using deferred shading in OpenGL 3.3)

# Answer
> 3 votes
* Branching incurs overhead on GPU if the threads take different branches, which leads to serialisation. Thus, if all of your pixels take the same conditional branch, the overhead is negligible.
* In addition, if the condition is complex, it can increase the number of registers used per thread which can impact performance depending on how much is this increment.
* You should also consider the choice in a code maintainability perspective. If the use of two separate programs makes code clearer, more maintainable and with no code replication I would suggest this approach if the overhead considered at the aforementioned items is acceptable.

---
Tags: opengl, shaders, glsl, deferred-rendering, deferred-shading
---


# Question
Title: What causes still objects have lines in them when lighting is being changed?
First, here is what I'm talking about (I changed the contrast to make it more visable, since it's not really visible in still images):

*Ingore the chat box, I was spamming buttons to see which one took a screenshot :P*

Hopefully you can see clearly what I'm talking about. Basically, those lines in the sky (they're only visible in the top part of the image). This seems to occur for me any time I use a still object and move lighting across it (the faster the light, the more the lines are visible to the player). What causes this? It seems to happen in lots of games though (especially in the sky, since it's pretty much still). Is there any way to remove them (I'm not looking for API specific because it seems to occur in all APIs)?

# Answer
> 0 votes
As danijar says, it might be due to a compression, but let me remind you what is **Colour** in computer.

You may already know that a color is made by RGB components, which can represent 16 777 216 different colors (256 red * 256 green * 256 blue). But it's quite small compared to the real world :)

You can see the limitations in soft gradients with few color changes like in your picture, because there's big chunks of colors varying of certainly the smallest unity.

Over that, compression makes calculations faster and reduces memory usage, but with a loss of color information.

You can color objects in several ways, but the next two are the most commonly used:

* If you color your models with vertices, a color interpolation is done between two vertices. *(If you don't know, a vertex can handle several data other that it's own position, like depth, normal or color)*.
* If you color your models with textures, then you have more control of how an object looks by flattening textures on faces, but textures really consumes a lot of memory.

---

Now you know how to color your objects, but how to avoid this bad color banding side effect ? Some people have already thought to this problem.

If you don't use textures, the only solution is to use vertex shaders. Unfortunately, I couldn't tell you how to make one.

Else, just dither your texture with *wavelet dithering*. It's a well fitted algorithm.

You can see how it looks without and with dithering:

---
Tags: 3d, shaders, lighting
---


# Question
Title: Entity component systems and DDD: violation of encapsulation?
I'm using a hybrid of DDD (domain-driven development) and an entity-component system. That is to say:

* I have an `Entity` class with a list of `Component`s, and the ability to add/remove/get components
* I have `component` instances like `HealthComponent` (health and is-alive), `DrawComponent` (position + display), etc.
* `System` instances (like `DrawSystem`) that find a bunch of components and operate on them

I also have "domain objects" like `Player` and `Monster`, which subclass Entity. Their constructors usually add a bunch of components.

Since I'm a fan of the DDD idea of objects represent business/game entities, I model my classes around that. For a roguelike, my `Player` class has methods like:

* `Attack(Monster)`
* `GetX` and `GetY` (delegates to the position component)
* `LevelUp`
* `RegenerateHealth`
* And others

It seems to me that the components are a white-box internal detail; they shouldn't be known to any outside objects. In fact, domain objects should operate on other domain objects (eg. `Player.Attack(Monster)`).

Most (if not all) of my actual game code operates on entities, not components. My tests usually do something like:

* Create an entity
* Grab a certain component
* Verify that it meets expectations

In general, this raised a question in my mind: isn't this a violation of encapsulation? Aren't components just an internal implementation detail of entities (that could change or disappear at any time)?

On the other hand, I have a lot of delegation, which seems useless (like `Player.getX()` is just `Player.get(DisplayComponent).getX()`).

This seems confusing. Can someone provide some clarity? What is the right mix of DDD, encapsulation, and entity/component composition?

# Answer
I'm afraid you've got this a bit wrong. The entire reason for component-based entity systems is that you should be favouring composition over inheritance. You should not be using inheritance over `Entity`. `Entity` exists as a composed piece of data / functionality, consisting of `Component`s *only*. It is, so to speak, intended to be a `final` class, i.e. no extensions.

Processing which you currently have in constructor functions, is meant to be performed by factories. Your factory's `build()` method should take an object of parameters used for the construction of your individual entity types. This means you can create any permutation you wish, at runtime, provided the appropriate parameters are supplied to that method. Parameters may be either static (e.g. loaded from a data file) or runtime-constructed based on certain conditions (such as a the player entering a factory or store in-game, and specifying a new unit type). You want to decouple your logic related to building an `Entity`, from the `Entity`s themselves. By using inheritance hierarchies, you are instead locking yourself down to compile-time decisions.

Very little of your code should be operating on `Entity` itself. `Entity` should be a highly generalised access point for specific data/functionality sets; thus, you ought to have your `Component`s as sets of related functionality, for instance, `transform`, `physics`, `ai`, `inventory`, `renderer` (if applicable) and so on. You can store these either as individual properties or as keyed values in a hashtable. The reason that you are specifying these as such, is that they are self-contained. For instance, you wouldn't need an AI command queue if the object had no AI. So we pack these together, and then it also makes access easier within related sets of functionality (due to shared scope).

Lastly, do not concern yourself overly with encapsulation at the `Entity` level. Your primary goal is to make your entities and their components as accessible as possible between different subsystems, at all times. Simply make them publically accessible, and worry about accessibility later if it really still seems important. But at the `Component` level, there may be methods and data members which will only ever be used internally and thus may be marked `private` from the get-go.
> 8 votes

---
Tags: architecture, entity-system
---


# Question
Title: Lunar lander: How to calc acceleration in each step
I'm trying to make a lunar lander simulator. I'm going to use a simple Euler integration. AFAIK all I've to calculate is the acceleration in each step, and then I should be able to update velocity and position.

I'm following this page: http://www.braeunig.us/apollo/LM-descent.htm

There's a paragraph I don't really understand:

> Although most operations are self-explanatory, a brief description of acceleration is warranted. Acceleration is broken down into vertical and horizontal components, where the vertical component is normal to the Moon's surface. The instantaneous vertical and horizontal accelerations of a moving body in reference to this surface are Av=Vh^2/r and Ah=–VhVv/r. To this we add the accelerations resulting from gravity and thrust. Gravity, of course, acts vertically downward. The vertical and horizontal components of thrust are a function of the pitch angle.

The author is making a much more realistic simulation here and because of that he is not assuming the Moon is flat. He comes up with two initial values for each acceleration component:

```
    Av=Vh^2/r

    Ah=–VhVv/r

```

1- Seems that Av is the centripetal acceleration, but where does the Ah come from?

2- Are those initial values really needed? In my game the Moon is going to be flat. I thought taking into account thrust/mass and gravity would suffice.

Thanks in advance.

# Answer
The author is working in a polar coordinate system, as it is probably more suitable for realistic simulations of this kind.

Those are not initial values. They are the **instantaneous** (for each moment in time) components of acceleration, in a polar coordinate system, of an object that is moving tangentially with respect to that coordinate system's origin. `Av` is the 'vertical' component away from the moon's center and `Ah` is the 'horizontal' component along the surface of the moon. Note that the same motion in a cartesian coordinate system would be a non-accelerated one.

For a flat moon you can just add thrust and gravity to get the current acceleration.
> 3 votes

---
Tags: physics, physics-engine, simulations, trajectory
---


# Question
Title: How to benefit from cpu cache in a entity component system game engine?
I often read in the ECS game engine documentations that is a good architecture for using cpu cache wisely.

But I can't figure how we can benefit from cpu cache.

If components are saved in an array (or a pool), in contiguous memory, it's a good way to use cpu cache BUT only if we read the components sequentially.

When we use systems, they need entities list which are list of entities that have components with specific types.

But these lists give the components in a random way, not sequentially.

So how to design a ECS to maximize the cache hit ?

**EDIT :**

By example, a Physic system needs an entities list for entity that has the RigidBody and Transform components (There is a pool for RigidBody and a pool for Transform components).

So its loop for updating entities will be like this :

```
for (Entity eid in entitiesList) {
    // Get rigid body component
    RigidBody *rigidBody = entityManager.getComponentFromEntity<RigidBody>(eid);

    // Get transform component
    Transform *transform = entityManager.getComponentFromEntity<Transform>(eid);

    // Do something with rigid body and transform component
}

```

The problem is that the RigidBody component of entity1 can be at the index 2 of its pool and the Tranform component of entity1 at the index 0 of its pool (because some entities can have some components and not the other and because of adding / deleting entities / components randomly).

So even if components are contiguous in memory, they are read randomly and so it will have more cache miss, no ?

Unless there is a way to prefetch the next components in the loop ?

# Answer
Mick West's article explains the process of linearising entity component data, in full. It worked for the Tony Hawk series, years ago, on much less impressive hardware than we have today, to greatly improve performance. He basically used global, pre-allocated arrays for each distinct type of entity data (position, score and whatnot) and references each array in a distinct phase of his system-wide `update()` function. You can assume that the data for each entity would be at the same array index in each of these global arrays, so for instance, if the player is created first, it might have its data at `[0]` in each array.

Even more specific to cache optimisation, Christer Ericsson's slides for C and C++.

To give a bit more detail, you should try to use contiguous memory blocks (most easily allocated as arrays) per each type of data (e.g. position, x y and z), to ensure good locality of reference, utilising each such data block in distinct `update()` phases for the sake of temporal locality i.e. to ensure the cache isn't flushed via the hardware's LRU algorithm before you've reused any data you intend to reuse, within a given `update()` call. As you've implied, what you don't want to do is to allocate your entities and components as discrete objects via `new`, as data of different types on each entity instance will then be interleaved, reducing locality of reference.

If you have interdependencies between components (data) such that you absolutely cannot afford to have some data separated from it's associated data (eg. Transform + Physics, Transform + Renderer) then you may opt to replicate Transform data in both the Physics and Renderer arrays, assuring that all pertinent data fits the cache line width for each performance-critical operation.

Remember also that L2 and L3 cache (if you can assume these for your target platform) do a lot to alleviate the problems that L1 cache may suffer, such as a restrictive line width. So even on an L1 miss, these are safety nets that will most often prevent callouts to main memory, which is orders of magnitude slower than callouts to any level of cache.

**Note on writing data** Writing does not call out to main memory. By default, today's systems have *write-back caching* enabled: writing a value only writes it to cache (initially), not to main memory, so you will not be bottlenecked by this. It is only when data is requested from main memory (won't happen while it's in cache) and is stale, that main memory will be updated from cache.
> 14 votes

---
Tags: c++, architecture, entity-system, memory-efficiency, entity-component
---


title: Goalkeeper Jumping Algorithm?

text:
# Question
Title: Goalkeeper Jumping Algorithm?
This may be a "best way to" question, so may be susceptible to opinion-based answers (which is ok for me). But I would also like if there are any tutorials , research papers , etc.

I'm trying to make a 3D free kick game, and I want to decide on the Goalkeeper algorithm.

Usually (and in my game) the shot is a function of `direction` , `power` and `swerve`. Maybe wind can be a factor too. So the shots trajectory is pre-deterministic, i.e., the point that intersects the goal (or out) plane is determined as soon as the shot fires.

So what could be a good approach for the goalkeeper to jump (or walk) ?

I have two approaches in mind :

1- determine the point, and jump to there. 2- when the ball is closer than a threshold distance, estimate the point by the ball's velocity vector, and jump to there.

The problem with the first approach is, goalkeeper will always save the shot, which I want to prevent. So there should be some kind of randomness, or the goalkeeper's ability to jump and walk will be restricted.

The problem with the second approach is, when there is a high amount of swerve, the goalkeeper will always fail to save the shot.

So how could these approaches be better?

Thanks for any help !

## Edit:

if you want to play the game, click here

# Answer
You know *where* the ball will hit the goal, and you know *when* this will happen. So you could set up some basic variables such as "reaction speed", "movement speed" and/or "jumping force".

A goal-keeper with a high reaction- and movement-speed will be able to catch most shots, while a goal-keeper with worse stats won't be able to do so.

If you have the ball-travel time `t`, and the player reaction time `rt`, then the effective time for the player to react will be `t - rt`. This is the time he has to move from his position to the position where the ball will hit the goal. So if `(t - rt) * movement_speed > distance_to_ball`, then the ball can be saved.

Of course it should become gradually more difficult to catch a ball that's further away from the keeper. Also you might want to introduce some kind of randomness... so the rule could be:

```
if( distance_to_ball / ((t - rt) * movement_speed) <= RAND() ){
    // ball catched
}

```

Where `RAND()` would return a random float between `0` and `1`.

The "Swerve" could just be some factor that reduces the players actual time to react.

Also instead of using a linear approach like above, you could experiment with another falloff (cubic, exponential etc.), so that shots fired really close to the goalkeeper have a much higher chance of getting caught.

I think the **most important aspect** is that the gameplay is fun and diverse. There's so much luck involved in saving a penalty-shot, that a *realistic* simulation/algorithm isn't going to produce much better results than something close to completely random.

Try to tweak the formula in a way that it rewards skill (eg. if you practice to land good shots, your chances of scoring are increased) but still allows a complete newcomer to score a goal as well.
> 4 votes

# Answer
In reality, a goalkeeper needs to do two things:

1. watch the ball and notice when its trajectory will cause it to fly into the goal
2. when this is the case, jump into the way

(a real soccer fan will now likely tell me about 20 other jobs a soccer goalkeeper has to perform, but bear with me, I am a nerd who hates sports).

To perform these jobs, the goalkeeper has to react quickly and correctly. When the kick is performed from a longer distance and the player isn't shooting very fast, the keeper will have a longer time to react and will be more likely to catch it. But a shot from a close distance could not leave the keeper enough time to react at all or when he reacts, the surprise might cause him to react incorrectly. The performance of a goalkeeper isn't consistent. There are cases of amateur keepers catching seemingly impossible shots or world-class keepers making stupid blunders in harmless situations. Both occurences aren't frequent, but they happen from time to time. So a certain element of chance should be part of your AI.

To simulate this, you could give the AI keeper a certain probability per physics-tick to react on a goal-shot and perform the necessary action to prevent it (it might already be too late to do this succesfully, but it would look more human when he would try anyway). When the keeper reacts, you could also give them an additional probability to react incorrectly. This probability should be antiproportional to the distance which is left, so that "stupid mistakes" are more likely to happen in difficult situations than in easy ones. The exact probabilities could be variable depending on the skill-level of the keeper and/or your difficulty level.
> 3 votes

# Answer
My team is working in a Football MMO and our approach is to attribute goal keepers (and other players) with several attributes, such as JUMP, PHYSIQUE, AGILITY, REACTION, REASON, POSITIONING, to name a few. The probability to perform a task is then a weighted sum of the attributes of the player related to that task. In your case, the task is to defend the shoot. You can model this as simple or complex as you like, depending on the quantity of skills used. You can also save presets of the skills set and use them depending on the difficulty, for example. Finally, to get some randomness, just simulate a dice and use it to check if the returned value is within the probability threshold. If it is, the shoot is defended. If not, it is a goal.
> 1 votes

# Answer
As of playing as a goalkeeper, I have to suggest these: Not all keepers have the same ability to jump, intelligence or reflects. As stated before, a goalkeeper always looks at the ball - and in real world, a good response is to move so that the goalkeeper will always cover the ball no matter how far it is from the goal if a straight shot is achieved.

An idea could be this: the keeper is moving on side based on the ball. When a shot is performed, the goalkeeper will "fall" (put his body in the angle of the potential position of the ball when it reaches the goal line) and fall (with animation) after a while. The keeper will jump (move horizontally, vertically or diagonally up for a while and then fall) if the potential position of the ball on the line is in bigger distance than its body length.

The delay of this move can be associated with the reflects of the keeper and the how high will it jump with the skills. Now, about intelligence, you could set a random indicator of when it will be confused by the curve (and jump in wrong way or with delay). The higher the skill, the less the probability to get confused. Jump delay, height and confusion can probably be enough for simple cases (if the goalkeeper jumps with delay or not far enough, then a goal can be achieved).

And again this is very generic, and just the way I think of it.
> 0 votes

# Answer
The ways to handle this are different based on how you are assigning speed, swerve etc. I'm assuming you have a skill challenge to do that ("stop the moving needle in the right part of the gauge"-type thing or something similar). If so, then you want higher-swerve and higher-speed to equal higher-percentage chance of scoring. If they are just chosen values, then they shouldn't have such a direct effect, or the player will always choose them to be high.

You could set a percentage of the time you want the goalkeeper to save (based on the speed and swerve), and simply pick a random number, if it's below that percentage, play the correct animation (diving the right way) for the save, if it's higher, play the wrong one and allow the score. This is simple, but also a little "cheating"-like.

You could set an amount of time for the goalie to read the direction the ball is going, and then start moving him in that direction, and constantly allow him to adjust for the swerve until the last X% of the time it takes the ball to arrive, at which point the goalie can dive for the ball if it's within a range of where he is (and outside "move-to" range). "Better" goalies (higher levels?) will read sooner, move faster, and dive later(and further). This is more complicated, but more flexible, and more simulation-like.
> 0 votes

---
Tags: unity, algorithm, jumping, trajectory
---


# Question
Title: Is it possible to achieve a smooth sprite animation with a fixed 60 FPS using Java 2D?
I've seen a lot of different game loops, and before implementing anything complicated I decided to start with a capped 60 FPS. My run method looks like this in my game thread:

```
/**
 * Fixed Frames Per Second = 60
 */
public void run() {
    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            stage.render();
        }
    }, 0, 17);
}

```

The stage is a canvas, and the render method looks like this:

```
public void render() {

    BufferStrategy bufferedStrategy = this.getBufferStrategy();

    if (bufferedStrategy == null) {
        createBufferStrategy(3);
        return;
    }

    Graphics2D graphics2d = (Graphics2D) bufferedStrategy.getDrawGraphics();

    for (Actor actor : actors) {
        graphics2d.setColor(Color.WHITE);
        graphics2d.fillRect(0, 0, 600, 600);
        graphics2d.drawImage(actor.getDrawableImage(), actor.getX(), actor.getY(), 32, 32, this);
    }

    graphics2d.dispose();
    bufferedStrategy.show();
    Toolkit.getDefaultToolkit().sync();
}

```

The only "actor" sprite is 32x32, is currently moving 1 pixel at a time, and is too slow. So I bumped it to move anywhere from 2-4 pixels at a time across the stage, but now it is chunky. Is this related to my implementation or specific to Java 2D? The movement happens while the user presses one of the arrow keys.

# Answer
> 2 votes
It might be related to the way you are setting the new position. Check this answer for some code related to how to monitor key down events.

https://stackoverflow.com/questions/2702203/keyboard-input-for-a-game-in-java

---
Tags: java, animation, sprites, frame-rate
---


# Question
Title: Create tile map in Cocos2D-X by not using TMX file
I used to make a tile base game in Windows with my own tile map file, but it is a static tile map. I use an 2D array to store of my tile map. Now I want to make game in smartphone by using Cocos2D-X, and I want to make a random tile map, so I guess using TMX file is not appropriate in this case. I tried to search about making a tile map with Cocos2D-X but there is only a tutorial with TMX file.

Can you give me an idea about this case.

Thanks in advance.

# Answer
You should generate the tmx file before you open the level. The format is open:

https://github.com/bjorn/tiled/wiki/TMX-Map-Format

That way you can take advantage of all the good things Cocos2D can do for you, and still have a random map.
> 0 votes

---
Tags: cocos2d-x
---


# Question
Title: Can I store D3D9 textures so that they don't consume process memory and also don't require "lost device" handling?
I have an OpenGL application that uses a lot of texture memory. While the texture is stored in the *system* memory, that texture memory is not part of my application *process* memory.

When this application is ported to D3D and the textures are uploaded to the `D3DPOOL_MANAGED` pool, the *process* memory increases proportional to the texture memory and the application crashes due to running out of memory (while in OpenGL, even though the overall *system* memory utilization has greatly increased, the *process* memory is still low)

I don't want to have to switch to `D3DPOOL_DEFAULT`, since the I would have to reload all textures when the device is reset. Is there a workable solution to get my D3D9 application to put the system texture memory somewhere else beside my process, similar to OpenGL?

EDIT: So I just learned about `IDirect3DDevice9Ex`. Turns out using this interface instead of IDirect3DDevice9 make DirectX work exactly like opengl in terms of texture memory (system memory goes up proportional to my texture usage, but not the process memory). So this is an option for me. However I would still like to know if there are any options since `IDirect3DDevice9Ex` doesn't work on XP.

# Answer
> 3 votes
If you don't want your textures backed by system memory, don't use `D3DPOOL_MANAGED`. Use some other member of the `D3DPOOL` enumeration (and change your code accordingly).

Generally this means choosing `D3DPOOL_DEFAULT` and handling device resets. You don't really have many other options, that's just how D3D9 works. If you can tolerate `IDirect3DDevice9Ex`, that will change your lost device behavior (see here and here), but also note that you cannot use `D3DPOOL_MANAGED` at all with `IDirect3DDevice9Ex`.

You might also consider the more drastic step of moving to D3D 10+ (but that will also cost you XP support).

# Answer
> 3 votes
If you're okay with using D3D9Ex which is Vista+ only then you should have absolutely zero reasons not to just using D3D11 (don't bother with 10; there are no systems that support 10 that don't support 11 if up-to-date service packs are installed). You can use a lower *feature level* in D3D11 so your game will still run on older hardware.

Note that according to the Steam Hardware Survey, only around 6.4% of users are even running XP (it confusingly also states that 14% of users have a DX10/11 capable GPU and are running on XP). XP can be considered a relic if you're targeting North America. Some other markets still have much higher XP installation rates but they also tend to have older hardware.

So far as actually answering directly your question: no. D3D requires that memory be managed in your process space or not at all. If it's not managed then you must deal with lost device.

For what it's worth, even with D3D10/11/GL you should still deal with removed device issues. Lost device is a relic of XP (back when the OS tried to stick to giving a process total control of the GPU and might have to wrench it back). Removed/reset devices can include driver crashes and restarts. If you handle removed devices, you're going to have to deal with reloading resources. This is one of the nicer features you can provide a user; I recall Borderlands managing to cause my GPU to lock up frequently due to a hardware issue, Windows would detect the locked GPU and then reset it (turning the screen black and freezing the system for a few seconds), and then Borderlands would continue like nothing had even happened. Most other games are just dead and all progress lost.

Note that GL has no standard way to detect removed/reset devices, owing possibly to the fact that most every GL implementation will just crash your kernel on such problems (this is one of the many reasons for users to prefer games written in D3D on Vista+: the system will be more stable). Mobile platforms tend to add in some way to know that the device has been reset owning to their limited resources and multi-tasking model (it's basically the D3D9 lost device situation; gone on the PC but alive and kicking on phones, albeit under vendor proprietary APIs).

The absolute best idea is to just update your engine to be able to deal with the need to reload assets on demand. Then you can on any platform or API (aside from desktop GL) deal with any variation of lost device or removed/reset device on almost.

# Answer
> 2 votes
First thing to consider is: is XP support really that important? Have you actually profiled your potential customer base and determined that XP support is something you need? Or is this just based on a gut feeling? Unless you have the numbers to back it up, losing XP support could be something you could easily afford to do.

If you're running out of process address space (and I'm assuming this means that you're building a 32-bit app) then your program already has quite heavy hardware requirements. There's a reality you're going to need to face here, and that's the fact that most people still on XP machines will also be on older hardware. *This hardware may just not be able to support your program's requirements*. Some vendors may not even have XP drivers available for the kind of hardware your program needs (e.g AMD appear to no longer do XP drivers for HD6000 series notebook cards). You need to get realistic about your requirements here.

Based on this, I'm suspecting that your wish to continue supporting XP is an artificial limitation you're placing on yourself. I'd urge you to reconsider this, and at least do the research (which you may already have done, but it's not coming across in your question) to determine if it's something you even need.

Regarding OpenGL vs D3D memory usage, my *guess* (and it's just a guess) is that D3D is storing the system memory backup in user space, whereas your GL driver is storing it in kernel space.

I made a point of saying "your GL driver" above because that leads me into the second thing: because a GL driver is fully implemented by the hardware vendor, different GL drivers may behave differently. Your driver may be OK with the amount of memory you're using, a user of your program may have different hardware from a different vendor with a different driver that may not be OK.

What I'm saying here is that you have a bigger problem on your hands than this difference between GL and D3D on your own machine. You have a problem that may also prevent your program from working on other people's machines under GL.

The underlying cause here is that large amount of texture memory you're using. There are standard approaches for dealing with this: using compressed textures, using lower resolution textures in low memory scenarios, unloading textures that aren't needed any more, implementing texture streaming. As well as reconsidering the XP requirement, that's something that you may need to work on.

---
Tags: opengl, directx
---


# Question
Title: How can I avoid applying textures to a fragment in a shader when the surface normal is (0, 1, 0)?
I have a small GLSL shader with a vertex shader and a fragment shader. I want to avoid applying textures to faces that have a normal equal to `(0, 1, 0)`. Is this possible? These are my shaders:

Vertex:

```
#version 120

varying vec2 UV;
varying vec3 normal;

void main()
{
  UV = gl_MultiTexCoord0;
  gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
  normal = gl_Normal;
}

```

Fragment:

```
#version 120

varying vec2 UV;
uniform sampler2D diffuseMap;

void main(void)
{
  gl_FragColor = texture(diffuseMap, UV);
}

```

# Answer
Use an if-statement in the fragment shader and pass through the normal or a flag from the vertex shader.

Note that sampling of textures must be in uniform flow, i.e. outside of the if-statement. Something like the following probably-not-legal-GLSL:

```
// vertex
in vec4 aPosition;
in vec3 aNormal;

out vec3 vsNormal;

void main(void)
{
  gl_FragCoord = project_transform * aPosition;
  vsNormal = aNormal;
}

// pixel
in vec3 vsNormal;

void main(void)
{
   vec4 tex = texture2D(blah);
   vec4 color = vec4(1, 1, 1, 1);

   // depending on the input normal,
   // you should better normalize it in the fragment shader before you use it
   vec3 normal = normalize(vsNormal);
   float dotN = dot(vsNormal, vec3(0,1,0));

   if (dotN < 0.99)
     color *= tex;
   else
     really_simple_effect();

   gl_FragColor = color;
 }

```

Note that you want to deeply minimize the amount of code you use inside of any branch in a shader. You might be best off simply rendering a 5-sided "cube" for the sides/bottom and then a separate plane for the top with two totally different materials/shaders. Batch as much as you can (e.g. draw all the 5-sides parts in one go, then draw all the tops in a second go).
> 3 votes

---
Tags: shaders, glsl
---