# Question
Title: Why would Rigidbody.AddForce not resulting in movement of my objects?
I'm trying to get my card objects to spread out randomly but nothing happens. I know the method is called cause I get the prints in the console for each card. But they don't move. No errors reported. The cards have a `RigidBody`.

```
public static void CardCascade ()
{
     print ("CARD CASCADE!");
     foreach (var card in Card.Cards) {
          float range = 500F;

          var x = Random.Range (-range, range);
          var y = Random.Range (-range, range);
          card.rigidbody.AddForce (x, y, 0);
          print ("I just added force to card: X/Y " + x + y);
     }
}

```

# Answer
**Don't miss the last argument to AddForce(), `ForceMode mode`.** The default mode `ForceMode.Force` (*kg·m/s²* or *N*) works in the most physics-natural way, but you also have the option of making the addition mass-independent (`ForceMode.Acceleration`, *m/s²*), or velocity-based instead of acceleration-based (`ForceMode.Impulse`, *kg·m/s*), or both mass-independent and velocity-based (`ForceMode.VelocityChange`, *m/s*).

In general, the acceleration-based pair (`ForceMode.Force` and `ForceMode.Acceleration`) are best for over-time effects (in FixedUpdate(), as suggested by @danijar), while the velocity-based pair (`ForceMode.Impulse` and `ForceMode.VelocityChange`) are best for one-time effects (in Start(), Update(), FixedUpdate(), etc.). And it's not like either won't work in either situation, it's just that the values you'll end up using are aligned to each situation. *E.G. Using `ForceMode.Force` with a force of `30.0 * Time.fixedDeltaTime` for a one-time burst should work fine, but using `ForceMode.Impulse` with just `30.0` is more semantically meaningful.*

Setting the Rigidbody's `.velocity` directly is not recommended if the Rigidbody is already moving— the Rigidbody does a number of things internally that will likely cause the resulting velocity to not match what you set it to. I suppose it's in there and settable for esoteric setups or custom physics system hacks, like setting an initial value for `velocity` within Start() in a situation where everything should be moving from the get-go. However, the recommended way to accomplish `rigidbody.velocity += 5.0` is `rigidbody.AddForce(5.0, ForceMode.VelocityChange)`.

---

Your code looks as if it's for a card game, so if you do indeed want the cards to move at a predictable speed in a UI-ish manner, `ForceMode.VelocityChange` may be your best bet.
> 2 votes

# Answer
Force makes rigid bodies accelerate, so their speed grows over time. Most physics engines reset the applied force every frame. Therefore, you need to apply force for several frames to give the bodies time to accelerate.

Another solution would be to set speed directly, instead of applying force. That would result in instant motion.
> 0 votes

---
Tags: unity, physics
---


# Question
Title: 2D Tiled Map - Small tiles or big tiles with pixel-precise movement
I am using Java - LWJGL - Slick2D . I have tried to do a proper collision detection with 32 x 32 tile size but failed three times. I just cant get it to work! I found a youtube video that was using ligbdx (but the code was understandable) that used small tiles and achieved something like pixel-precise movement , so here is the question , NOT opinion based. Keep trying to make a legit collision system or use small tiles? Also , please give me some info related to your answer like "tiles need to have X times Y size" or "a good resource is X Site for pixel-precise movement".

# Answer
> 0 votes
You probably had some problem in your code, because basically collision detection can always be resolution independent, so it won't matter whether your tiles are 8x8 or 1024x1024.

The following would be just one possible workflow to achieve this. Note that I didn't care for strict casting etc. so there might be cases where you'd have to cast an `int` to `float` go get the needed precision or where you'd have to cast a `float` to `int` to get the modulo operator to work.

Determine the tile where to check for a collision. How you'll have to do this really depends on your coordinate system. It could be as easy as rounding down your coordinates:

```
int tile_x = (int)(x / tile_width_in_world);
int tile_y = (int)(y / tile_height_in_world);

```

These coordinates can be used to get a first estimate, whether there's more work to be done, i.e. whether there's just sky, some ground (i.e. pixel testing needed) or only ground.

If you need pixel perfect testing, the next step should involve determining the position within the tile you'd be looking at:

```
float check_x = (x % tile_width_in_world) / tile_width_in_world;
float check_y = (x % tile_height_in_world) / tile_height_in_world;

```

This would result in two values, each ranging from 0 to 1 based on where in the tile your position is. This can then be converted to pixel coordinates within the actual tile texture:

```
float real_check_x = tile_offset_x + check_x * tile_width;
float real_check_y = tile_offset_y + check_y * tile_height;

```

---
Tags: java, collision-detection, lwjgl, slick
---


title: glGenBuffers fails with 0x0, win7, glew

text:
# Question
Title: glGenBuffers fails with 0x0, win7, glew
I try to run a simple renderer on my win7 machine but it dies at the first glGenBuffers call. The computer has an Intel HD3000 card, with the latest driver (OpenGL 3.0 support). I use glew 1.10 (self compiled with mingw). The linker command is:

```
g++ -LC:\Program Files\Microsoft SDKs\Windows\v7.1\Lib -Lc:\opt\glew-1.10.0\lib -LC:\opt\SDL-1.2.15\lib\x86 -o pysicsdemo.exe src\main.o src\Box.o -lOpenGL32 -lglu32 -lSDLmain -lSDL -lglew32.dll

```

And the result is 0x0. Most probably glew can't load the extension, but why?

# Answer
> 1 votes
Ok. I forgot to call glewInit. I leave this here just in case if anybody is as stupid as me...
So glew won't find the extensions unless it's properly initialized - explicitly. Always call `glewInit()` first and check whether it was successful or not by comparing the result to `GLEW_OK`, as written at the glew website.

---
Tags: opengl, mingw, glew
---


# Question
Title: Is this really the reason for smoother movement?
Actually i'm watching a tutorial series on youtube about 2D Game programming in Java. My question is about the player-movement.

The first version:

```
        public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();

            if(key == KeyEvent.VK_RIGHT) {
                player.setX(p.getX() + 5);
            }else if(key == KeyEvent.VK_LEFT) {
                player.setX(p.getX() - 5);
            }else if(key == KeyEvent.VK_DOWN) {
                player.setY(p.getY() + 5);
            }else if(key == KeyEvent.VK_UP) {
                player.setY(p.getY() - 5);
            }
        }

```

The problem in this first version is, that if you press now for example VK-RIGHT (and holding it), than the figur in the game moves first one step to the right, then stops for a half second or so and then the figur moves constantly to the right. The problem here is the stopping, which takes a half second or so. This is not smooth.

Then the author of the tutorial presented a second, better version:

```
        public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();

            if(key == KeyEvent.VK_RIGHT) {
                player.setVelX(5);
            }else if(key == KeyEvent.VK_LEFT) {
                player.setVelX(-5);
            }else if(key == KeyEvent.VK_DOWN) {
                player.setVelY(5);
            }else if(key == KeyEvent.VK_UP) {
                player.setVelY(-5);
            }

        }

        public void keyReleased(KeyEvent e) {

            int key = e.getKeyCode();

            if(key == KeyEvent.VK_RIGHT) {
                player.setVelX(0);
            }else if(key == KeyEvent.VK_LEFT) {
                player.setVelX(0);
            }else if(key == KeyEvent.VK_DOWN) {
                player.setVelY(0);
            }else if(key == KeyEvent.VK_UP) {
                player.setVelY(0);
            }

        }

```

and the tick() method in the Player.java:

```
public void tick() {
    x += velX;
    y += velY;
}

```

The author said, that the second version is smoother, because we don't need to ask first with the get-methods the actually value of x/y. Is this really the reason, why the second method is smoother respectively we don't have still this stop for a half second or so?

If this is really the reason, why the start time of the player figur is in both version the same? In the first version the player figure would then have to need more time to start movement? But this is not the case! The difference is this stop for a half second or so after the first steop of movement is finished.

# Answer
> 11 votes
The get methods do not take so much time, so you're right - this isn't the reason. What's probably happening is that the `KeyEvent`s aren't executed every tick, but are showing the same behaviour as you expect in a browser or anywhere else - when writing something and you move the cursor with the arrow keys, it first moves one space, then stops, and only after half a second or so continues moving. In the second version, you only use the `KeyEvent` to set the velocity of the player, which is then applied on every tick without pause.

# Answer
> 6 votes
The first method relies **directly** on the key presses.

It's a standard behavior ( probably coming from the operating system ) for there to be a delay before it starts repeating itself. That's why it moves, then stops and then keeps moving afterwards.

The second method sets a value for the velocity which is then applied to the x position. It's not exactly clear whether your event or tick() function is called first.

When you press the right key, it adds 5 ( or subtracts it if it's the left key) from the x value. When you release the key the velocity is set to 0. So when the tick() function is called 0 is added to the x property.

You have to think in logical steps. It's smoother in the sense that the movement depends on a value rather than a direct key press. You basically "turn" the value "on" by key presses and "turn" it "off" by releasing a key.

Edit: A lot of game frameworks come with something like an Input manager which you can check in your tick() or update() function.

# Answer
> 1 votes
No, the game code has nothing to do with it. I don't know where he got that idea from and if that is what he said, you should look elsewhere for tutorials. Sounds more like BIOS / OS-level key-repeat functionality to me, which should be bypassed for games.

Typically there are two types of key / button input supported for games:

* Press OR press-and-hold results in a single frame's worth of action (like hitting F1 for help -- holding makes no difference)
* Press and hold results in contininuous action between frames (like holding for movement)

Usually the underlying input API is written in such a way that the key-repeat functionality is ignored altogether, and input values are stored in a boolean buffer that indicates whether each key is up or down. Then additional functionality such as one-press keys (F1) can be built on top of that.

You can certainly do that in Java quite easily, as I have in the past.

---
Tags: java
---


# Question
Title: How to get pixel coordinates between 0,1 from SV_POSITION
I am new to HLSL and Directx. I was trying to write a simple gradient Shader by modifying one of Microsoft samples.

1.I can not understand why SV\_POSITION is float4? If it is pixel coordinates shouldn't it have only x and y ? What are the 4 parts? I think SV\_POSITION is not between 0,1 and the maximum val is bufferWidth,bufferHeight ... then how can I get the position between 0,1?

1. The first code does not work because distance between float2 and float4 is impossible. While the second one works I get a warning. How can I avoid the warning message because I believe something is wrong!

Fist code (Of course it should not work):

```
float4 VS( float4 Pos : POSITION ) : SV_POSITION
{

    return Pos;
}

float4 PS(   float4 Pos : SV_POSITION) : SV_Target
{
    float distfromcenter=distance(float2(0.5f, 0.5f), Pos);
    float4 rColor = lerp(float4(0,0,0,1),float4(1,1,1,1), saturate(distfromcenter));
    return rColor;
}

```

The second one :

```
float4 VS( float4 Pos : POSITION ) : SV_POSITION
{

    return Pos;
}

float4 PS(   float2 Pos : TEXTCOORD  ) : SV_Target
{
    float distfromcenter=distance(float2(0.5f, 0.5f), Pos);
    float4 rColor = lerp(float4(0,0,0,1),float4(1,1,1,1), saturate(distfromcenter));
    return rColor;
}

```

Why do I get this warning ? How can I compile this Shader using SV\_POSITION to avoid the warning message ?

```
D3D11 ERROR: ID3D11DeviceContext::Draw: Vertex Shader - Pixel Shader linkage error: Signatures between stages are incompatible. The input stage requires Semantic/Index (TEXTCOORD,0) as input, but it is not provided by the output stage. [ EXECUTION ERROR #342: DEVICE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND]

```

# Answer
> 0 votes
I'm new too in directx and not very good in english so i havent understand your question at all but...

Try to change the pixel shader like this:

```
float4 PS(float4 Pos:SV_POSITION):SV_Target //pos contain x,y,z,w but you only need x,y
{                             //remember PS is called for each pixel and so it must now the pixel-screen position
pixelPosX=Pos[0]; pixelPosY=Pos[1];//theese are the pixel coordinates in the window start from top-left corner and are integer ones(ex. 100-200, 0-0, window_width, window_height)
...
}

```

If the backbuffer width\_height are different from window ones, i dont know if the max Pos\[0\] value( and Pos\[1\] too) is the window width or the bck buffer one.

Hope that it works.

Look the comment.

```
#define MAX_X 640
#define MAX_Y 400
Vertex shader....

float4 PS(float4 Pos:SV_POSITION):SV_TARGET
{
 int x=Pos[0]/MAX_X;
 .....
}

```

---
Tags: directx, shaders, hlsl
---


# Question
Title: Is there a way to optimize this 2D lighting effect shader?
I'm doing a little 2D game in C++ with Direct3D 11.

In the game I want to render a sort of shadow that covers part of the screen:

To do this I am using this pixel shader:

```
float4 PS_Main( PS_Input frag) : SV_TARGET
{
    float4 color = {0, 0, 0, 1};
    for (int cont=0; cont<lights; cont++)
    {
        int dist = pow(frag.pos[0] - singleLight[cont][0], 2) + pow(frag.pos[1] - singleLight[cont][2], 2);

        if (dist < singleLight[cont][3] * singleLight[cont][4])
        {
            color[3] -= 1 - (dist / (singleLight[cont][5] * singleLight[cont][6]));
        }
    }

    return color;
};

```

The constant buffer I pass to the shader is:

```
cbuffer PSbuffer : register( b0 )
{
    int lights;
    float4 singleLight[15];
};

```

I also pass an array to the shader, each element of which contains the position and radius of a light.

The code works with more than one light, but if I try to use more than ten lights the FPS drops down to 40 or 50. How can I optimize this effect?

Thank to all!! I try to optimize the pixel shader code but i earn 4-5 fps so i decide to to a "light map" in this way; I create a second Render Target View i will use to render the lights(sprite i draw). The light will be alpha-channel inverted in order to have to clear the render target view with color{0,0,0,0}; draw the light on the second target view like this: and then create a texture with this render target view and render it on the first with a shader that invert the alpha channel (color.a=1-color.a); but, since i am new in directx i dont now how to do it and i cant find a good tutorial.Can you help me??

# Answer
> 1 votes
You could create a (low-resolution) "light map" in which you render your "lights" and then do a simple postprocessing pass in which you multiply both sources.

Loops in shaders tend to become expensive very quickly.

As a short term improvement: Try removing the if, at first glance it looks easy to replace.

Jumps (including ifs) are also expensive.

# Answer
> 1 votes
A few comments:

* is `frag.pos[1] - singleLight[cont][2]` correct? I think you want `[1]` here.
* `pow(x, 2)` is not guaranteed to be understood as `x * x` and might therefor be slow.
* avoid `if()` when what’s inside is not very complex, try to use `min`, `max`, `clamp` *etc.*

Here is how I'd rewrite the shader:

```
float4 PS_Main( PS_Input frag) : SV_TARGET
{
    float4 color = {0, 0, 0, 1};
    for (int cont = 0; cont < lights; cont++)
    {
        float2 V = frag.pos.xy - singleLight[cont].xy;
        float K = 1.0 / (singleLight[cont][2] * singleLight[cont][2]);
        color.a -= max(1.0 - K * dot(V, V), 0.0);
    }

    return color;
};

```

Final note: if all you’re going to do with `singleLight[cont][2]` is compute that value `K`, you should precompute `K` on the CPU instead. That’s one more computation on the CPU, but several million fewer divisions on the GPU. The fragment shader would then be:

```
float4 PS_Main( PS_Input frag) : SV_TARGET
{
    float4 color = {0, 0, 0, 1};
    for (int cont = 0; cont < lights; cont++)
    {
        float2 V = frag.pos.xy - singleLight[cont].xy;
        color.a -= max(1.0 - dot(V, V) * singleLight[cont][2], 0.0);
    }

    return color;
};

```

---
Tags: directx, optimization, fragment-shader
---


# Question
Title: Is there a way to limit the size of the D3DPOOL_MANAGED pool?
I have over 2GB of textures that I need to put in D3D9's `D3DPOOL_MANAGED` pool.

D3D9 charges the system copy of anything in the `D3DPOOL_MANAGED` to my process space. I'm working on a 32-bit system so I have less than 1.7GB of available process space.

Is there a way to limit the size of the pool D3D9 stores in my process, that is to tell it to keep anything else it needs to cache on disk?

# Answer
> 2 votes
No. You will need to implement that behavior yourself.

A simple way to do this is to wrap the D3D texture object in your own type (in order to allow you to keep the references to that texture while still dropping and reallocating the underlying D3D texture):

```
struct TextureReference {
  IDirect3DTexture9 * GetTextureObject();

  std::size_t GetSize() const;
};

```

Keeping all these in a central pool via a dictionary or set will allow you to know the size consumption of all textures. When you start to reach a limit, you can evict textures based on size or last-recently-used timestamps or whatever else you'd want to track.

It's tricky because getting the in-memory consumption of a texture from D3D is not reliable, so you'll be leveraging guesswork most of the time to implement `GetSize`. You can use the on-disk size of the texture as a baseline and add padding as necessary.

This method also allows you sufficient abstraction to implement this pooling as one giant "megatexture-like" back-end D3D texture, where you load new textures by rendering them into available regions on the single backing texture and evict them by marking the regions as empty. This does require a good bin-packing algorithm, but it could help with problems related to GPU-memory fragmentation (since you can allocate a fixed-size texture as large as you can get away with and that consumption stays fixed). However, if you find yourself needing to swap textures frequently it could be a performance issue. It is probably worth considering, though.

---
Tags: directx9, resource-management
---


# Question
Title: Should references between assets be handled by name or ID or something else?
How should content or asset items be referenced in their serialized form?

For example, a material might need to reference several textures. The simplest way would be to use a path, relative to the base directory of the assets.

Alternatively, all content items could be referenced by an ID. I implemented it this way (using GUIDs), which allows content items to be renamed or moved without breaking references. However, this makes it more difficult to replace a content item (delete the original, then rename something else to the same name... requires copy/pasting GUIDs around). It also makes debugging missing content trickier.

Is there a clear winning option here?

# Answer
> 8 votes
**String-keying / Hashmaps**

* Are fast, as read time is amortized O(1), meaning that read access is usually very fast, but in worst cases (rare, but not unheard of), it can be quite slow. Worst case results from hash collisions.
* Implementations sometimes have to be built, or found (for instance, in C). Writing / finding a performant string-keyed map implementation can be non-trivial.
* String comparisons can be expensive, though whether this is pertinent depends on your language's implementation of both hashmap read ops, and string equality implementation.
* May make it possible for you to inadvertently create duplicates or overwrite existing values (depends on implementation).

**Numeric keying / arrays**

* Are very fast, because the structure you're adding to maps directly to memory (as per arrays in most languages)
* Are very fast, because numeric equality is checked rapidly (at least for sufficiently small bitwidths)
* Are very fast, because long, contiguously-allocated arrays can have superb cache performance (caveat: this depends very much on your choices of language and implementation).
* Require that your "GUID" is not too large to act as an array index. However, fast options can be found to work around this, such as breaking up your ID (via bit ops) to use as two sufficiently-short indices per element in a 2D array.
* Are inconvenient, for the reasons you've mentioned. If the IDs are compile time values that you need to be able to develop with, it's less of a problem, since they can be assigned to appropriately-named ALL CAPS constants and used that way.
* Can reference structures that contain a human readable name. This offers some convenience, even if they can't be accessed by this name.

**Conclusion**

Unless you are going to be processing *many* elements (say, tens of thousands) per 16-20ms tick using either of these options, I wouldn't worry about numeric IDs, and particularly if you are using a language where efficient hashmaps are already available, just opt for a hashmap.

Otherwise, the numeric ID / array approach is good for conserving CPU cycles, but go for this in cases where resources come at a premium.

# Answer
> 6 votes
I would strongly advocate the use of IDs, and GUIDs especially. GUIDs have a number of excellent advantages:

* They can be generated locally and still preserve their uniqueness. Simple numeric IDs require a central authority to guarantee uniqueness, which makes them immediately more cumbersome to use once you have more than a single person working a project.
* Altering the name of an asset does not require the expensive operation of locating all the references to that old name and updating them. Not only is this error-prone, it *also* has severe problems in a world where many people are collaborating on a data set (if somebody is working on a file *referencing* the one you are changing, then either you are forced to wait or they are forced to resolve the merge).
* Moving assets around within the filesystem or logical hierarchy of the content store does not require updating any references *either*.

GUIDs do have disadvantages, but they are all solvable with a little effort.

* They are hard to remember and type, which means it can be difficult to collaborate with another user ("Look at object {CD0B6FBB-1156-4BCF-A5EB-82967376090E}" is a bit cumbersome). However, you can build into your asset editing toolchain a way to look up objects by name, or even better, build a URL scheme for your tools that allow you to generate clickable links that load up the tools viewing the desired asset.
* They are big. This is generally not as much of a concern during development, but is for shipping the code. However, it's very easy to support a data-compile-time step that produces a remapping from GUIDs to integer IDs when baking final content for the game.

On Guild Wars 2, we used named-references to content for several years early in development. It was the wrong decision and hamstrung the performance of our tools for quite some time before we were able to transition to GUIDs. Every project I've ever worked on that used named-references had trouble with them, so I would absolutely recommend against them. The effort it takes to build tool support around GUIDs is less, in the long run, that it will take to cope with named-references.

If you have a small project, just by yourself or *maybe* a handful of others you can get away with using IDs (giving each person a dedicated "block" of IDs, for example, can easily avoid the clashing problem for some time). But if you have a small project the overhead of GUIDs isn't likely to be problematic *either*, so I'd just say you should use those for the best future scalability.

# Answer
> 1 votes
It is easier to think about it when you make a distinction between external identifiers and internal identifiers. An asset has a unique external identifier that is referenced in configuration files, makefiles, documentation, etc. Once an asset has been loaded into your application the assets might get an efficient internal identifier for internal referencing.

For the external identifier, I would use a consistent naming scheme, following the convention over configuration paradigm. So you might want to use a path-based scheme such as 'resources/textures/walls/concrete.png'. This identifiers tells you a lot: that it is a resource, that it is a texture, that it belongs to the texturegroup 'walls' and even where it can be found on the disk. Plus it is human-readble, much more so than a GUID.

For the internal identifier, you can choose to use either memory locations (pointers), increasing integers or GUID's. Ofcourse you can also opt to use the external identifier as your idental identifier, at the cost of higher memory-usage and slower performance.

To get an internal identifier from your external identifier you will most likely need a central mapping/repository in your application. Typically the resourcemanager that loads your resources can be used for this.

Finally, about the point of missing references: as resources are typically lazy-loaded at runtime, you should have some kind of test-suite or integrity check for your application anyway, so I don't think it will matter much what kind of identifier scheme you will use.

# Answer
> 0 votes
There's no best approach, because it always depends on the actual use case and your overall architecture.

Using IDs or GUIDs won't necessarily be easier to use or replace. Just remember that you'll have to copy and use those as well. Especially GUIDs are typically rather long and hard to remember without copypasting. Same can be true for raw numbers of some kind.

As such, "talking" names are probably the best approach, even if this involves some more writing or replacing.

What you can do, is using some fixed length identifier. For example, you could use 4 alphanumeric characters to identify everything. This also has the added advantage, that you'll be able to easily cast the ID (string) to an integer (just keep byte order differences in mind) and compare it the fast way.

This could also be extended to the file name as well, so you won't have to refer to full paths either. For example, if I use "NMY1" for my first enemy, it's data would be stored in the file "NMY1.dat", with the texture sitting in "NMY1.png", script code in "NMY1.lua", etc.

Another thing would be modability: If you want users to be able to easily mod your game, try to avoid overoptimizing it. I.e. prefer talking names over abbreviations, don't use raw IDs or GUIDs and use something easier to read/understand/copy instead, even if that means you might have to update lots of references as well.

If your data gets too complex to easily update/check, write tools to do it for you (and to verify integrity as well) or rethink your approach.

---
Tags: architecture, design-patterns, asset-management
---


# Question
Title: How do I change the window position in Unrealscript?
So when I start my game it starts out in the middle of my screen at 1024x768 resolution, but then when I change the resolution via `consolecommand("SETRES ...");` it resets the window position to the top left of my desktop.

Is there a way for me to set the windows position after I make this change?

# Answer
As far as I am aware, there isn't; I think `SETRES` is intended to be used in conjunction with the game running in (or toggling almost immediately to) full-screen.

However, it's possible that you could write a C++ extension DLL to provide yourself a scripting command to move the window (you'd want to use Win32 method to locate the window and call `SetWindowPos` probably).

It's also possible that you can achieve what you want by setting the appropriate values in the viewport frame of the game client object, if you have access to it.
> 1 votes

---
Tags: udk, scripting
---


# Question
Title: What exactly does SDL_RenderSetClipRect do?
I assumed that this function would move the area which is clipped out of conceptual space and copied onto the renderer (and subsequently drawn to the window) - i.e. change the origin of rendering - but it doesn't seem to do this. Anybody know how it works?

# Answer
> 4 votes
From the source code (available via the website):

```
int
SDL_RenderSetClipRect(SDL_Renderer * renderer, const SDL_Rect * rect)
{
    CHECK_RENDERER_MAGIC(renderer, -1)

    if (rect) {
        renderer->clip_rect.x = (int)SDL_floor(rect->x * renderer->scale.x);
        renderer->clip_rect.y = (int)SDL_floor(rect->y * renderer->scale.y);
        renderer->clip_rect.w = (int)SDL_ceil(rect->w * renderer->scale.x);
        renderer->clip_rect.h = (int)SDL_ceil(rect->h * renderer->scale.y);
    } else {
        SDL_zero(renderer->clip_rect);
    }
    return renderer->UpdateClipRect(renderer);
}

```

A little more digging reveals that `UpdateClipRect` is dispatched based on the underlying rendering API (D3D or OpenGL), and all it does is used the computed rectangle above to set the scissor test rectangle.

It does not do anything related to transforming coordinate systems; it just means that anything rendered to the window that falls *within* that rectangle will be rendered, and anything *outside* of that rectangle will be discarded. That's generally the meaning of "clip" in graphics terms.

# Answer
> 1 votes
Assuming that function works similarly to the glScissor test, all it does is test if the pixel falls within the defined rectangle. If it falls outside that rectangle, it's discarded.

---
Tags: sdl
---


# Question
Title: What's the difference between Textures and VertexTextures in XNA?
The `GraphicsDevice` class of XNA has the properties `Textures` and `VertexTextures`.

What is the exact difference? I don't really understand what MSDN tells me about this.

I usually use `Effect` parameters to pass textures to my HLSL shaders. What are the differences between these methods, which is faster?

# Answer
`GraphicsDevice.Textures` are your "traditional" textures; the one's you sample from during the fragment shader.

`GraphicsDevice.VertexTextures` are textures that you want to sample from in the *vertex* shader, which required specialized HLSL instructions (`texldl`, as noted in the documentation) on the D3D9-class hardware that XNA is based on. Vertex textures were a half-measure towards the more unified shader resource input pipe that is available on modern cards, but not via XNA. You probably do not need to concern yourself with the `VertexTextures` property for the time being.

Using the `Effect` API to send textures to the shader will, under the hood, do exactly the same set of steps that you would need to do if you manually assigned textures to specific samplers. I would recommend you continue to just use the `Effect` methods as they are likely going to be easier for you, since you already understand them.
> 2 votes

---
Tags: xna, xna-4.0, textures, performance, hlsl
---


# Question
Title: How do I access the pixels of an SDL 2 texture?
How exactly can one get to the RGBA pixel arrays of SDL 2.0 textures? Does the texture need to be specially initialized and locked down?

# Answer
> 3 votes
Call `SDL_LockTexture` to get the data and `SDL_UnlockTexture` when you are finished:

```
byte * bytes= nullptr;
int pitch = 0;
SDL_LockTexture(texturePointer, nullptr, reinterpret_cast<void **>(&bytes), &pitch);

// ...read data...

SDL_UnlockTexture(texturePointer);

```

Both methods have return codes you should check for errors, obviously.

The `bytes` pointer will refer to the locked bits of the texture, and the `pitch` variable will contain the number of bytes between successive rows of a texture (to account for padding).

Note that the texture must have been created with the streaming access flag (`SDL_TEXTUREACCESS_STREAMING`).

Also note that you get the raw bytes of the texture data, which may not always be RGBA (for example, the texture may not have alpha).

---
Tags: sdl, pixel
---


# Question
Title: Why does my object "jump" immediately as the game starts?
I'm having a problem where, when I start my game, my game object (a 3D plane) immediately jumps 300 pixels or so. I suspect this has something to do with my joystick handling code that I've written to move this game object:

```
 xMin1 += Input.GetAxisRaw("LeftRight");
 yMin1 += Input.GetAxisRaw("UpDown");

 //_targetPlane is my game object
 _targetPlane.transform.position = new Vector3(xMin1, yMin1, 2.5f);

```

The object jumps even if I don't touch the joystick. Am I doing this wrong?

# Answer
You can confirm that the problem has anything to do with your joystick code by commenting out the code. If that fixes the behavior, the problem is likely how you are interpreting the data or initializing the variables. If it doesn't, you will need to debug your code elsewhere because there's nothing else we can do for you with this limited information.

If commenting out the code fixes the problem, take the following steps:

* Verify that both `xMin` and `yMin` are initialized to zero using your debugger. It might be useful to log them or to log the position of the object every frame, that may help identify the problem.
* If your joystick is not *perfectly calibrated* to rest at dead center (most aren't), you may be getting non-zero input even when the stick appears at rest (which will quickly accumulate and move your object). Log the values returns from `GetAxisRaw` to confirm this (Unity may or may not do the usual dead-zone computation to handle this for you, I'm not sure, but it's worth checking).
* Note that `GetAxisRaw` doesn't do smoothing, and generally the values returned by `GetAxisRaw` should be weighted by delta time, as in the linked example code from `GetAxisRaw`. You may alternatively want to consider `GetAxis` instead.
> 3 votes

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


# Question
Title: Is it more efficient to store my tile grid as a dictionary or an array?
I've just started making a video game in AS3, and I'm trying to keep the graphics, sound, and actual game state in three completely different spots and sets of classes. That being the case, the graphics module will have to repeatedly parse the state module. The game is divided into levels, and each level is divided up into square spaces (like a board game); thus the graphics module will have to repeatedly parse out a certain cross-section of spaces of the current level.

The player will always show up in the middle of the spaces' overall graphic (the "Grid"), and there will be 4 spaces in every direction from the player's positioin that will be displayed, along with any object each space may contain (such as the player, a monster, etc.).

So right now I'm trying to decide how to store the spaces in each level (all of the level's spaces themselves, not the graphics). The first thing that came to mind was a 2D Array. Then I started to use a 2D Vector, then came back to using an Array, like at first; and now I'm wondering whether to use an Array or a Dictionary.

The problem:

Let's say a level looks like this:

```
xxxxxxxxxxxx
xxxxxxxxxxxx
xxxxPxxxxxxx

```

x's are blank spaces, P is the space that the player. As the Grid parses this information, if it's a 2D Array, then it can use the length property of the main Array and the length property of each sub-array to set up its for loops reasonably well. Furthermore if a space is outside the bounds of the 2D array, then rather than wasting memory trying to form more objects in the code or something, the Grid can just assume the space is blank:

```
var arr:Array;
var space:Space;

for (var i:int = level.playerX - 4; i <= level.playerX; i++)
{
    arr = level.spaces[i];
    if (arr)
    {
        for (var j:int = level.playerY - 4; j <= level.playerY; j++)
        {
            space = arr[j];
            if (space)
            {
                // find every object inside space and animate accordingly
            }
            else
            {
                // assume the space is blank
            }
        }
    }
    else
    {
        // assume the whole column of spaces is blank
    }
}

```

Within the player's radius, the Grid must animate any non-existent spaces as blanks. Therefore the graphical output is as follows:

```
xxxxxxxxx
xxxxxxxxx
xxxxxxxxx
xxxxxxxxx
xxxxPxxxx
xxxxxxxxx
xxxxxxxxx
xxxxxxxxx
xxxxxxxxx

```

But now if we have a level that looks more like this:

```
xxxxxxxxxxxxx
xxxxxxxxx
    Pxxxx
    xxxxx

```

then using an Array leaves two basic options:

1. Use null elements within the sub-arrays to get the Grid to animate non-existent spaces that come before the real ones in the sub-array (the sub-array's length can be used for non-existent spaces that come after the real ones).
2. Make that simple for-looping inside the Grid a whole lot more complex to compensate for rows and columns of spaces starting at variable locations along each axis (and not simply ending at variable locations).

I don't want to use option 2. I was just going to use option 1 with Arrays, but now the possibility of using Dictionaries instead has come to mind. At least with Dictionaries, I wouldn't have to just waste memory every time I wanted, let's say, for the first space in a row to begin at postion 5.

Sorry, I know this was lengthy, but I hope I've illustrated the problem. Which is better - an Array, or a Dictionary? If a Dictionary is better, should it use sub-Dictionaries or sub-Arrays to establish a 2-dimensional effect? Thanks!

# Answer
Use a (single dimension) array. You can treat such an array as "2D" for the purposes of accessing tiles with some simple math:

```
var tile = tiles[y * width + x];

```

This will allow you to access the tile at position (`x`, `y`) but still retain the benefit of having all your data in a single contiguous array, rather than an array-of-arrays approach, which has poorer locality-of-reference (although if you have access to actual contiguous 2D rectangular arrays in your language, you could those too). Keep your levels rectangular tile grids, even if some tiles are not used (the "null" tiles in your previous example can be represented by a sentinel value, such as `0` if all you are storing are tile IDs, or `null` if you are storing actual `Tile` references).

The rationale here is that most of the time you're going to be looping over regions of the tile grid to check or do something with a bunch of tiles. It benefits you to be able to access and iterate those regions quickly, and an array provides `O(1)` random access and quick iteration. Dictionaries can also provide `O(1)` access for hash-based implementations with a good hash selection, but sometimes that becomes amortized and even when it isn't, the constant factor is usually higher. Iteration over dictionary keys is usually not as efficient (or even possible in the fashion you'd need), so they make a sub-par choice here.

In fact the only *potential* benefit you get from a dictionary really seems to be a reduction in memory overhead for severely pathological maps where the actual used set of tiles in the grid is small compared to the unused set. In practice, I don't think that will be enough of a benefit to offset the runtime performance or complexity issues, because the amount of data we're talking about here is usually quite small.
> 2 votes

---
Tags: actionscript-3, level-design, data-structure, efficiency
---


# Question
Title: How do I organise the code for an episodic game?
We're working on a game that's going to be split into three episodes, which we'll release one after another, as they get finished. I'm worried that our typical somewhat-monolithic architecture is not a good fit for this model.

The game code consists of basically three parts:

* `_Engine_`: Renderer, physics, UI etc.
* `_Logic_`: The concrete scenes and entities.
* `_Scripts_`: Levels and dialogs.

`_Engine_` and `_Logic_` are native code, `_Scripts_` are shipped with the game data and executed at runtime.

I think I can safely assume that:

* `_Engine_` will be the same for all episodes.
* `_Logic_` will be largely the same for all episodes. but have some specific parts.
* `_Scripts_` will differ significantly for each episode.

---

I see three options for organising this:

1. Create episode two by copying all the code from episode one, adjusting as needed. I believe this is how sequels are typically done; id Tech 4 appears to be part of the *"Doom 3"* code, not clearly separated.
2. Keep all the shared code in one place, making it possible for each episode to override parts of it.
3. Create a reusable engine, completely separating `_Engine_` from `_Logic_` and `_Scripts_`, to be used by all episodes. Shared `_Logic_` will either be duplicated for each episode, or generalised and moved into `_Engine_`. This is how the folks behind *"Penumbra"* apparently did it.

The major drawback I see with the first approach is that I'll have to back-port any fixes and refactoring to episode one, manually.

The major drawbacks I see with the second approach is that it's more upfront work, and that I'll have to make changes to already released episodes, requiring me to keep testing them.

The major issue I have with the third approach is that it's a big amount of upfront work. and smells a bit like premature generalisation. I cannot fully predict what changes I'll have to make for episodes two and three; it depends on their unfinished design. On the other hand, it would probably give us more flexibility, and speed up development, later.

What is the typical way of organising the code for episodic games? Do I have options, other than the three I can think of?

# Answer
> 7 votes
If you're already putting in solid efforts to abstract engine code from game code, AND you want to keep your various game projects up-to-date with the latest version of the engine, then and only then would I suggest keeping it in a separate repository, since that would make it worth the effort.

Otherwise, if you're only developing a single game, don't worry about doing this till the game has been or is about to be released, i.e. *when you have time for it*. Until you start writing a second game, you have no guarantee that the code needs to be separated, so it's likely to be a waste of time.

If your goal is to write a game, then you will use your time effectively and focus on that and only that. That is plenty of work as it is, without self-imposing additional concerns.

Whereas if you, for instance, have multiple projects on for clients and wish to use / are using the same engine, then you / your company might make a smart business decision by abstracting out your engine code in every sense (code architecture and version control), ASAP.

It's that simple. Most game developers do what it takes to get a finished game out the door, instead of committing themselves to tasks which may never see any real-world use, such as abstraction of unproven engine code. For triple-A or otherwise fairly extensive episodic games this will be the case, since changes in technology or in game design over time (between one episode and the next) will obsolete many of the original ideas and necessitate an engine rewrite *anyway*.

Ultimately, apply the Pareto Principle: If you're really very keen on separation, do that small amount of abstraction work that wins you the majority of the abstraction prize. Don't push too hard on separating engine code out, and where it's in question, just leave it and mark is as "for later".

# Answer
> 2 votes
Data-driven development is key here!

You don't want to copy any code between episodes, that's just plain terrible and will become a maintenance nightmare.

Instead strive to make your code generic and configurable via data obtained from files that are specific to each episode. You can create each episode from the exact same codebase, only resource files (which includes scripts) should change. If a new episode demands a new code feature, it'll simply be ignored in the older episodes.

---
Tags: architecture
---


# Question
Title: How can I render 3D dots at object vertex positions?
What is the best way to put a dot on a vertex?

I have a model (a plane for example) consisting of a few thousand vertices. I want to draw a red dot at every vertex's 3D position, just like 3ds Max's vertex selection mode, for example).

I've tried drawing a small line on each vertex location which works fine with few vertices, but it causes performance problems when I have large objects with many vertices. I've also tried doing this with a shader, but I can't get this to work (I want to highlight the selected vertices). I've thought about drawing a small 3D cube at every vertex location, but this seems terribly inefficient.

How can I accomplish this in a way that will scale to large scenes?

# Answer
> 1 votes
As stated in the comments, this effect can be achieved by rendering the desired vertices as Points. In DirectX, this can be accomplished using this function:

```
public void Device.DrawPrimitives(
    PrimitiveType.PointList,
    int startVertex,
    int primitiveCount
);

```

As a prerequisite, you must have a Device with a bound VertexBuffer. You can see how to setup the Device, create a VertexBuffer, set it as a stream and bind it to the Device in this Drunken Hyena's tutorial.

# Answer
> 2 votes
If you need to draw larger dots, or drawing your geometry as points is undesirable for some other reason, there are multiple ways you could go about it.

Drawing a shape at each vertex position might seem inefficient, though if you use instancing it shouldn't really be that bad - you might even be able to use your vertex buffer as the instance buffer directly by using the right stride and offset values. This would also allow you to draw whatever shape you want.

You could also try to get clever with shaders to get the dots at the same time as you are drawing your object. For example by storing the screen-space positions of all three vertices belonging to a triangle in each vertex of that triangle, you could use them in the pixel shader to determine the current fragment's distance to those vertices, and when appropriate draw a dot instead of the regular shading you'd apply.

In DX10 or 11 this could be done easily with a geometry shader without modifying your actual vertex buffer's layout, without that it gets a little trickier.

While this approach is relatively cheap and lets you draw dots of any size you want, the drawn dots won't extend beyond the silhouette of the object, which becomes more apparent the larger the dot size:

---
Tags: c#, directx, shaders
---


title: No collision detected with 2D rigidbody

text:
# Question
Title: No collision detected with 2D rigidbody
No collision detected with 2D rigidbody 0 I have a ZombieBoy with a circle collider2D and a box collider2D and a RigidBody2D . The player shots energy balls which has a Circle Collider2D and a Rigidbody2D. It is set to trigger. But i have also tried without it set to trigger.

The ZombieBoy has this on its script

```
        void OnTriggerEnter (Collider other)
       {
          Debug.Log ("Im hit! " + other.name);
       }

       void OnCollisionEnter (Collision collision)
       {

          Debug.Log ("Im hit! " + collision.gameObject.name);
       }

```

But i get nothing in the console, and no breakpoints react.

# Answer
> 1 votes
Should use:

```
void OnTriggerEnter2D (Collider2D other)
{
}

```

---
Tags: 2d, unity, physics
---


# Question
Title: XNA 3D Unable to Position Bounding Sphere
I have a collision method that seems like it would work, and it does, but the bounding sphere is always at 0, 0, 0. How do I fix this? Any more code and or details are available upon request.

```
BoundingSphere CreateBoundingSphereForModel(Model model, Matrix worldMatrix)
{
    Matrix[] boneTransforms = new Matrix[this.model.Bones.Count];
    this.model.CopyAbsoluteBoneTransformsTo(boneTransforms);

    BoundingSphere boundingSphere = new BoundingSphere();
    BoundingSphere meshSphere;

    for (int i = 0; i < model.Meshes.Count; i++)
    {
        meshSphere = model.Meshes[i].BoundingSphere.Transform(boneTransforms[i]);
        boundingSphere = BoundingSphere.CreateMerged(boundingSphere, meshSphere);
}
return boundingSphere.Transform(worldMatrix);
}

bool IsCollision2(Model model1, Matrix world1, Model model2, Matrix world2)
{
    BoundingSphere bs1 = CreateBoundingSphereForModel(model1, world1);
    BoundingSphere bs2 = CreateBoundingSphereForModel(model2, world2);

if (bs1.Intersects(bs2))
    return true;

return false;
}

private bool checkPlayerCollision(Model model1, Matrix world1)
{
    //Make player location matrix
    Vector3 playloc = new Vector3(X, Y, Z);
    //Make ship1 matrix
    Matrix ship1WorldMatrix = Matrix.CreateTranslation(ship1loc) * Matrix.CreateScale(0.1f);
//Make ship2 matrix
Matrix ship2WorldMatrix = Matrix.CreateTranslation(ship2loc) * Matrix.CreateScale(0.1f);
//Check for collision with ship1
if (IsCollision2(model1, world1, model, ship1WorldMatrix)) return true;
//Check for collision with ship2
if (IsCollision2(model1, world1, model, ship2WorldMatrix)) return true;
return false;
}

```

# Answer
A bit hard to see what you are doing ( will try an answer anyhow ), but if you are storing a sphere for testing collision or intersecting bounds , your bounding sphere should be initialized from the model bounding box, and store it. However keep it to object's local positioning ( usually Vector3.Zero ).

I think you may be over-complicating your collision by using translation matrices to setup world positions of bounding spheres when your ship location vectors are already in world space - when you can just use the vector3 values directly? ( also makes the code easier to read )...

I suggest not applying a world position to the bounding sphere until you do the actual hit testing, thus keeping a local space sphere for each mesh.

It sounds like ( in your comment response to Peter ) that you want to also scale it?

Assuming this , ensure you always scale the bounding-sphere independently of the positioning of the player/object's position.

1: \- Create Bounding Sphere from loaded model in local space ( of the mesh itself ) - usually Vector3.Zero ( because most models are usually centered on it's center point ), or relative to the center of the overall mesh in local space ( averaged position of all mesh vertices )

2: \- Scale the bounding sphere as needed . If all models of the same source are scaled to the same value, then you can keep one bounding sphere for all instances of the same model. If you scaled the mesh vertices in local space using matrix( scale\* bonetransform ) directly, then generate the bounding sphere from the mesh itself only after scaling the mesh, but might be easier to creat the bounding box from the mesh first, then initialize a bounding sphere from that bounding box, as the bounding box will fit to the mesh itself.

3: \- Apply object/player position to the bounding sphere only when testing collision or intersections ( not when the mesh is loaded or generated ). Use a local space copy to create a world space equivalent of the same bounding sphere ( and they can be cached ).

For example:

```
//
// the bounding sphere passed to the method, and is relative to the mesh's local space ( usually vector3.Zero, or averaged to mesh center )
//
// ObjectPosition represent the position of the player or game object
//

//
// the iCamera object contains a view frustum to test intersection against if we are testing against the camera's view frustum. This does not apply when hit testing two bounding spheres though.
//
public static bool g_IsInViewOfCamera(Vector3 ObjectPosition, BoundingSphere Sphere, iCamera Camera)
{

    //
    // This is the World Space bounding sphere used to test collisions or intersections:
    //
    BoundingSphere S = new BoundingSphere(ObjectPositionInfo.Position + Sphere.Center, Sphere.Radius);

    // logic here... such as hit testing or frustum checks

    // If you are testing View Frustum only:
    return Camera.ViewFrustum.Contains(S) == ContainmentType.Contains ? Camera.ViewFrustum.Contains(S) == ContainmentType.Intersects : false;

}

```

And if you want to test only collisions between two bounding spheres (if they are both from the same model):

```
/// <summary>
/// Tests colition between two player positions, if both objects use the same bounding sphere
/// </summary>
/// <param name="ObjectPosition1">World Space position of a player or object</param>
/// <param name="ObjectPosition2">World Space position of the other player or object</param>
/// <param name="BoundingSphere">Local Space bounding sphere realitive to zero, generated from the mesh.</param>
/// <returns>True if they collide or intersect</returns>
/// <remarks></remarks>
public bool g_IsCollision(Vector3 ObjectPosition1, Vector3 ObjectPosition2, BoundingSphere BoundingSphere)
{
    //
    // World Space bounding sphere of player1 / object1
    //
    BoundingSphere S1 = new BoundingSphere(ObjectPosition1 + BoundingSphere.Center, BoundingSphere.Radius);

    //
    // World Space bounding sphere of player2 / object2
    //
    BoundingSphere S2 = new BoundingSphere(ObjectPosition2 + BoundingSphere.Center, BoundingSphere.Radius);

    if (S1.Contains(S2) == ContainmentType.Intersects)
        return true;
    if (S1.Contains(S2) == ContainmentType.Contains)
        return true;

    return false;
}

```

Or if you want to test using two local space spheres generated from two different meshes:

```
//
// Sphere 1 and 2 are local space bounding spheres
// object positions are in world space
//
public bool g_IsCollision(Vector3 ObjectPosition1, Vector3 ObjectPosition2, BoundingSphere Sphere1, BoundingSphere Sphere2)
{
    //
    // World Space bounding sphere of player1 / object1
    //
    BoundingSphere S1 = new BoundingSphere(ObjectPosition1 + Sphere1.Center, Sphere1.Radius);

    //
    // World Space bounding sphere of player2 / object2
    //
    BoundingSphere S2 = new BoundingSphere(ObjectPosition2 + Sphere2.Center, Sphere2.Radius);

    if (S1.Contains(S2) == ContainmentType.Intersects)
    return true;
    if (S1.Contains(S2) == ContainmentType.Contains)
    return true;

    return false;
}

```

Just my input though. I don't see any need to create world matrices to test sphere intersections when the when the vector used to create the world translation matrix is *already* in world space. Seems like a bit of unnecessary processing to me...

...Probably just my own opinion though...

If you want scale, then you could simply add a scale argument to the collision test routines of my above examples

```
public bool g_IsCollision(Vector3 ObjectPosition1, Vector3 ObjectPosition2, BoundingSphere Sphere1, BoundingSphere Sphere2, float Scale)

```

and then ...

```
BoundingSphere S1 = new BoundingSphere(ObjectPosition1 + BoundingSphere.Center, BoundingSphere.Radius * Scale);

```

Note: \- above examples intend that the bounding spheres are ONLY in local space relative to mesh before being passed as arguments, and *can have bone transformations applied* ( as bone transformations are generally relative to local space? ) , world transformation should not be applied to bounding spheres before passing to the above examples.

* Another note in your code, the following looks to me like you are scaling the entire world matrix, and not the scale of the mesh itself... ( so if scale changes, the positions of ALL objects using this algorithm would scale closer or farther away from World Center instead of Mesh Centers ) - is this intended?

Matrix ship1WorldMatrix = Matrix.CreateTranslation(ship1loc) * Matrix.CreateScale(0.1f);

# Update

Example Usage of the above methods, without bone transforms:

```
vector3 ShipLocation1 = new vector3( /* whatever value here */);
vector3 ShipLocation2 = new vector3( /* whatever value here */);

/*
    Lets assume both players have the same ship:
*/
Model ShipModel = Content.Load<Model>("Models\MyShipModel"); /* etc... */

/*

*/
BoundingSphere LocalSphere = ShipModel.Meshes[0].BoundingSphere;

/*
    if you want to scale the sphere independently of model.
*/
// BoundingSphere.Radius = BoundingSphere.Radius * 0.1f;

/*
   Will be true if colliding ( unscaled )
*/
bool IsColliding = g_IsCollision(ShipLocation1, ShipLocation2 , LocalSphere );

```

You can apply the bonetransform ( or should ) from the Mesh's ParentBone - but do not multiply a world matrix against it.

The only time you really need to apply world transformation matrices is when you draw the mesh itself.
> 0 votes

---
Tags: xna, 3d, collision-detection, bounding-spheres
---


# Question
Title: How does the Simple Stupid Funnel Algorithm work?
Working with the funneling algorithm shown on Digesting Duck I'm not sure how the detection of the funnel works.

Can someone explain the method clearly to me or suggest an alternative way of detecting the funnel and if the funnels sides overlap?

# Answer
The algorithm start with a path you found earlier, in this case a list of triangles:

The code at the bottom of Mikko's blog post constructs the portals array, which is a list of line segments representing the line segments between the path's polygons. These are the "portals" the smoothed path has to go through (or the polygon edges from "let's trace the polygon edge midpoints"). Note that the portals list starts and ends with degenerate line segments at the start and goal points.

This portals list is shown as the yellow dotted line segments in his pictures.

The algorithm starts with a wide funnel and proceeds by iteratively moving the funnel sides forward along the portal side points (the end points of the line segments) as long as this tightens the funnel (A-D).

This means each move forward should move the funnel edges inward, this can be checked with the cross product of the vectors representing the old side and the potential new side (**P** × **Q** in the image below; also see `triarea2` in Mikko's code). If a move forward for a side would not tighten the funnel, we don't update that side for the current iteration of the portals (E).

The other case that needs to be handled is when the funnel degenerates to a line segment. To account for this the algorithm checks if one of the sides is on the "wrong" side by using the cross product again, this time of the vectors made by the funnel apex and the right and left side end points respectively (**R** × **S** in the image below).

If this is the case, the vector from the funnel apex and the correct side end point is added to the smoothed path (**R** in the image above) and the algorithm is restarted with its end point as the new apex (F-G), unless, of course, if it is the goal point.
> 22 votes

---
Tags: c++, algorithm, path-finding
---


# Question
Title: Should widgets be part of a scene in a 2D game?
I'm in the middle of separating logic and drawing of a 2D game, i.e. I'm moving from scenes/entities that draw themselves to scenes/entities that merely store and update data, getting drawn by a renderer.

This works pretty well for scenes and entities, but I can't figure out how the UI fits in. Right now, I draw widgets in the draw routines of some scenes. Scenes can currently also handle input, so it's relatively close to how UI toolkits do things. There are even scenes with nothing but UI, e.g. the main menu. But with the new approach where scenes don't draw themselves anymore, I need a new approach.

How could I do this? Are widgets even supposed to live in scenes, alongside entities? Or should they be in their own kind of scene, e.g. windows or dialogs?

# Answer
> 1 votes
It varies.

Many games have completely separate UI systems that don't use game objects at all.

Using game objects and components for widgets does make some sense, though you should still definitely have a separate hierarchy of UI elements outside of the game scene itself that walks the element tree and renders appropriately.

Note that aside from input, UI is just 2D rendering. It's quite feasible to allow any 3D object to have a 2D widget object hierarchy attached to it which renders into a buffer and then which is displayed on the 3D object as a texture. This can be used for in-game computer terminals, floating partially-3D HUDs (like in Dead Space), or so on. You can also then have special "fullscreen roots" to a 2D hierarchy to use for an overlay HUD or main menu.

The neat thing about integrating your UI widgets into your in-game objects is that you can use other components in your UI. For instance, you could attach a 2D physics components, or allow drag-and-drop of 3D objects onto 2D receptacles, or let your engine be trivially used for both pure 2D games and 3D games.

The rendering of the 2D nodes should - just like regular game object rendering - be handle by a separate render graph in either case, though. Especially for UI. UI is often made of a great many little tiny sprites and the like; having each object in that hierarchy draw itself is terrible for performance.

# Answer
> 1 votes
For MOTES I had to completely develop a *separate* set of components for the user interface.

The thought crossed my mind that I could just use an orthogonal camera and ray-poly intersections to handle widgets, (because MOTES already features ray picking in the game), but I decided against that because point-in-rectangle is much more efficient than point-in-poly.

The underlying rendering subsystem is the same, but I branched my hierarchy roughly like so:

```
                   +----------------+
                   |   GameObject   |
                   | pos,vel,common props (verts, etc)|
                   +----------------+
                           ^     ^
                           |     |
                +-----------+   +------+
                + Touchable +   + Ship +
                + rect      +   +      +
                +-----------+   +------+

```

So there was some overlap in that each object has a position and a way to store its vertices and get rendered, so that part was shared.

So for that game, ships didn't need to be *touchable*, instead I placed an *invisible* touchable widget over the main window, and *that* intercepts touches and cast rays into the scene to pick things.

---
Tags: 2d, architecture, entity-system, gui
---


# Question
Title: How to get surrounding tiles in a tile array
I've created a tiled map that holds two layers, one for the tile type, and the other for whether it is solid or not. I plan on creating very big maps, and checking every tile seems like it would slow down my game immensely.

So lets say I had an array of integers. "0" representing solid, and "1" representing not solid. How would I check only the 8 surrounding integers instead of the whole array each update.

`0 0 0`

`0 1 0`

`0 0 0`

# Answer
> 6 votes
Checking the surrounding tiles is pretty simple. You can do it pretty easily in a nested for loop:

```
for(int i = x-1; i <= x+1; i++) {
    for(int j = y-1; j <= y+1; j++) {
        if(i != x || j != y) { //ignore the center tile
            //process tile (i,j)
        }
    }
}

```

This will loop through each tile surrounding tile (x, y). You'll want to add some bounds checking as well for when you're looking at a tile on the edge of your map.

# Answer
> 4 votes
Another option is to hardcode the list of the surrounding tiles offsets. E.g.:

```
// Somewhere at init:
Object[][] xyoffsets = {{-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1}};

// ...

// Later:
for(Object[] xyoffset : xyoffsets) {
    int i = x + xyoffset[0];
    int j = y + xyoffset[1];
    // process tile (i,j)
}

```

This avoids an unnecessary if and allows to easily change the order in which tiles are processed, but also adds the cost of an extra table.

---
Tags: java, collision-detection, tiles, tilemap
---


# Question
Title: "Fading" effect between different screens?
I'm not sure what the correct word for it is, but I'm thinking like the fading effects when you move between different screens in Powerpoint or Keynote; that the screen fades black before the new screen is shown instead of instantly change.

The "screens" I'm talking about are actually two pictures, and since it's for an adventure type game I thought it'd be cool if it could be done.

Does anyone know a good way to implement this?

# Answer
> 1 votes
The XNA Game State Management example project provides this exact function. It also handles loading screens, directing and halting input to the topmost screen, and some simple nested menu screens. You should probably check it out.

And to answer your question directly, it achieves the fading effect by drawing a full-screen black quad with a shifting alpha value. You could easily customize it by drawing your two pictures instead.

---
Tags: xna, c#, image, image-effects
---


title: FBO blit depth buffer to screen?

text:
# Question
Title: FBO blit depth buffer to screen?
I have an FBO in a deferred 4.3 OpenGL renderer, in which I setup the depth buffer of that FBO like this:

```
GLCALL(glGenRenderbuffers(1, &mDepthbuffer));
GLCALL(glBindRenderbuffer(GL_RENDERBUFFER, mDepthbuffer));
GLCALL(glRenderbufferStorageMultisample(GL_RENDERBUFFER, 0, GL_DEPTH32F_STENCIL8, windowWidth, windowHeight));
GLCALL(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, mDepthbuffer));
GLCALL(glBindRenderbuffer(GL_RENDERBUFFER, 0));

```

Normally when I debug I can output the color attachments to screen easily, like this for normals:

```
GLCALL(glReadBuffer(GBuffer::GBUFFER_COLOR_ATTACHMENT_NORMAL));
GLCALL(glBlitFramebuffer(0, 0, mWindowWidth, mWindowHeight, 0, 0, mWindowWidth, mWindowHeight, GL_COLOR_BUFFER_BIT, GL_LINEAR));

```

But how can I do the same for the depth buffer contents, as it is not a color buffer?

# Answer
> 4 votes
First of all if you tried to do exactly that it would not work because blitting the depth / stencil buffer using `GL_LINEAR` is undefined. It literally lists this very situation as the first possible error on the manual page for `glBlitFramebuffer (...)`:

> **Name**
>
> > **`glBlitFramebuffer`** — copy a block of pixels from the read framebuffer to the draw framebuffer
>
> ...
>
> **Errors**
>
> > `GL_INVALID_OPERATION` is generated if ***mask*** contains any of the `GL_DEPTH_BUFFER_BIT` or `GL_STENCIL_BUFFER_BIT` and ***filter*** is not `GL_NEAREST`.

---

More importantly, however, it is generally quicker to draw a textured quad than to do a blit from a read buffer to a draw buffer. It seems almost counter-intuitive; after all, the **only** reason `glBlitFramebuffer (...)` was created was to copy data from one framebuffer to another. But if you want the best performance just stick to textured quads.

The textured quad approach will also allow you to do linear interpolation of the depth buffer, which is a limitation you cannot work around if you do a blit.

The only real reason you would ever consider using `glBlitFramebuffer (...)` is if you want to do MSAA resolve of a multi-sampled renderbuffer. This is the least painful way of accomplishing that particular task, particularly if you are dealing with Shader Model 4.0 (DX10) hardware, which only supports multi-sampled color textures. You can implement MSAA resolve in shaders using `texelFetch (...)` but unless you have Shader Model 4.1 (DX10.1) hardware you cannot use multi-sampled depth textures.

---
Tags: opengl
---


# Question
Title: How can I easily model semi-realistically human movement and collision in a 2D game?
I am writing a sports simulation game in which the simulated players will interact physically with each other (i.e. tackle, push, bump...) as well as do individual actions such as changing direction of motion quickly in response to a changing game state.

At the moment all movement occurs with no inertia and infinite acceleration (so each step of the game loop the player can move at their top speed in whatever direction they want, regardless of their current motion). This has been sufficient to develop the main parts of the player AI, but it's time to get a little more realistic. The game has a cartoony look and feel so it doesn't need to be perfectly realistic, but player movement and interaction should give a semblance of reality.

So, how could human movement be summarized in a few key restrictions? I've toyed around with setting maximum acceleration and turning rates, as well as a momentum/inertia model for dealing with player collisions, but the game ends up looking like it's played by a bunch of bumper cars, rather than people (i.e. these restrictions and collision model describe cars on a slippery surface, not bipeds).

# Answer
Probably the best way to handle this *easily* is to use a pre-existing physics engine that has the capability to provide inelastic collisions. Move your players under a physically-correct (or at least nearly-so) model and you'll have the physically-correct appearance (or at least something that is close enough).

You will have a bit of a challenge making the game feel responsive under more strict inertia and acceleration rules, though, and so you'll probably have to sacrifice some of that to tweak the playability of your game.

There was an excellent article by Steve Rabin in the 2nd Game Programming Gems book that dealt with the third-person motion and camera control of Super Mario 64, which had a good balance between a sense of physicality and weight to Mario's movement and responsive gameplay. I'd recommend reading it if you can get ahold of a copy.

You will probably want to search related materials without bias to 2D gameplay, since 3D ones will be more common and should be easily adaptable.
> 1 votes

---
Tags: movement, collision-resolution
---


# Question
Title: How can I fix this transparency problem when my data is viewed from a certain angle?
```
using Microsoft.DirectX.Direct3D;
using Microsoft.DirectX;

```

I render a 3D data by setting `device.RenderState.AlphaBlendEnable = true`

Now my top view looks like below, the outer surface layer covered the underneath layers and resulting only outer layer is displayed at top view.

I would like to view the underneath layer from top view. How do I do this? Is there any setting can be done using `Microsoft.DirectX` ?

**Update: Question is solved by myself**

```
device.RenderState.ZBufferWriteEnable = false;

```

# Answer
> 1 votes
You're only seeing the top layer of your data from the overhead view because your depth buffer is enabled. One way to fix this and possibly achieve the result you want is to disable writes to the depth buffer when rendering that volume data:

```
device.RenderState.ZBufferWriteEnable = false;

```

Do note that this could mean some objects that should be behind others show up "in front," especially if you are not then depth-sorting your transparent rendering. You may want to look into other ways to handle order-independent transparent rendering, such as depth peeling.

---
Tags: 3d, directx, transparency
---


# Question
Title: Converting 3 axis vectors to a rotation matrix
I am trying to get a rotation matrix (in 3dsmax) from 3 vectors that form an axis (all 3 vectors are aligned by 90 degrees each other)

Somewhere I read that I could build a rotation matrix just by inserting in every row one vector at a time (source: http://renderdan.blogspot.cz/2006/05/rotation-matrix-from-axis-vectors.html)

So, I built a matrix with these example vectors

x-axis : \[-0.194624,-0.23715,-0.951778\]

y-axis : \[-0.773012,0.634392,0\]

z-axis : \[-0.6038,-0.735735,0.306788\]

But for some reason, if I try to convert this matrix to eulerangles, I receive this rotation: (eulerAngles 47.7284 6.12831 36.8263) ... which is totally wrong, and doesn't align to my 3 vectors at all.

I know that rotation is quite difficult to understand, may someone shed some light? :)

# Answer
A rotation matrix can be built by using the axis of the coordinate system you're rotating into. As others stated in the comments you have to make sure you don´t mix row- and column-major matrices and dont mix any coordinate spaces. Since the math you used is correct, as you said, the problem must be somewhere else in your code.
> 1 votes

---
Tags: rotation, matrix, vector
---


# Question
Title: Why does my blur shader implementation produce this strange result?
I tried to implement the blur shader shown here.

Instead of having a simple 2D texture I use Unity's `GrabPass` function to capture what's behind the plane to have a transparent effect. Then I apply this on a 3D plane:

```
struct v2f {
    float4 pos : SV_POSITION;
    float4 screenPos : TEXCOORD3;
    float3 uv;
};

v2f vert(appdata_full v)
{
    v2f o;
    o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
    o.screenPos = ComputeScreenPos(o.pos);
    o.uv = UNITY_PROJ_COORD(o.screenPos);
    return o;
}

// In the frag part there is the shader blur computation but based on XYZ, with Z = 0

```

Then I apply the blur and this leads to this when I zoom in:

Is there a way to avoid this effect?

# Answer
> 3 votes
I concur with Nathan Reed's assessment that the issue is probably caused by spacing your blur kernel too widely.

Use additional rendering passes, downsample the image, decrease your blur radius, or some combination thereof.

---
Tags: opengl, unity, directx, shaders, hlsl
---


# Question
Title: Does the feature level affect multisampling?
I'm using DirectX 11 with the feature level 9\_3 even though my computer could run 11\_0, but I want to support older hardware as well.

I'm using `CheckMultisampleQualityLevels` to check whether multi sampling with the given samplecount is supported or not. However it returns 1 for quality with 4samples. And with 8samples it returns 0 (so its not supported). With feature level 11\_0 `CheckMultisampleQualityLevels` returns 1 for 8samples. I'm using a ***AMD/ATI Radeon HD5830***. In the most DirectX9 games I can still use 8x antialiasing. So why is it not supported in DX11 with a lower feature level.

Another point is it seems like 4samples doesnt really affect the output:

With mutlisampling disabled the result is the same. I'm sure that I configurated ms correctly.. even in the Depthbuffer.

Whether I enable `AntialiasedLineEnable` in the `RasterizerDesc` or not the output is still the same.

I searched in MSDN but I couldn't find any more information about multisampling.

EDIT: The blacklines in the picture are outlines made in the pixelshader

# Answer
A breakdown of capabilities by feature level is available here. You'll note there is no explicit mention of MSAA support. However, the documentation does point out that for the 9.3 feature level, no guarantee is made for MSAA support.
> 1 votes

---
Tags: directx, directx11, antialiasing
---


# Question
Title: Why would Assets.getBytes returns null in a test environment?
I'm using the latest Haxe (2.10), NME (3.4.3), and MUnit.

I've written some unit tests that need to fetch bitmap data from SWF symbols. The first step is to actually load the SWF data. To do this, I use NME's `getByteArray` along with the `swf` library, like so:

`var blah:SWF = new SWF(Assets.getBytes("assets/swf/test.swf"));`

The call to `Assets.getBytes` returns null when I'm running this under MUnit. When running my actual game code, I'm able to get the byte array (and consequentially, instantiate the SWF class).

Am I doing something wrong? What am I missing?

**Edit:** My directory structure is:

```
. (root
.\assets
.\assets\*.png (other images)
.\assets\swf\*.swf (SWFs)
.\Source\*.hx (source code)
.\Test\*.hx (tests)

```

# Answer
This looks like an issue with the working directory; likely when running under MUnit, your working directory isn't the same as when running your primarily applicable and thus the paths do not correctly resolve (it's also possible for some reason that file IO methods are disallowed under test, but that seems egregious).

Consider using embedding the resources in your test assemblies, or determining how to alter the working directory for MUnit's test execution.
> 1 votes

---
Tags: haxe
---


# Question
Title: Why are my animated objects (from Blender) always playing at the global origin in Unity?
I created and animated a sledgehammer in Blender 2.67b using an armature. The sledgehammer has one animation (created using the Action Editor) called "Idle". I parented the imported sledgehammer to an empty GameObject and set the sledgehammer's position to (0, 0, 0). I then moved the parent GameObject to where I want it in the scene. When I launch the game, the animation plays but the sledgehammer child always re-positions itself to be at the global origin, no matter where I place the parent GameObject. See the image below:

Notice how the sledgehammer's position goes from (0, 0, 0) to (-1087, -3, -1149).

The armature has a single bone and has the sledgehammer object as a child. I've spent about 4 hours looking this up on the Internet, but it seems like parenting the animated mesh to an empty GameObject worked for everyone else except me. Anyone else experience this? I've tried both .fbx and .blend files.

# Answer
You can solve this programatically for now. A small script will update the position before the draw call to keep the sledgehammer in the position of your Parented game object. Drag the GameObject parent onto the inspector after applying this script:

## UnityScript:

```
#pragma strict

var localOrigin : GameObject;

function Start () {
    transform.position = localOrigin.transform.position;
}

function LateUpdate () {
    transform.position = localOrigin.transform.position;
}

```

## C#

```
public GameObject localOrigin;

void Start () {
    transform.position = localOrigin.transform.position;
}

void LateUpdate () {
    transform.position = localOrigin.transform.position;
}

```

Hope it helps.
> 1 votes

---
Tags: unity, animation, blender, 3d-meshes, import
---


# Question
Title: Opengl binding shaders vs binding buffers performance
Quick question for an opengl guru, I'm in the process of building a render queue and can either reduce the number of shader binding or the number of vertex buffer binding. I just want to know which one is more expensive on newer graphics cards (IE)(opengl \>= 3.2)?

# Answer
> 2 votes
How exactly your system performs state changes is not part of the OpenGL specification, so perfomrances may vary betwen diffrent vendors and implementations. The only real way to answer your question is simply by testing it. Write a simple test program (or use the the thing you´re currently working on if possible), which performs alot of buffer bindings to reduce shader bindings and then the opposite. Use a high precision clock to measure the time of both test cases and compare.

---
Tags: opengl, graphics, shaders, performance, graphics-programming
---


# Question
Title: How do I create a manual object with colors for each vertex?
How do I create a shaded manual object with colours for each vertex? Eg if `ogreObj` is the `Ogre::ManualObject` :

```
ogreObj->begin("BaseWhiteNoLighting", Ogre::RenderOperation::OT_TRIANGLE_LIST);

```

will allow me to select each vertex's colour with `ogreObj->colour(r, g, b)` after each `ogreObj->position(x, y, z)` and `ogreObj->normal(x, y, z)` call.

However, if I change the material to `BaseWhite`, `color()` instructions are ignored. I read that you must disable lighting int the `.material` script, but I need it active... Any advice?

**ANSWER:** This Ogre forum's thread has a simple `.material` script that works for this purpose:

```
material Voxel/Default
{
   technique
   {
      pass
      {
         diffuse vertexcolour
         specular vertexcolour
         ambient vertexcolour
         lighting on

      }
   }
}

```

# Answer
As you discovered, a material script can be used for this purpose.

```
material Voxel/Default
{
   technique
   {
      pass
      {
         diffuse vertexcolour
         specular vertexcolour
         ambient vertexcolour
         lighting on

      }
   }
}

```
> 1 votes

---
Tags: shaders, 3d-meshes, ogre, vertex, materials
---


# Question
Title: How do I make the camera focus on a moving game object with ITween?
I'm trying to write a solar system with Unity3D. Planets are sphere game objects rotating around another sphere game object representing the star.

What i want to achieve is let the user click on a planet and then zoom the camera on this planet and then make the camera follow and keep it centered on the screen while it keep moving around the star.

I decided to use iTween library and so far i was able to create the zoom effect using `iTween.MoveUpdate`. My problem is that the focused planet does not say properly centered as it moves.

Here is the relevant part of my script:

```
void Update () {
    if (Input.GetButtonDown("Fire1"))
    {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, Mathf.Infinity, concernedLayers))
            {
                    selectedPlanet = hit.collider.gameObject;
            }
    }
}

void LateUpdate() {
    if (selectedPlanet != null)
    {
            Vector3 pos = selectedPlanet.transform.position;
            pos.z = selectedPlanet.transform.position.z - selectedPlanet.transform.localScale.z;
            pos.y = selectedPlanet.transform.position.y;

            iTween.MoveUpdate(Camera.main.gameObject, pos, 2);
    }
}

```

What do i need to add to this script to make the selected planet stay centered on the screen?

I hosted my current project as a webplayer application so you see what's going wrong. You can access it here.

# Answer
What you may be missing is the center point of the planets. The position may be a handle at the right of the planet (and so it is pushed off to the left.)

Use the mesh itself to find the center point. As you have very low poly meshes on that example this shouldn't be any strain at all:

```
using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {

    void Update () {
        if (Input.GetButtonDown("Fire1"))
        {
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                RaycastHit hit;

                if (Physics.Raycast(ray, out hit, Mathf.Infinity, concernedLayers))
                {
                    selectedPlanet = hit.collider.gameObject;
                }
        }
    }

    void LateUpdate() {
        if (selectedPlanet != null)
        {
            Vector3 pos = GetCenterPoint(selectedPlanet);
            pos.z = selectedPlanet.transform.position.z - selectedPlanet.transform.localScale.z;
            pos.y = selectedPlanet.transform.position.y;

            iTween.MoveUpdate(Camera.main.gameObject, pos, 2);
        }
    }

    Vector3 GetCenterPoint(GameObject gameObj) {
        Mesh mesh = gameObj.GetComponent<MeshFilter>().mesh;
        Vector3[] vertices = mesh.vertices;
        float
            xMax = float.NegativeInfinity,
            yMax = float.NegativeInfinity,
            zMax = float.NegativeInfinity;
        float
            xMin = float.PositiveInfinity,
            yMin = float.PositiveInfinity,
            zMin = float.PositiveInfinity;
        //Time to loop through and find the min and max x,y,z
        int i = 0;
        while (i < vertices.Length) {
            xMin = Mathf.Min(xMin, vertices[i].position.x);
            yMin = Mathf.Min(yMin, vertices[i].position.y);
            zMin = Mathf.Min(zMin, vertices[i].position.z);

            xMax = Mathf.Max(xMax, vertices[i].position.x);
            yMax = Mathf.Max(yMax, vertices[i].position.y);
            zMax = Mathf.Max(zMax, vertices[i].position.z);
        }
        //avg out the points to get the center
        Vector3 centerPoint =
            new Vector3((xMin+xMax)/2,(yMin+yMax)/2,(zMin+zMax)/2);
        return centerPoint;
    }
}

```

**Edit:**

I have also noticed that you have not taken into account the X position of the planet, only the Y and z. This would make the planet offset if the camera was at a certain rotation to the planet but not adjusted for the x AND z then you would have it not centered on screen:

Notice the top one, ideal situation with your current setup. Bottom left is what can happen if your camera is rotated on it's Y axis slightly but you are tracking directly on x,y,z. Using the above should solve this issue but I believe this is the origin of the offset camera.
> 2 votes

---
Tags: unity
---


# Question
Title: When to read/write to database with a game server
My question is fairly simple but maybe hard to answer. I'm currently building my own game server and I've done to login server now. So, on to the actual game server. I have a question for this server though. Say, a thousand players are moving around on this server, how do I manage this with the database (MySQL) that should hold the player positions and such?

I understand I can't query the database every time something small changes or a single player moves because that would be a huge load for that server. How is this done in real game servers? When do they read or write to the database?

# Answer
> 5 votes
Database access is always an expensive operation. For that reason it should be minimized as much as possible.

In an ideal case, you would read and write the player data once per session: When the client connects you read it, and when the client disconnects, you write the changed data back. In the meantime it should be kept in the memory of the gameserver.

But in practice you can never be sure that your gameserver never crashes, so you should do regular backup saves to the database so players don't lose too much progress when your network admin stumbles over the servers power cord. Once every few minutes is usually enough.

---
Tags: server, databases, mysql
---


# Question
Title: How to store and parse story actions in XML
I been working on a game in Unity that reads its story (Actions, scene descriptions, NPC's, ect...) from an XML and have been wondering there was a better way to store actions based on player data such as item in an inventory or attribute.

An example would be the player having a light source greater then 5 on hand while entering a dark room.

```
<scene>
 <description>You enter a dark room </description>
 <sceneReq>
  <text>and do not have enough light to see it well.</text>
  <action trigger="player.lightLevel > 4"  sceneIndex="5"/>
 </sceneReq>
</scene>

```

How would I be able to act on the above logic in C# without hard coding the actions and load dynamically from the XML? Also how should I handle logic in XML if it requires multiple actions or parameters?

For example having a crowbar and the strength greater then 15 to open a door.

```
<scene>
 <description>You see a stuck door in front of you.</description>
 <sceneReq>
  <text>Your effort to remove the door has failed.</text>
  <and>
   <action trigger="player.item == 1"  sceneIndex="10"/>
   <action trigger="player.strLevel > 15"  sceneIndex="10"/>
  </and>
 </sceneReq>
</scene>

```

Because I am rather new to parsing XML I can't think of a way to break the logic out of the XML and use it in code dynamically. I looked over https://stackoverflow.com/questions/372915/game-logic-in-xml-files and really did not seem to answer my question on how to solve it in C#.

**Edit:** Spent more time on this and with Blue's answer I was able to come up with a viable solution.

Sample XML

```
 <scene>
  <description>You enter a dark room </description>
  <condition type="itemEquip" itemType="Flashlight">
   <message>and do you do not have a light source.</message>
  </condition>
  <button text="Use flashlight" sceneIndex="2">
   <condition type="itemHave" itemType="Flashlight">
    <message> and you forgot your flashlight at home.</message>
   </condition>
  </button>
  <button text="Go back" sceneIndex="0"/>
 </scene>

```

Made it so that you can have a condition for a button and for the scene as separate checks, that way buttons can be also dynamic based on the condition class.

The condition class:

```
public enum ConditionType
{
    itemLevelReq,
    itemEquip,
    itemHas,
    playerLevel,
    playerAttribute,
    baseDefault
}

abstract class Condition
{
    public ConditionType type;
    public string failMessage = "Condition not met";

    public abstract bool IsThisConditionMet();
}

class BaseCondition : Condition
{
    ConditionType type = ConditionType.baseDefault;
    string failMessage = "Condition not met";

    override public bool IsThisConditionMet()
    {
        return false;
    }
}

//example concrete condition
class ItemHasCondition : Condition
{
    ConditionType type = ConditionType.itemHas;
    string itemType;
    int levelReq;

    public ItemHasCondition(String item, string fail)
    {
        this.itemType = item;
        this.failMessage = fail;
    }

    override public bool IsThisConditionMet()
    {
        if(Program.testPlayer.items.Contains(this.itemType)){
            return true;
        } else {
            return false;
        }
    }
}

```

Then here is the parser for the XML(Simplified)

```
private static void readThisXML()
{
    XDocument doc = XDocument.Load("Scenes.xml");

    foreach (XElement root in doc.Root.Elements("scene"))
    {
        SceneStruct scene = new SceneStruct();
        List<ButtonStruct> buttons = new List<ButtonStruct>();
        List<Condition> conditions = new List<Condition>();

        foreach (XElement element in root.Elements("button"))
        {
            ButtonStruct btn = new ButtonStruct();
            List<int> btnIndex = new List<int>();
            List<Condition> btnConditions = new List<Condition>();
            btn.text = (string)element.Attribute("text");
            //Maybe different indexes based on conditions?
            btnIndex.Add((int)element.Attribute("sceneIndex"));
            btn.btnIndex = btnIndex;

            foreach (XElement elementC in element.Elements("condition"))
            {
                if (elementC.Attribute("type").Value.Equals("itemEquip"))
                {
                    Condition con = new ItemHasCondition((string)elementC.Attribute("itemType"), (string)elementC.Element("message").Value);
                    btnConditions.Add(con);
                }
            }
            btn.conditions = btnConditions;

            buttons.Add(btn);
        }

        dwStruct.buttons = buttons;

        foreach (XElement element in root.Elements("description"))
        {
            scene.description = (string)element.Value;
        }

        foreach (XElement element in root.Elements("condition"))
        {
            if (element.Attribute("type").Value.Equals("itemEquip"))
            {
                Condition con = new ItemHasCondition((string)element.Attribute("itemType"), (string)element.Element("message").Value);
                conditions.Add(con);
            }
        }

        scene.conditions = conditions;

        sceneList.Add(scene);
    }
}

```

Hopefully this helps anyone who happens to stumble over this problem like I did. You might not need the enum but it could be handy for later.

# Answer
> 3 votes
I would look heavily into state machines and deserializing the XML data into state instances.

You can create class definition for a condition, be that an integer on an item for it's `int brightness = 4;` value or a `string name = "torch";` in the inventory.

Something along these lines:

```
public enum ConditionType{
    default,
    itemLevelReq,
    itemEquip,
    playerLevel,
    playerAttribute
}

abstract class Condition{

    abstract ConditionType type;
    string failMessage = "Condition not met";

    public abstract bool IsThisConditionMet();

}

//example concrete condition
class ItemLevelCondition : Condition{

    Condition type = itemLevelReq;
    string itemType;
    int levelReq;

    public ItemLevelCondition(String item, int level, string fail){
        this.itemType = item;
        this.levelReq = level;
        this.failMessage = fail;
    }

    public bool IsThisConditionMet(){
        if(player.items.contains(this.itemType)){
            return player.items[itemType].level >= this.levelReq;
        } else {
            return false;
        }
    }

}

class Scene{
     string description;
     Condition[] requirements;

     public Scene(string description,Condition[] requirements)
     {
         this.description = description;
         this.requirements = requirements;
     }

     public bool AreAllConditionsMet(){
         bool result = true;
         string responseMessage;
         foreach(Condition condition in requirements){
             if(!condition.IsThisConditionMet()){
                 responseMessage += condition.failMessage + "\n";
             }
             result &= condition.IsThisConditionMet();
         }

         Scene.OutputFailMessage();
         return result;
     }

     public void OutputFailMessage(){
         Console.Write(this.responseMessage);
     }
}

```

Please excuse the roughness but I hope this gives you a decent idea for structure. Formatting your XML a little better you can then create a parser to create the scenes and the requirements in them, here is an example of both the scenes above in one:

```
<scene index="5">
 <description>You enter a dark room and feel a door stuck in front of you</description>
 <condition type="itemLevelReq" itemType="light" levelReq="5">
  <failMessage>and do not have enough light to see it well.</text>
 </condition>
 <condition type="playerAttribute" attrType="strength" levelReq="15">
  <failMessage>You are not strong enough.</text>
 </condition>
 <condition type="itemEquip" itemType="crowbar" equipped="true">
  <failMessage>You do not have a crowbar equipped.</text>
 </condition>
</scene>

```

Here is a snippet of how to do the XML parsing itself:

```
using System.Collections.Generic;
using System.Xml;
    public static List<Scene> InitialiseScenes()
    {
        List<Scene> scenes = new List<Scene>();

        Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Scenes.xml");

        //This if block verifies the file was loaded into the stream and throws a FileNotFound if it isn't
        if (stream != null)
        {
            StreamReader reader = new StreamReader(stream);

            XmlDocument sceneDoc = new XmlDocument();
            sceneDoc.LoadXml(reader.ReadToEnd());

            string xpathQuery = "/scenes/scene";
            foreach (XmlNode sceneNode in sceneDoc.SelectNodes(xpathQuery))
            {
                //Set up new Champion details
                Scene currentScene;
                List<Condition> conditions = InitialiseConditions(sceneNode.SelectNodes("conditions"));

                currentScene = new Scene(sceneNode.SelectNode("description").InnerText, conditions)

                scenes.Add(currentScene);
            }
        }
        else
        {
            throw new FileNotFoundException("The resource file for the champions data is missing.", "Champions.xml");
        }
        return champions;
    }

    public List<Condition> InitialiseConditions(XmlNodeList nodeList) {

        //Get conditions from nodes
        List<Condition> result;
        foreach (XmlNode conditionNode in nodeList){
            Condition tmpCondition;

            //TODO: Create list of nodes and use switch statement to load the
            // node into a concrete implementation of the abstract Condition class
            //eg. tmpCondition = new ItemLevelCondition(item, level, fail);

            result.Add(tmpCondition);
        }
    }

```

I hope this gets you on the right track.

---
Tags: c#, unity, scripting, level-design, xml
---