# Question
Title: Entity/Component based engine rendering separation from logic
I noticed in Unity3D that each gameObject(entity) have its own renderer component, as far I understand, such component handle rendering logic.

I wonder if it is a common practice in entity/component based engines, when single entity have renderer components and logic components such as position, behavior altogether in one box?

Such approach sound odd to me, in my understanding entity itself belongs to logic part and shouldn't contain any render specific things inside.

With such approach it is impossible to swap renderers, it would require to rewrite all that customized renderers.

**The way I would do it is,** that entity would contain only logic specific components, like AI,transform,scripts plus reference to mesh, or sprite. Then some entity with Camera component would store all references to object that is visible to the camera. And in order to render all that stuff I would have to pass Camera reference to Renderer class and render all sprites,meshes of visible entities.

Is such approach somehow wrong?

# Answer
> Such approach sound odd to me, in my understanding entity itself belongs to logic part and shouldn't contain any render specific things inside.

In some entity systems, components only contain logic. In others, they only contain data. In yet others, they contain both. I'd certainly argue that putting the actual render commands (as in the OpenGL or D3D code) into the rendering component isn't ideal (see my answer here regarding the question "should objects render themselves?", which is the same principle under discussion). However, it is certainly possible to do so and even to do so in a fashion that allows the implementation of the rendering components to be swapped without having to alter the consumers of the component system. Doing so just involves any typical implementation-hiding technique.

It's acceptable, and common, to have a "visual component" that contains a reference to some renderable object that comes from the lower-level rendering subsystem and have that component export behavior or interface to allow the appearance data to be specified by other components (such as ones containing scripts).

> The way I would do it is, that entity would contain only logic specific components, like AI,transform,scripts plus reference to mesh, or sprite. Then some entity with Camera component would store all references to object that is visible to the camera. And in order to render all that stuff I would have to pass Camera reference to Renderer class and render all sprites,meshes of visible entities.
>
> Is such approach somehow wrong?

I don't really see what you gain by having a "camera" component. It seems like a very heavyweight operation inject into the entity system. Does, for example, the presence of the camera component mean that you always get a scene rendered from that camera's perspective? How then do you determine which of those scenes to present to the user, and where? It feels like -- without knowing more about this design -- you'd be shoving a lot of unrelated responsibility into the camera component. I'd prefer to see that responsibility handled by something external to the entity system.

Otherwise, that sounds like a perfectly usable system. It will have it's pros and cons, of course, but those will become apparent in practice and many of them will be specific to your needs and/or the needs of your game.
> 6 votes

# Answer
You are right and wrong at the same time. The entity/component model is very flexible and that is one reason why it is used. What you very well point out is that it muddles the simulation (game logic) and presentation (graphic & sound).

The first thing to note is that a component does not mean that it will actually do something. For example a `MeshRenderComponent` may not actually render the mesh. It can be implemented as containing all relevant data and hand the actual rendering to a "system" of the engine.

This has two advantages. First, the entity can be fully instantiated on the server. All components that don't "work" on the server are just dumb data containers. The second, is that a system with all data resident can run tighter and more efficient loops, then when moving over components.

The quint essence, is that the data of entity/component model is muddled, but you can still keep the different systems properly isolated.

The second thing to note is, the good old question: *"Does it matter?"*

This is a way harder question to answer. From a software engineering standpoint the decision is clear, you have a pure simulation and a pure presentation layer. (Model-View-Controller) But when it comes to artists and level designers, it gets harder. You mention Unit3D and you may see where I am coming from.

A level designer says, I want this splash here over the waterfall. The engineer will implement a water simulation and determine where these effect need to go, the level designer just want to place it there, who cares that it is not perfectly accurate.

As it turns out the way that Unity3D muddles logic and presentation is how most non engineers actually think how things should work. *(And don't try to explain why multi-player is so hard to implement with such a model...)*
> 3 votes

# Answer
It seems that Renderer is just a component (http://docs.unity3d.com/Documentation/ScriptReference/Renderer.html).

As far as I understand Renderer provides common functionality to more specific inherited components:

http://docs.unity3d.com/Documentation/Components/class-MeshRenderer.html http://docs.unity3d.com/Documentation/Components/class-ParticleRenderer.html http://docs.unity3d.com/Documentation/Components/class-LineRenderer.html

As far as I know Unity supports several underlying renderers for its various platforms, Direct3D and OpenGL among them:

Does Unity for PC use Direct3D or OpenGL?

So it must be possible to swap underlying renderers even if it is not available to end user (scripter).

If you have already read general information on component-entity-system architectures, then you know that entities are generally collections of components. A component may generally be anything including physics, animation, game logic etc. Why treat graphics differently?

Some component-entity-system architectures tend to put more logic in components, while some concentrate it all in systems and use components as pure data.

Read this if you had not already:

https://stackoverflow.com/questions/1901251/component-based-game-engine-design/3495647#3495647
> 0 votes

# Answer
All i can say is GUI.Button is the worst kind of code any development team can write. This can lead to slow downs and what not.. Rendering and Logic in the same loop? Why then does Unity need an Update function? If Unity wanted to draw and run logic at the same time then it does not need any Update functions... In a team which is working on big projects handling code in the OnGUI() for logic is a disaster .. I'd rather not use Unity for this reason alone. Also the other reason is the concept of the Loading and Unloading meaning memory management is left on Unity to decide which is not at all ideal for any programmer. A programmer must know where and when memory is being used but Unity hides all of that.

As far as I come to understand Unity lets you create a lot of code and infact the full game in a matter of days if not a few months. But the time when you actually try and sell this game over PSN or XBOX you will repent why you chose Unity because now you have a game that works but you have no control of its memory management or FPS because of Rendering and Logic being written in the same code.

Also having rendering and logic in the same code makes it a mandatory to have lesser and lesser team mates working on the project. If one day you change the programmer your team will suffer.

In my view this Entity Component structure is not suitable for large teams making huge games. Try making an MMORPG on Unity3D ... you'll know what PAIN is! :D
> -3 votes

---
Tags: rendering, logic
---


title: Setting Anchor Point

text:
# Question
Title: Setting Anchor Point
I want to set anchor point for the sprite like cocos2d has done for their implementation. I do not found any thing like that in andengine so please provide guidance on that. I want to move the sprite on touch so I use following code but that does not work for me.

```
super.setPosition(pX - this.getWidthScaled() / 2,
            pY - this.getHeightScaled() / 2);

```

Because I touch on the corner of the image but automatically it comes at center of the image because of above code. I want to remain the touch at desire position and drag it. For me the anchor point became useful. But I don't found anything in andengine.

# Answer
This is pretty basic, you need to remember the distance from the center when you first touch the Sprite and then take this into account when moving it around.
> 2 votes

# Answer
Not sure if this is what you want, because I don't know cocos2d. `Entity` in AndEngine has method:

```
@Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
    return false;
}

```

The `pTouchAreaLocalX` and `pTouchAreaLocalY` will give you relative position of touch inside the entity and `pSceneTouchEvent` then contains the absolute position on screen. You can use the local coordinates to correct the position.
> 0 votes

---
Tags: andengine
---


# Question
Title: Adobe Air turn based multiplayer Game, sockets vs http bandwidth
I am developing an Adobe Air multiplayer game for iPad.
It is turn based and not realtime. It is like checkers game.
I want to use a client server model.
I have found 2 options to connect to server so far: **socket connection** and **http requests**
My question is:
Is the bandwidth requirement for **socket connection** vs **http requests** different?
I need the game to work with **very** low speed internet connections

# Answer
**Adobe Air Socket**

> The Socket class enables code to establish Transport Control Protocol (TCP) socket connections for sending and receiving binary data.

**TCP**

> Transmission control protocol, a protocol developed for the internet to get data from one network device to another. Uses a retransmission strategy to insure that data will not be lost in transmission.

**HTTP**

> the Hypertext Transfer Protocol - provides a standard for Web browsers and servers to communicate. The definition of HTTP is a technical specification of a network protocol that software must implement. HTTP is an application layer network protocol built on top of TCP.

---

What this means is that HTTP requests module in Adobe Air is an implementation of the HTTP protocol, which uses the same sockets and runs on top of TCP. If you create your own binary protocol using sockets, you can save some bandwidth. HTTP is a textual protocol that is very verbose and most of the time even human readable. That adds certain overhead that you can avoid.
> 1 votes

# Answer
A HTTP request is also a socket connection. It just adds additional overhead in form of a HTTP header. So when bandwidth and low latency is a concern for you, you should rather use your own socket-based protocol.

There is, however, an advantage of using HTTP: It usually works in restrictive network environments. High secure LANs, like you encounter them at workplaces, usually have firewalls which prohibit any direct socket connections to the outside and only allow communication with the internet via a HTTP proxy. Using HTTP might be the only way to communicate with the outside world in such a scenario.

So when you target the demographic of office workers at companies with a bring-your-own-device policy who want to play a bit when the boss isn't looking during their breaks, supporting HTTP might be a good idea.
> 0 votes

---
Tags: flash, multiplayer, client-server, turn-based, socket
---


# Question
Title: Sfml: Sprite scale transformation animation
Is there any way to animate a transformation on sf::Sprite like setScale or setPosition?

ie: `sprite.setScale(0.5f,0.5f);`. I want the transition between normal and half scale be smooth.

Thanks!

# Answer
> 2 votes
Simply use interpolation between the two values.

A simple form:

```
Vector2 goalScale = new Vector2(1,1);
Vector2 resultScale = sprite.getScale();

resultScale+= (goalScale - resultScale)/2; // increase division for stronger easing

sprite.setScale(resultScale);

```

Alternatively use a C++ tweener library.

---
Tags: c++, animation, sprites, sfml, transformation
---


title: Sub-systems in game engines

text:
# Question
Title: Sub-systems in game engines
So here's the problem- I'm writing my own engine library, and it works fine with stuff like menus and the actual game screen. The thing is, I can't really figure out how to integrate something like an intro or dialogue preceding certain levels into this system. Let's look at another example- say I have a game-specific engine which gets a Level object and runs it. Engine would have its own collision and physics system, all hard coded. Now, what if at some point in a level, I want the player to enter a mini-game with different rules? How do I morph the Engine class to support these sub-systems without having to deal with their code all the time (as in: if(regular game) ... else if(mini game) ...)?

And what if I want an intro animation at the start of a level, and I want the player to be able to assume control of his character once the animation ends, do I implement the animation into the Engine class itself? Or maybe I need to run another class, CutScene, and when it ends, it calls Engine and starts the level? What if I want to add a dialogue system, where at the start of each level there's a short dialogue and the player can't control his character, and once it ends, he can? Would I then run the dialogue code inside the Engine code?

Maybe these sub-systems should all be scripted? I don't know anything about scripting, is it necessary for this kind of situation? Any help would be appreciated.

# Answer
> 1 votes
Broad and hard questions, there is a ton of ways to engineer this. But i would go with something like an interface for a "Game" module, and then code different games from there. That way you could have an array of pointers to different classes which is different mini-games, but comes from the same pure virtual interface.

I think a good idea is to read some basic design patterns, and especially about modules and interfaces, and test some with that. In my opinion there is never a bad design for anything as long as you find it simple and use full to use it.

Design patterns on Wiki Random design pattern on google

Im not sure if thees are super good links, but what i saw they look like a good starting point for what you are asking.

Other than this, i think this is a super broad question and i cant even answer it all. You have to google around and hope for some more good answer to this question.

---
Tags: scripting, cutscene
---


# Question
Title: Something other than Vertex Welding with Texture Atlas?
What options (in C# with XNA) would there be for texture usage in a procedural generated 3D world made of cubes to increase performance? Yes, it's like Minecraft.

I've been doing a texture atlas and rendering faces individually (4 vertices per face), but I've also read in a couple places about using texture wrapping with two 1D atlases to merge adjacent faces with the same texture.

If two or more adjacent faces share the same image, it'd be quite easy to wrap in this way reducing vertices by a large amount. My problem with this is having too many textures, swapping too often, and many image related things like non-power of 2 images.

Is there a middle ground option between the 1D texture atlas trick and rendering 4 vertices per cube face?

This is a picture of what I have currently (in wireframe). 4 vertices per face seems extremely inefficient to me.

# Answer
So I've really exceeded my time budget for this question, with my mega-answer. But here's an idea, which you can hopefully evaluate using the code I've provided in my other answer:

Basically, you have two texture coordinates per quad: One that is the same for all vertices of a given quad, to select the tile within the texture atlas. The second has coordinates that interpolate as normal for a fully-wrappable (not atlased) texture (so from 0..1 for a single tile, but extending beyond that for wrapping). You then combine those in a pixel shader to perform the wrapping.

This lets you do **completely arbitrary wrapping** \- allowing 2D texture atlases and 2D merging of faces! Far better than the 1D atlas and 1D merging we were discussing before.

Here's a pixel-shader I threw together to do exactly that:

```
sampler TextureSampler : register(s0);

// Select the tile within a texture by its coordinates
// For a real implementation, you'd probably pass this in TEXCOORD1
float2 textureBase = float2(0, 0);

// The size, in texture coordinates, of a tile
float2 tileSize = float2(1.0 / 16.0, 1.0 / 16.0);

float4 main(float4 color : COLOR0, float2 texCoord : TEXCOORD0) : COLOR0
{
    // Adjust the texture coordinate to map into a specific tile:
    texCoord = frac(texCoord) * tileSize + textureBase;

    return tex2D(TextureSampler, texCoord) * color;
}

technique TileMapRepeater
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 main();
    }
}

```

It's tested working, although it gives seams if you don't use point-sampling. You might be able to get it to work with linear-sampling, but that's more effort and a lot more computationally expensive.

So the question would be: **are extra pixel shader calculations and added vertex data worth the significant reduction in quads rendered?** I'll leave it to you to figure that out :)
> 5 votes

# Answer
This is a performance question. So, as always, the answer is: **measure it!**

So this is exactly what I did:

The Y axis is time taken to render, and the X axis is the number of "faces" rendered (pre-merging).

By my own rough estimates, a "really big Minecraft vista" is somewhere around the middle of the X axis. This is all assuming reasonable culling (you're not drawing faces between solid cubes, you're not drawing the inside of caves, you're not drawing chunks behind you).

I've simplified by assuming that uniform orthographic square faces are adequate analogue to perspective-rendered faces. I've assumed full screen coverage with no overdraw, and 25% of faces are off-screen.

I've assumed `BasicEffect`, with `VertexColorEnabled` and `TextureEnabled` (so: a vertex buffer of `VertexPositionColorTexture`), is a reasonable approximation of your shader for performance purposes.

**For this graph, I've *guessed* an average 4:1 merge ratio in a scene.** And that uniform merging is a suitable approximation.

There are 6 lines on my graph. The top three are without merging faces (1 quad = 1 face). The bottom three are with faces merged (1 quad ≃ 4 faces). Each set of three tests are with different textures: a single-pixel texture, a 2D texture atlas and a 1D texture atlas. Each atlas is made up of 16-by-16 pixel tiles (like Minecraft)

Given the way the measurements are the same no matter what texture is used tells us that, on a modern graphics card (or, at least, on *my* graphics card), and with textures at that resolution, **there's no performance downside to having a 1D texture atlas**.

Of course, a major limitation on this is that **XNA has a maximum texture size of 4096** (2048 in the Reach profile), which strictly limits the number of tiles you can have in a 1D atlas.

One potential work-around for this would be to have separate vertex buffers and batches for separate texture atlases. This would be a lot of additional work - so I didn't test this. In theory, this should allow you maintain this performance improvement, with limited negative impact, as long as you have the batches to spare - which may not be the case if you already rendering one batch per chunk.

And, of course, the two groups of lines on this graph tells us that **merging faces gives a significant, measurable performance improvement**. This performance improvement scales with the number of faces you can merge together.

This performance improvement exists even for relatively small numbers of faces, so it should still work if you have one vertex buffer per chunk - although the improvements may not be as significant. (I tested with a single vertex buffer for simplicity.)

Texture orientation may cause a reduction in the number of faces that can be merged or limit the available texture space (duplicating areas of texture should not affect performance, as texturing is not the limiting factor here). Another thing that will limit the number of faces that can be merged is lighting.

Of course, the slope of the graph tells us pretty much the same thing - and, in a more general sense - that **fewer quads drawn means better performance**, pretty-much linearly, no matter what method you are using to reduce the number of quads. (Note: quads cost both vertex processing time and raster time.)

So any method you have to reduce quads drawn is something you should consider implementing - whether that is face merging or culling.

At about the middle of that graph **this performance optimisation represents an improvement of about 1.4% of frame time**, on my GPU, at 60 FPS (the time for an entire frame at 60FPS is about 20 times higher than the visible graph area). And, again, it scales with the number of faces merged - for which I used a very generous estimate. So there's a very good chance that this performance optimisation may not provide sufficient improvement to justify the effort of its implementation.

---

Below is the code I used, which can be dropped into an empty XNA 4.0 project. You could use this for further performance experimentation.

```
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace VertexMergeTest
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            graphics.GraphicsProfile = GraphicsProfile.HiDef;
            graphics.PreferredBackBufferWidth = 1280;
            graphics.PreferredBackBufferHeight = 720;
            graphics.PreferMultiSampling = true; // Causes the rasterizer to do more work per polygon (subpixel sampling)
            graphics.IsFullScreen = true;

            Content.RootDirectory = "Content";

            // Unlock timer for performance measuring
            graphics.SynchronizeWithVerticalRetrace = false;
            IsFixedTimeStep = false;

            Window.AllowUserResizing = true;
            IsMouseVisible = true;
        }

        BasicEffect basicEffect;

        protected override void LoadContent()
        {
            SetupTextures();

            basicEffect = new BasicEffect(GraphicsDevice);
            basicEffect.VertexColorEnabled = true;
            basicEffect.TextureEnabled = true;

            Begin();
        }

        #region Textures

        void SetupTextures()
        {
            // Assume 16x16 tiles, arranged either 16x16 or 1x256 (note that this is the maximum texture height)
            Color[] buffer = new Color[16*16*16*16];
            for(int i = 0; i < buffer.Length; i++)
                buffer[i] = Color.White; // Assume texture contents don't affect performance

            whitePixel = new TextureInfo { texture = new Texture2D(GraphicsDevice, 1, 1), widthInTiles = 1, heightInTiles = 1 };
            whitePixel.texture.SetData(new[] { Color.White });

            twoDeeAtlas = new TextureInfo { texture = new Texture2D(GraphicsDevice, 16*16, 16*16), widthInTiles = 16, heightInTiles = 16 };
            twoDeeAtlas.texture.SetData(buffer);

            oneDeeAtlas = new TextureInfo { texture = new Texture2D(GraphicsDevice, 16*1, 16*16*16), widthInTiles = 1, heightInTiles = 16*16 };
            oneDeeAtlas.texture.SetData(buffer);
        }

        class TextureInfo
        {
            public Texture2D texture;
            public int widthInTiles, heightInTiles;

            public float TileWidthTexCoord { get { return 1f / (float)widthInTiles; } }
            public float TileHeightTexCoord { get { return 1f / (float)heightInTiles; } }

            public int TileCount { get { return widthInTiles * heightInTiles; } }

            public Vector2 GetTextureBase(int tile)
            {
                tile = tile % TileCount;
                int x = tile % widthInTiles;
                int y = tile / widthInTiles;
                return new Vector2(x * TileWidthTexCoord, y * TileHeightTexCoord);
            }
        }

        TextureInfo whitePixel, twoDeeAtlas, oneDeeAtlas;
        TextureInfo currentTexture;

        #endregion

        #region Buffers

        VertexBuffer vertexBuffer;
        IndexBuffer indexBuffer;

        void CleanupTest()
        {
            if(vertexBuffer != null)
                vertexBuffer.Dispose();
            if(indexBuffer != null)
                indexBuffer.Dispose();
            vertexCount = 0;
            indexCount = 0;
        }

        void CreateBuffers()
        {
            vertexBuffer = new VertexBuffer(GraphicsDevice, vertices.GetType().GetElementType(),
                    vertexCount, BufferUsage.WriteOnly);
            vertexBuffer.SetData(vertices, 0, vertexCount);

            indexBuffer = new IndexBuffer(GraphicsDevice, IndexElementSize.ThirtyTwoBits,
                    indexCount, BufferUsage.None);
            indexBuffer.SetData(indices, 0, indexCount);
        }

        #endregion

        #region Geometry

        VertexPositionColorTexture[] vertices = new VertexPositionColorTexture[endTestAtFaces * 4];
        int[] indices = new int[endTestAtFaces * 6];

        int vertexCount;
        int indexCount;
        int sideSize;

        void AddQuad(int x, int y, int width, int height, int tileTextureNumber)
        {
            Vector2 textureBase = currentTexture.GetTextureBase(tileTextureNumber);
            Vector2 textureWidth = new Vector2(currentTexture.TileWidthTexCoord * width, 0);
            Vector2 textureHeight = new Vector2(0, currentTexture.TileHeightTexCoord * height);

            vertices[vertexCount + 0] = new VertexPositionColorTexture
            {
                Position = new Vector3(x, y, 0),
                Color = Color.Lerp(Color.White, Color.Black, 0.1f),
                TextureCoordinate = textureBase
            };

            vertices[vertexCount + 1] = new VertexPositionColorTexture
            {
                Position = new Vector3(x, y+height, 0),
                Color = Color.Lerp(Color.White, Color.Black, 0.8f),
                TextureCoordinate = textureBase + textureHeight
            };

            vertices[vertexCount + 2] = new VertexPositionColorTexture
            {
                Position = new Vector3(x+width, y+height, 0),
                Color = Color.Lerp(Color.White, Color.Black, 0.6f),
                TextureCoordinate = textureBase + textureWidth + textureHeight
            };

            vertices[vertexCount + 3] = new VertexPositionColorTexture
            {
                Position = new Vector3(x+width, y, 0),
                Color = Color.Lerp(Color.White, Color.Black, 0.3f),
                TextureCoordinate = textureBase + textureWidth
            };

            indices[indexCount + 0] = vertexCount + 0;
            indices[indexCount + 1] = vertexCount + 1;
            indices[indexCount + 2] = vertexCount + 2;
            indices[indexCount + 3] = vertexCount + 2;
            indices[indexCount + 4] = vertexCount + 3;
            indices[indexCount + 5] = vertexCount + 0;

            vertexCount += 4;
            indexCount += 6;
        }

        #endregion

        #region Begin and End

        void Begin()
        {
            SetupTestSequence();
            WriteOutputHeader();

            facesInTest = facesPerTestIncrement;
            StartTestSequence();
        }

        void Finish()
        {
            File.WriteAllText("output.csv", outputText.ToString());

            Exit();
        }

        #endregion

        #region Test Sequence and Data Formatting

        StringBuilder outputText = new StringBuilder(8000);

        class Test
        {
            public string name;
            public Action<int> setupTest;
        }

        int currentTestNumber = 0;
        List<Test> testSequence = new List<Test>();

        void WriteOutputHeader()
        {
            // File Header
            outputText.AppendLine("Ticks per second = ," + Stopwatch.Frequency);
            outputText.AppendLine("Warmup Frames = ," + warmupFrames);
            outputText.AppendLine("Frames Per Measurement = ," + testFrames);
            outputText.AppendLine("Average Mergable Faces = ," + averageMergableFaces);
            outputText.AppendLine();

            // Column Headers
            outputText.Append("Faces");
            for(int i = 0; i < testSequence.Count; i++)
            {
                outputText.Append(',');
                outputText.Append(testSequence[i].name);
            }
        }

        void StartTestSequence()
        {
            outputText.AppendLine();
            outputText.Append(facesInTest);
            outputText.Append(',');

            currentTestNumber = 0;
            DoTestSetup(testSequence[currentTestNumber].setupTest, facesInTest);
            warmup = true;
        }

        void FinishTestAdvanceToNext(long resultTicks)
        {
            outputText.Append(resultTicks);

            if(++currentTestNumber < testSequence.Count)
            {
                // Next test in sequence
                outputText.Append(',');
                DoTestSetup(testSequence[currentTestNumber].setupTest, facesInTest);
            }
            else
            {
                // Increment face count and start the test sequence again
                facesInTest += facesPerTestIncrement;

                if(facesInTest > endTestAtFaces) // ... or finish all tests
                {
                    Finish();
                    return;
                }

                StartTestSequence();
            }

            // Start by warming up
            warmup = true;
        }

        void DoTestSetup(Action<int> setupAction, int faceCount)
        {
            CleanupTest();

            // Attempt to fill the display area with approximate squares:
            sideSize = (int)Math.Ceiling(Math.Sqrt(faceCount));

            setupAction(faceCount);

            CreateBuffers();
        }

        void SetupTestSequence()
        {
            testSequence.Add(new Test()
            {
                name = "Standard 0D",
                setupTest = (faceCount) =>
                    {
                        currentTexture = whitePixel;

                        for(int i = 0; i < faceCount; i++)
                        {
                            int x = i % sideSize;
                            int y = i / sideSize;

                            AddQuad(x, y, 1, 1, i / averageMergableFaces);
                        }
                    }
            });

            testSequence.Add(new Test()
            {
                name = "Standard 1D",
                setupTest = (faceCount) =>
                {
                    currentTexture = oneDeeAtlas;

                    for(int i = 0; i < faceCount; i++)
                    {
                        int x = i % sideSize;
                        int y = i / sideSize;

                        AddQuad(x, y, 1, 1, i / averageMergableFaces);
                    }
                }
            });

            testSequence.Add(new Test()
            {
                name = "Standard 2D",
                setupTest = (faceCount) =>
                {
                    currentTexture = twoDeeAtlas;

                    for(int i = 0; i < faceCount; i++)
                    {
                        int x = i % sideSize;
                        int y = i / sideSize;

                        AddQuad(x, y, 1, 1, i / averageMergableFaces);
                    }
                }
            });

            testSequence.Add(new Test()
            {
                name = "Merged 0D",
                setupTest = (faceCount) =>
                {
                    currentTexture = whitePixel;

                    for(int i = 0; i < faceCount; i++)
                    {
                        int x = i % sideSize;
                        int y = i / sideSize;

                        int width = Math.Min(averageMergableFaces, sideSize-x);
                        AddQuad(x, y, width, 1, i / averageMergableFaces);
                        i = i - 1 + width;
                    }
                }
            });

            testSequence.Add(new Test()
            {
                name = "Merged 1D",
                setupTest = (faceCount) =>
                {
                    currentTexture = oneDeeAtlas;

                    for(int i = 0; i < faceCount; i++)
                    {
                        int x = i % sideSize;
                        int y = i / sideSize;

                        int width = Math.Min(averageMergableFaces, sideSize-x);
                        AddQuad(x, y, width, 1, i / averageMergableFaces);
                        i = i - 1 + width;
                    }
                }
            });

            testSequence.Add(new Test()
            {
                name = "Merged 2D",
                setupTest = (faceCount) =>
                {
                    currentTexture = twoDeeAtlas;

                    for(int i = 0; i < faceCount; i++)
                    {
                        int x = i % sideSize;
                        int y = i / sideSize;

                        int width = Math.Min(averageMergableFaces, sideSize-x);
                        AddQuad(x, y, width, 1, i / averageMergableFaces);
                        i = i - 1 + width;
                    }
                }
            });
        }

        #endregion

        Stopwatch stopwatch = new Stopwatch();

        int frameCounter;
        const int warmupFrames = 100;
        const int testFrames = 400;
        bool warmup;

        const int facesPerTestIncrement = 500;
        int facesInTest = 0;
        const int endTestAtFaces = 100000;

        // This is the number of adjacent faces that could be merged
        const int averageMergableFaces = 4;

        protected override void Update(GameTime gameTime)
        {
            frameCounter++;

            if(warmup)
            {
                if(frameCounter >= warmupFrames)
                {
                    frameCounter = 0;
                    warmup = false;
                    stopwatch.Restart(); // Begin performance test this frame
                }
            }
            else
            {
                if(frameCounter >= testFrames)
                {
                    frameCounter = 0;

                    // End test this frame
                    stopwatch.Stop();
                    FinishTestAdvanceToNext(stopwatch.ElapsedTicks);
                }
            }

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // Setup camera
            basicEffect.World = Matrix.Identity;
            basicEffect.View = Matrix.Identity;
            basicEffect.Projection = Matrix.CreateOrthographicOffCenter(0, sideSize, 0, sideSize * 0.25f, -1, 1); // cut off 0.25 to simulate hidden faces

            GraphicsDevice.SetVertexBuffer(vertexBuffer);
            GraphicsDevice.Indices = indexBuffer;
            GraphicsDevice.SamplerStates[0] = SamplerState.PointWrap;

            basicEffect.Texture = currentTexture.texture;

            foreach(var pass in basicEffect.CurrentTechnique.Passes)
            {
                pass.Apply();

                GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0,
                        vertexCount, 0, indexCount / 3);
            }

            base.Draw(gameTime);
        }
    }
}

```
> 7 votes

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


title: Optimizing drawing of cubes

text:
# Question
Title: Optimizing drawing of cubes
After googling for hours I've come to a few conclusions, I need to either rewrite my whole cube class, or figure out how to use hardware instancing. I can draw up to 2500 cubes with little lag, but after that my fps drops. Is there a way I can use my class for hardware instancing? Or would I be better off rewriting my class for optimization?

```
    public class Cube
{
public GraphicsDevice device;
public VertexBuffer cubeVertexBuffer;

public Cube(GraphicsDevice graphicsDevice)
{
    device = graphicsDevice;

    var vertices = new List<VertexPositionTexture>();

    BuildFace(vertices, new Vector3(0, 0, 0), new Vector3(0, 1, 1));
    BuildFace(vertices, new Vector3(0, 0, 1), new Vector3(1, 1, 1));
    BuildFace(vertices, new Vector3(1, 0, 1), new Vector3(1, 1, 0));
    BuildFace(vertices, new Vector3(1, 0, 0), new Vector3(0, 1, 0));

    BuildFaceHorizontal(vertices, new Vector3(0, 1, 0), new Vector3(1, 1, 1));
    BuildFaceHorizontal(vertices, new Vector3(0, 0, 1), new Vector3(1, 0, 0));

    cubeVertexBuffer = new VertexBuffer(device, VertexPositionTexture.VertexDeclaration, vertices.Count, BufferUsage.WriteOnly);

    cubeVertexBuffer.SetData<VertexPositionTexture>(vertices.ToArray());

}

private void BuildFace(List<VertexPositionTexture> vertices, Vector3 p1, Vector3 p2)
{
    vertices.Add(BuildVertex(p1.X, p1.Y, p1.Z, 1, 0));
    vertices.Add(BuildVertex(p1.X, p2.Y, p1.Z, 1, 1));
    vertices.Add(BuildVertex(p2.X, p2.Y, p2.Z, 0, 1));
    vertices.Add(BuildVertex(p2.X, p2.Y, p2.Z, 0, 1));
    vertices.Add(BuildVertex(p2.X, p1.Y, p2.Z, 0, 0));
    vertices.Add(BuildVertex(p1.X, p1.Y, p1.Z, 1, 0));
}

private void BuildFaceHorizontal(List<VertexPositionTexture> vertices, Vector3 p1, Vector3 p2)
{
    vertices.Add(BuildVertex(p1.X, p1.Y, p1.Z, 0, 1));
    vertices.Add(BuildVertex(p2.X, p1.Y, p1.Z, 1, 1));
    vertices.Add(BuildVertex(p2.X, p2.Y, p2.Z, 1, 0));
    vertices.Add(BuildVertex(p1.X, p1.Y, p1.Z, 0, 1));
    vertices.Add(BuildVertex(p2.X, p2.Y, p2.Z, 1, 0));
    vertices.Add(BuildVertex(p1.X, p1.Y, p2.Z, 0, 0));
}

private VertexPositionTexture BuildVertex(float x, float y, float z, float u, float v)
{
    return new VertexPositionTexture(new Vector3(x, y, z), new Vector2(u, v));
}

public void Draw(BasicEffect effect)
{

    foreach (EffectPass pass in effect.CurrentTechnique.Passes)
    {
        pass.Apply();
        device.SetVertexBuffer(cubeVertexBuffer);
        device.DrawPrimitives(PrimitiveType.TriangleList, 0, cubeVertexBuffer.VertexCount / 3);
    }
}
}

```

The following class is a list that draws the cubes.

```
    public class DrawableList<T> : DrawableGameComponent
{
    private BasicEffect effect;
    private ThirdPersonCam camera;
    private class Entity
    {
        public Vector3 Position { get; set; }
        public Matrix Orientation { get; set; }
        public Texture2D Texture { get; set; }
    }

    private Cube cube;
    private List<Entity> entities = new List<Entity>();

    public DrawableList(Game game, ThirdPersonCam camera, BasicEffect effect)
        : base(game)
    {
        this.effect = effect;
        cube = new Cube(game.GraphicsDevice);
        this.camera = camera;
    }

    public void Add(Vector3 position, Matrix orientation, Texture2D texture)
    {

        entities.Add(new Entity()
        {
            Position = position,
            Orientation = orientation,
            Texture = texture
        });
    }

    public override void Draw(GameTime gameTime)
    {
        foreach (var item in entities)
        {

            effect.VertexColorEnabled = false;
            effect.TextureEnabled = true;
            effect.Texture = item.Texture;

            Matrix center = Matrix.CreateTranslation(new Vector3(-0.5f, -0.5f, -0.5f));
            Matrix scale = Matrix.CreateScale(1f);
            Matrix translate = Matrix.CreateTranslation(item.Position);

            effect.World = center * scale * translate;
            effect.View = camera.view;
            effect.Projection = camera.proj;

            effect.FogEnabled = true;
            effect.FogColor = Color.CornflowerBlue.ToVector3();
            effect.FogStart = 1.0f;
            effect.FogEnd = 50.0f;

            cube.Draw(effect);
        }

        base.Draw(gameTime);
    }
}
}

```

There are probably many reasons that my fps is so slow, but I can't seem to figure out how to fix it. I've looked at techcraft as well, but what I have is too specific to what I want the outcome to be to just rewrite everything from scratch

# Answer
Are you trying to create a voxel engine (with grid-aligned cubes)?

If so: Try doing face occlusion. When you build a cube, check if it has a neighbor cube. If, say, the block to the X- position is solid, then you don't need to build the X- face.

```
if(!blocks[x - 1][y][z].solid) { /* build XNegative face */ }
if(!blocks[x + 1][y][z].solid) { /* build XPositive face */ }
// etc...

```

If you aren't trying to create a voxel engine, and instead want to just have a lot of objects that are cubes, then yes, you will want to look into hardware instancing. You can do so with XNA's GraphicsDevice.DrawInstancedPrimitives() method.
> 3 votes

# Answer
The blog 0FPS has an excellent article on optimizing using greedy meshes: Meshing in a Minecraft Game

The article reviews some of the basic ideas like culling presented by previous answers, and then describes a fairly simple system to greatly reduce the meshes needed for a large number of cubes. While the middle of the article is math-heavy, there are concrete examples near the end including a JavaScript demo. An additional part 2 of the article describes other possible optimizations.
> 1 votes

# Answer
You should only draw the cubes that need to be drawn. I can't help you much on this since my experience lies with 2D mostly.

And you should never use you cubeclass to populate the world. If so your cube class gets iterated each gameloop probably multiple times (in update and drawing). If you just make a struct like this:

```
struct Cube
{
public int textureID;
public int health;
//or even
public byte health;
}

```

and then make a 3 dimensional array from that it will iterate through that many times faster. Within this iteration you decide what to draw and using the cubes\[x,y,z\] to where you are drawing it. Using bytes won't speed up the iteration but when saving millions of cubes to disk will save disk space.
> 0 votes

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


# Question
Title: How can you put all images from a game to 1 file?
I've just finished a basic RPG game written in C++ SFML, I've put a lot of effort into the game and I'd want to distribute it, however I've ran into a small issue.

Problem is, I have well over 200 images and map files (they're .txt files which hold map codes) all in the same folder as the executable, when I look in the folder, it makes me want to cry a little bit seeing so many resources, I've never seen a game which shows you all the resources directly, instead I believe they pack the resources in a certain file.

Well, that's what I'm trying to achieve: I'm hoping to pack all the images in 1 file (Maybe the .txt files as well) then being able to read from that file or easily add to it.

# Answer
Game programmers have relied on one of two main methods of data storage:

* store each data file as a separate file
* store each data file in a custom archive format

The drawback to the first solution is the wasted disk space problem, as well as the problem of slower installations.

The second solution provides it's own pitfalls, first is that you must write all your own image/sound/etc. loading routines which use a custom API for accessing the archived data. A further drawback is that you have to write your own archive utility to build the archives in the first place.

Unless you will always load all files from the archive, TAR/GZ might not be a very good idea, because you cannot extract specific files as you need them. This is the reason many games use ZIP archives, which do allow you to extract individual files as required (a good example is Quake 3, whose PK3 files are nothing but ZIP files with a different extension).

**EDIT :** "Hide" the game folder structure and "Keep" only the executables

> Another solution is often used to "hide" the game files in folder structure. Keep only your executables and maybe a readme file in the main directory and move the game files into a sub folder named "data" or other related.

**EDIT :** Gamedev Tuts Plus have a nice resource

**EDIT :** libarchive

One potential solution libarchive, which is an archiving library that will handle extracting files from an archive such as a ZIP file. It even allows you to assign the extracted file to a standard FILE pointer, which would make interfacing with any other libraries potentially more straightforward.

**EDIT :** ZIP Format files with alternative extension

Here, I like @Joachim Sauer's Comment

> Using ZIP-format files with alternative extensions has a great tradition outside of games as well: Java does it, the OpenDocument Format (a.k.a. the OpenOffice/LibreOffice format) does it, even Office Open XML (a.k.a. the "new" Microsoft Office format) does it.
> 64 votes

# Answer
Another solution often used to "hide" the game files is folder structure. Keep only your executables and maybe a readme in the main directory and move the game files into a sub folder "data". I don't think that it is very uncommon to do so. Many games I know store their content in such a way.
> 39 votes

# Answer
I really like PhysFS for this. It allows you to access either folders or zip archives with the same code. It works well for all stages of a Games lifetime.

1. **During development**: access the resources directly from a folder hierarchy. This way compressed archives are not in the way and you can rapidly iterate.
2. **Initial deployment**: zip up your resources for easy deployment / quick installs. No code needs to change. Just point PhysFS at the zip instead of the folder.
3. **Updates / Modding**: PhysFS can load multiple zip archives where the resources from one override the other. Updates can be as simple as a new zip with only the changed files. Similarly for modding.

---

### update:

I used the tutorial included with the source and the doxygen documentation to learn PhysFS. The API really is fairly simple, you'll spend more time learning how to load images into SFML via memory buffers instead of by file path.
> 22 votes

# Answer
I'd suggest using a ZIP file. It's an ubiquitous format and you'll find ready-made libraries that allow you to load files from within a ZIP file. A quick Google search even revealed a zip loader for sfml.
> 12 votes

# Answer
Well, you could cheat like they mentioned:) You can make a sprite-sheet from the imagery, there is no need to zip it nowadays unless it saves a ton of space. After you create a sprite-sheet or several sprite-sheets from the images, you could simply rename their extensions. Most Gamers will not bother to check and why not leave that option to Artists who may want to mod your game in the future? That way they can too create a sprite-sheet, rename it's extension and start rolling.

With the text files, I would humbly suggest you convert that data into binary form. I am pretty sure you will find a simple way to do it.. For instance, if you only use A-Z, a-z and the 0-9, you can use 6 bits to represent each character, that will somewhat protect your copyrighted material, it will also prevent others from editing maps.. You can always add a map converter if you like. Zipping is completely reasonable for text though.
> 3 votes

# Answer
It's not only about the number of resources or disk space.
With a lot of different texture files, as you are using SFML, which renders with OpenGL, each time you are going to render a texture, OpenGL needs to bind the next texture to the video card (check glBindTexture() ), and it is a really expensive task.
With that in mind you can realize why games usually put a number of sprites in the same texture, the so called spritesheets, according to your menus/levels/maps of the game.
The result is a huge gain in performance, since you are rendering a lot of sprites with the same bind texture call.
> 2 votes

# Answer
I would personally head down the custom binary file route for this. This is something I do myself all of the time now, it isn't as difficult as it might sound, and it also provides a level of obfuscation for you game resource files. I wrote a small introductory Gamedev article about this not so long ago if you are interested:

http://gamedev.tutsplus.com/tutorials/implementation/create-custom-binary-file-formats-for-your-games-data/

Sprite-sheets are a different subject entirely but they are the norm for most games :)
> 2 votes

# Answer
Another method you can use:

The free version of XnView provides a feature called "`Strip of Images`" (SHIFT+A), which allows you to create `sprite-collections`.

This minimizes file access and is particularly important for web applications/games to minimize the number of `HTTP-roundtrips`.

Access to individual images is then granted through coordinate maps (for instance css-definitions).
> 1 votes

# Answer
First you must write all your own image/sound/etc. loading routines which use a custom API for accessing the archived data. A further drawback is that you have to write your own archive utility to build the archives in the first place. Unless you will always load all files from the archive, TAR/GZ might not be a very good idea, because you cannot extract specific files as you need them. This is the reason many games use ZIP archives, which do allow you to extract individual files as required (a good example is Quake 3, whose PK3 files are nothing but ZIP files with a different extension). http://zpp-library.sourceforge.net/
> 0 votes

---
Tags: c++, assets, sfml, spritesheet
---


# Question
Title: XNA Rendering vertices that only appear within the cameras view
I'm making a game in XNA and I recall hearing that professionally made games use a technique to only render the polygons that appear within the cameras projection. I've been trying to find something on this to do something similar in my game, could anyone point me in the right direction? Right now all I have is a plane/grid of vertices that you can set the X/Y on which is drawn using DrawUserIndexedPrimitives, but I plan to make a bunch of props as scenery items and I can imagine myself running into issues later on if I don't address this now.

Thanks

# Answer
> 0 votes
## Basic Frustum Culling

Frustum culling is what you are looking for and is very easy to do in XNA. Create a Bounding Frustum by passing in the view\*projection matrices.

```
Frustum = new BoundingFrustum(view * projection);

```

Then create Bounding Boxes for your models. Finally you want to make sure you only draw the model's whose Bounding Boxes interact with the Bounding Frustum.

```
foreach (var gameobject in gameobjects) {
    currentContainmentType = Frustum.Contains(BoundingBoxe);
    if (currentContainmentType != ContainmentType.Disjoint)
    {
        //Draw gameobject
    }
}

```

---
Tags: xna, rendering, camera, projection
---


# Question
Title: Common way to store model transformations
I ask myself what's the best way to store the transformations in a model class. What I came up with is to store the translation and scaling in a Vector3 and the rotation in a Matrix4.

On each update (frame) I multiply the 3 matrices (first build a Translation and Scaling Matrix) to get the world matrix. In this way I have no accumulated error.

```
world = translation * scaling * rotation

```

Another way would be to store the rotation in a quaternion but then I would have a high cost to convert to a matrix every time step. If I lerp the model I convert the rotation matrix to quaternion and then back to matrix.

For speed optimization I have a global dirty flag and one for each transformation so that I only do a matrix multiplication if necessary.

```
if (isDirty) {
    world = translation
    if (isScaled) {
        world *= scaling
    }
    if (isRotated) {
        world *= rotation
    }
}

```

Is this a common way or is it more common to have only one Matrix4 for all transformations? And is it better to store the rotation only as quaternion? For info: Currently I'm building a CSS3D engine in Javascript but these questions are relevant for every 3D engine.

# Answer
> 0 votes
I would prefer

world = translation * scaling * rotation

you save the translation and scaling and rotation matrix in each object and recalculate the matrices only if the transation/scaling/rotation changed.

In the rendering loop you transform the object after the world matrix.

The reason for this against the cached version is simple, it doesn't branch (except in the multiplication operation, but the compiler or you can inline/optimize it so it works without branches) and its more simple.

**About the Quaternions**: You use Quaternions only if the rotate operations are used very frequently (Forward kinematic, IK) because of the Quaternion\<-\>Matrix conversation overhead.

---
Tags: matrix, models, transformation
---


# Question
Title: does glBindAttribLocation silently ignore names not found in a shader?
Does `glBindAttribLocation` silently ignore names that are not found? For example, in a shader:

```
// Some vertex shader
in vec3 position;
in vec3 normal;
// ...

```

And in some set up code:

```
// While setting up shader
GLuint program = glCreateProgram();
glBindAttribLocation(program, 0, "position");
glBindAttribLocation(program, 1, "normal");
glBindAttribLocation(program, 2, "color"); // What about this one?
glLinkProgram(program);

```

# Answer
> 3 votes
I did a test for that and the short answer is openGL didn't return any error.

OpenGL documentation also states:

> glBindAttribLocation can be called before any vertex shader objects are bound to the specified program object. **It is also permissible to bind a generic attribute index to an attribute variable name that is never used in a vertex shader.**
>
> If name was bound previously, that information is lost. Thus you cannot bind one user-defined attribute variable to multiple indices, but you can bind multiple user-defined attribute variables to the same index.

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


# Question
Title: Resolution independence - resize on the fly or ship all sizes?
My game relies heavily on textures of various sizes with some being full-screen. The game is targeted for multiple resolutions. I found that resizing textures (downsizing) works quite well for this game’s art type (it’s not Pixel Art or anything like that). I asked my artist to ensure that all textures at the edges of the screen to be created in such a way that they can safely “overflow” off screen; this means that aspect ratio is not an issue.

So with no aspect ratio issues, I figured that I would simply ask my artist to create assets in very high resolution, and then resize them down to the appropriate screen resolution. The question is, *when* and *how* do I do that?

Do I pre-resize everything to common resolutions in Photoshop and package *all* assets in the final product (increasing the size download that the user has to deal with) and then select the appropriate asset based on the detected resolution? Or do I ship with the largest set of Textures, detect the resolution on load, set a render target and draw all downsized assets to it and use that? Or for the latter, do I use some sort of a CPU-sided algorithm to resize on game load?

# Answer
> 1 votes
Generally you do what you need and that requires testing and/or some thought:

* Does your platform allow pre-rendering all different sizes, perhaps with manual touch-up when needed, or will the distribution simply be too big?
* Does your platform incur too much of a performance hit using the largest assets at all times?
* Can you do a platform-based resize during initialization of the game (pre-render on load) to avoid the above if it applies?
* Does your platform allow you to resize assets in a way that looks acceptable to you?
* If it looks good and performs well enough - just go with it

Sometimes having a few different major sizes pre-rendered is a good idea - a 256x256 pixel bitmap won't resize favourably to 16x16 or even 32x32 unless an artist does it by hand - so perhaps you should have two or three vastly different sizes from your artist and pick the one that's the best fit at run-time.

---
Tags: textures, resolution, rendertargets
---


# Question
Title: When to use an Array vs When to use a Vector, when dealing with GameObjects?
I understand that from other answers, Arrays and Vectors are the best choices. Many on SE claim that Linked Lists and Maps are bad for video game programming.

I understand that for the most part, I can use Arrays. However, I don't really understand exactly when to use Vectors over Arrays.

Why even use Vectors? Wouldn't it be best if I simply always used an Array, that way I know how much memory my game needs?

Specifically my game would only ever load a single "Map" area of tiles, such as Map\[100\]\[100\], so I could very easily have an array of GameObjectContainer GameObjects\[100\]\[100\], which would reserve an entire map's worth of possible gameobjects, correct?

So why use a Vector instead? Memory is quite large on modern hardware.

# Answer
Vectors are dynamically sized (usually) random access containers. They facilitate constant time look ups to any location within the array, and better yet, their direct storage is contiguous. The biggest (and its a big one) downside to vectors is the performance hit when they need to grow. Vectors typically allocate a certain capacity, and this capacity is expanded whenever it is either full, or when the vector size reaches a specific threshold. Due to vectors requiring contiguous memory to maintain constant time random access, they must allocate an entirely new block of memory of the appropriate size, and copy over the contents. This is slow.

Linked lists on the other hand are linear access containers, requiring you to walk the list (either from beginning or end), this makes it difficult if you need access to a specific member of the list. The major benefit of linked lists is the ability to add, and remove data members in constant time. Linked lists are not contiguous.

Maps/Hash maps are often built on top of a container such as a vector (though it could just be a standard C-style array), and provide constant time look ups via key, as opposed to index. They suffer the same disadvantages that vectors do. The efficiency of a hash map depends on the efficiency of the hash function. It is not uncommon for a hashing algorithm to be unique to the data set, as opposed to a simple modulus bucket count operation

All data types are suitable at times, and you should always approach each problem differently.

EDIT - There are numerous reasons to avoid standard C-style arrays, and they usually come back to user error. One of the biggest issues is the risk of writing beyond the bounds of the array, and modifying something else in memory. This can be an extremely difficult bug to detect, and even harder to fix. Additionally, c-style arrays dont have integrated support for STL algorithms, iterators, and allocators.
> 5 votes

---
Tags: vector, data-structure, gameobject
---


title: Rendering order in an Entity System

text:
# Question
Title: Rendering order in an Entity System
Say I use a basic ES approach, and also inside Systems I hold lists of all entities that Systems are required to process.

How do I maintain this list of entities in desired rendering order, i.e. for a dumb 2D RenderingSystem?

I saw this discussion, and what they suggest is to do something like Z ordering - what I would probably do is just to store a "layer" int in DrawableComponent and then, inside RenderingSystem, just sort entities by mentioned "layer" whenever the entity list for RenderingSystem changes.

They also say we could just delete and recreate the entity whenever we want it on the top, but it seems too inflexible to me.

How is this problem usually solved?

# Answer
> 7 votes
Sort at rendering time if you sort at all. You don't need to keep the list sorted during every operation; in fact, this may be harmful. What happens if you spawn 20 enemies at once? Sort 20 times? They sorted quality doesn't matter until rendering, so why ever do it more than once per frame?

Furthermore, with an entity-component system, it can be handy to keep component databases sorted similarly. Despite all the theoretical cruft on the Internet about ECS, you will at times need to update two object lists in parallel or otherwise break out of the single-system ideal. Keeping the entities' components in these lists consistently ordered will make such updates faster; instead of iterating over one list sequentially and the other in essentially random order, you iterate over both sequentially. Your component databases should intrinsically have this property.

There's also a strong argument to make for separate object collections. The ComponentSprite component can just be a data record noting what the object wants rendered while a completely separate scene graph manages SceneSprite objects that deal with efficient rendering. Complex game objects might be made out of multiple sprites or so on in ways that are inefficient to handle with game object hierarchies. Your renderer and object systems don't need to be interdependent. Or they can be. Whichever is easier for your game.

When the renderable list changes, just mark a flag that it's dirty. Before rendering, check the flag and resort if it's set (and then unset the flag, of course).

In 3D systems this is more important as the entire sort order is likely to shift and change almost every frame.

Remember that it's not *just* layer you might want to sort by. With enough objects on screen - even in 2D - you might need to sort by screen tile, sprite, effect, etc., in addition to or instead of layer/depth.

For many games you can split your renderable object list into a set of layer "buckets." When an object is create/removed/re-layered, just perform a simple add/remove as necessary to the corresponding bucket(s). No need for explicit sorting steps at all. Many 2D games work with only a few pre-defined layers so they're simply no need for arbitrary depth/layer values to sort by.

# Answer
> 3 votes
i had something like this once.

i sorted the entity array by property z.

i used a sorting algorithm for it.

and the game loop ran from lowest z to highest z

somthing like: (every game loop so youll need a good sorting algorithm,and that did the trick,showd the right entities in front, everything was on its defind layer)

```
    this.y_world_mc=y_sort_by_depth(this.y_world_mc);//sorts everything by z

for(var i = 0, len =this.y_world_mc.length;len > i; i++ )
{
    if(this.y_world_mc[i] != null )
    {

        this.y_world_mc[i].update();

    }

}

```

# Answer
> 2 votes
@rolen123 answer is correct. I wish to introduce a data structure, QuadTree, to the formula.

As you said, sorting a vector of thousands of entities every time you are about to render is slow. But if QuadTree is introduced things change.

Implement QuadTree is not so difficult. Implement a QuadTree to only update entities that are moving is a bit more challenging but can be done, mine does. Most implementations in internet simple destroy the whole QuadTree and recreate it when something moved, that won't work for a fast paced game.

I have a QuadTree.selectRect(x, y, with, height) method that let me obtain all entities inside the specified rectangle, entities have a z property but they are returned in any order. Then I run Quick Sort in the returned array. Then I render the entities starting at the one with the less z value.

Hint: if an entity rectangle does not fit entirely in a node do not make multiple adjacent nodes reference the same entity, move the entity up to a bigger node is better.

Sorting before rendering may sound like overkill but even 3D engines do some kind of sorting and games perform OK.

---
Tags: architecture, component-based, entity-system
---


# Question
Title: Saving an interface instance into a Bundle
All

I've have an interface that allows me to switch between different scenes in my Android game. When the home key is pressed, I am saving all of my states (score, sprite positions etc) into a Bundle. When re-launching, I am restoring all my states and all is OK - however, I can't figure out how to save my 'Scene', thus when I return, it always starts at the default screen which is the 'Main Menu'.

How would I go about saving my 'Scene' (into a Bundle)?

**Code**

```
import android.view.MotionEvent;

public interface Scene{

void render();
void updateLogic();
boolean onTouchEvent(MotionEvent event);

}

```

I assume the interface is the relevant piece of code which is why I've posted that snippet.

I set my scene like so: ('options' is an object of my Options class which extends MainMenu (Another custom class) which, in turn implements the interface 'Scene')

```
 SceneManager.getInstance().setCurrentScene(options);  //Current scene is optionscreen

```

# Answer
> 2 votes
Use a piece of data to denote your scenes. A simple enumeration is the easy way; even a string works just fine in a pinch.

Your interface should be extended to have something like

```
ESceneType getSceneType();

```

which returns the type of that scene (e.g. `ESceneType.MainMenu` or `ESceneType.Pause` or whatever).

You then create a factory object which, using either a data set or a hard-coded switch statement or the like, instantiates scene objects based on id. The low-tech hard-coded version is something like

```
Scene createScene(ESceneType type) {
  switch (type) {
    case ESceneType.MainMenu: return new SceneMainMenu();
    case ESceneType.Pause: return new ScenePause();
    case ESceneType.Play: return new ScenePlay();
    default: throw error;
  }
}

```

Now you can save this scene type value easily, query it from the active `Screne` instance, and recreate a scene from it.

---
Tags: android, interface, scene, game-state
---


# Question
Title: Game physics presentation by Richard Lord, some questions
I been implementing (in XNA) the examples in this physics presentation by Richard Lord where he discusses various integration techniques. Bearing in mind that I am a newcomer to game physics (and physics in general) I have some questions.

15 slides in he shows ActionScript code for a gravity example and an animation showing a bouncing ball. The ball bounces higher and higher until it is out of control. I implemented the same in C# XNA but my ball appeared to be bouncing at a constant height. The same applies to the next example where the ball bounces lower and lower.

After some experimentation I found that if I switched to a fixed timestep and then on the first iteration of `Update()` I set the `time` variable to be equal to elapsed milliseconds (16.6667) I would see the same behaviour. Doing this essentially set the `framerate`, `velocity` and `acceleration` to zero for the first update and introduced errors(?) into the algorithm causing the ball's velocity to increase (or decrease) over time. I think!

My question is, does this make the integration method used poor? Or is it demonstrating that it is poor when used with variable timestep because you can't pass in a valid value for the first lot of calculations? (because you cannot know the framerate in advance).

I will continue my research into physics but can anyone suggest a good method to get my feet wet? I would like to experiment with variable timestep, acceleration that changes over time and probably friction. Would the Time Corrected Verlet be OK for this?

# Answer
A higher timestep introduces more calculation errors, it also depends on the used integration method.

Use constant time verlet integration, not the variable time verlet integration because it doesn't have the advantages of the verlet integration technique. The advantage of the constant time verlet integration technique is that the enery of the system can only decrease, not increase, which is a very good property of a physics simulation.

Here is a comparisation of some techniques:

**Euler integration**

*pro*

* simple
* fast

*contra*

* energy addition/loss easily possible

**Variable time verlet integration**

*pro*

* better energy conservation property than the euler method

*contra*

* introduces calculation errors
* a bit slower to calculate than euler

**Constant time verlet integration**

*pro*

* ball jumps everytime in the same height
* no energy addition possible (but loss)

*contra*

* a bit more compuation requirement than theeuler integration

*how to write code for it*

just let the time actor of the variable time verlet integration at the same value.

---

**Why is energy loss better than the addition of energy over time?**

Because the objects in the gameworld will get eventually to an halt. This is good because the object can be put to sleep and it doesn't need any more calculations for the collision if no object is near it.

It is also better because your gameworld can't 'explode' because everything collides with everything.

---

Pseudocode for the constant time verlet integration with drag

Friction for an object can be simulated with the usage of the Acceleration field of an object

```
PhysicsObject has
   Vector2 OldPosition
   Vector2 CurrentPosition

   // difference between the two is the speed

   float Dragfactor // 0.0f ... 1.0f

   Vector2 Acceleration

// Timestep is the time in seconds of a timestep, can be/is a constant
physics.timestep()
{
   foreach PhysicsObject as IterationPhysicsObject
   {
      Speed = (IterationPhysicsObject.CurrentPosition - IterationPhysicsObject.OldPosition)

      Speed.scale(IterationPhysicsObject.Dragfactor);

      IterationPhysicsObject.OldPosition = IterationPhysicsObject.CurrentPosition;
      IterationPhysicsObject.CurrentPosition = IterationPhysicsObject.CurrentPosition + Speed + IterationPhysicsObject.Acceleration * Timestep * Timestep;

      // reset acceleration
      IterationPhysicsObject.Acceleration = new Vector2(0.0f, 0.0f);
   }
}

```
> 5 votes

# Answer
As mentioned, Euler integration is simple and fast, but not very accurate. It is fairly easy for a stiff system (one requiring large forces to satisfy constraints) to explode in a small number of frames.

Choosing an integration method is highly dependent on what it's for. If you are making a simple particle system, there is no point in having variable-timestep, 4th-order Runge Kutta integration.

Euler is fine but you NEED some damping.

To simulate air resistance, just subtract a small portion of the velocity every frame.

To simulate energy loss due to collision, reduce the component of the velocity in the direction of the normal. For a collison with a horizontal floor, this is just the y component.

```
float GRAVITY = -0.1;
float AIR_RESISTANCE = 0.001;
float RESTITUTION = 0.8;

void update() {
    _vel.y += GRAVITY; // downward force
    _vel -= _vel*AIR_RESISTANCE; // slowing force
    _pos += _vel; // Euler timestep (symplectic)

    if( _pos.y<0.0 ) { // collison with floor
        _pos.y = 0.0; // resolve penetration
        _vel.y *= -RESTITUTION; // bounce up but lose energy
    }
}

```

This is as simple as I can make it. Hope it helps.
> 1 votes

---
Tags: c#, physics
---


# Question
Title: How to prevent "underwater sight" in games
In many games where the player can go underwater, it seems like when you look where the top half of the screen is in the air, and the bottom half the screen is in the water, it's almost like the water doesn't exist and the player is... flying slowly with water sounds?

Is there a logical way to solve this? An algorithm? Doesn't seem like any solution has come up yet since many games still have this. I don't want to make the same mistake.

# Answer
> 16 votes
How about simply not permitting this situation?

I don't know how you are making your game, but if you detect that the view will be partly underwater, you can force the camera to be above water, and only when the entire view would be below water, you can switch to the underwater view.

Depending on how you do it, this could mean that there is an additional delay from the moment where you start diving and when you actually view the scene from beneath the surface. This may actually be a good thing from a UX perspective, so feel free to experiment.

On a separate but related note, I wonder why most underwater scenes are rendered crystal clear... If you ever put your head underwater, you will notice that your eyes are not designed for underwater sight, and therefore everything seems blurry. You'd have to be wearing goggles to actually see clearly underwater.

And additionally, things look (and hear) very different underwater than above water. Water absorbs light much faster than air, so the farther light travels, the less light will arrive at your eyes. This means that the deeper you go, the bluer things look (red light has less energy, and is therefore absorbed more easily than blue light). In fact, at a mere 12 meters underwater, blood looks black, not red.

I've yet to see a non-specialized game that even tries to get underwater environments right...

# Answer
> 7 votes
The problem you are referring to has to do with the camera's view volume clipping through the water plane; typical "underwater effects" are done via full-screen post-process effects, and wouldn't look correct if the view is clipped like this (it would just be the opposite problem).

Even if you do bother to detect the clipping case (potentially difficult) and scissor or clip the otherwise full-screen underwater effect so it only applied to the underwater scene (which is a potential solution you could explore), you'd still have the problem of the actual water plane itself. The transition there would still be a jarring visual artifact. You could detect that plane and blur it heavily; this is probably the closest you can get to a real-world analogy of what the view may be through a partially-submerged camera lens.

Alternatively, prevent this from happening entirely: don't let the camera go below the water plane if the player is "above" the water or above the water plane when the player is "below" the water. This will only really work if you have discrete player operation modes for above/below water, and works best if there is a physical button or other clear and obvious action the player can take to transition between "swimming on the surface" and "swimming below the surface."

Instead of an explicit keystroke to dive, you could interpret forward motion while the camera is pitched down sufficiently to mean "dive." You can then use a graphical effect (splashes or whatever) to hide the camera's transition through the water plane, which it would normally not be able to cross.

We used a technique like this in Guild Wars 2.

# Answer
> 3 votes
Games usually turn on some sort of effects, primarily blue fog, when the camera is underwater. To handle the situation where the near plane clips through the water surface, you can turn on the fog shader when the camera gets close to the water surface, but then add some code to the pixel shader that calculates the point on the near plane corresponding to that pixel, and activates the fog only if that point is under the water surface.

If fog is done as a postprocess, by rendering a full-screen pass, this is especially easy - you just have to calculate the world-space position of each vertex of the full-screen quad or triangle on the near plane (with the inverse view/projection matrix), and interpolate this value down to the pixel shader; then you can check its vertical component and see if it's above or below the water plane.

For bonus points you can use the same technique to add a few-pixels-thick texture to represent the meniscus at the water surface, so it doesn't look so much like a sharp line.

# Answer
> 0 votes
I have two methods; One uses a shader, the other one could use a GUI. Both will start the same:

"Simplified" - `If, Object(Camera) is in 3d Space(Water bounding box/whatever you choose) trigger a shader/GUI.`

Shader will give more realism, you can apply a distortion Like This one

Fog Like Com. Boy stated, can be applied through GUI. Create a photo, with a partial transparency and use it as GUI on the entire camera view. For the photo you supplied I would try a brown colour.

This has been used in a horror game called Drea D Out. If the player approached a ghost, the screen would turn foggy. Although it wasn't used under water it gave a similar effect :)

You can always choose both methods, or make a shader that would change the colour.

```
Taken from : http://sahdan-share.blogspot.com/2013/04/dreadout.html

```

---
Tags: 3d, rendering, terrain-rendering, water
---


title: Kickstarter and 2D smartphone games

text:
# Question
Title: Kickstarter and 2D smartphone games
I am about to launch a Kickstarter project as, after 14 months of full time development on my first iOS game, I run out of money. I developed an iOS game that needs few more months to be ready (the game structure is there but haven't yet worked on balancing the difficulty of the various levels).

**I have a feeling that most of the computer games founded on Kickstarter are for console, PC or Mac and not for smartphones**. The category that many people seem to like is RPG style games.

I have done tons of work over a year and collaborated with musicians and illustrators to get top quality graphics and music. The game looks cool to be an iOS 2D game but, compared to what I've seen on Kickstarter, I feel so little and humbled.

I have searched for smartphone game projects on Kickstarter but haven't found many. I believe that the reason is that people are not keen in backing an APP that is normally sold for 0.99$ **as they perceive is not something big**. Am I the only one having this feeling?

Could anyone please share a list of references to some successfully backed kickstarter smartphone game projects? (In this way the question will not become a "chat" and will fulfill the requirements to be a gamedev question).

Any other article or authoritative answer will be welcome.

# Answer
I've done some research on this topic before and I agree, there are not many crowdfunding projects for mobile games.

Searching Kickstarter itself is not easy. But it can be done and some people make their living by doing exactly this. What you need to look for are mobile gaming blogs and webzines that crawl through kickstarter and post articles named like: Top 10 most exciting iPhone and Android games on Kickstarter or tagged with kickstarter. Second page of Google usually has better results, because the first one is all about kickstarter itself. Also tags and categories on kickstarter homepage can be useful, but as you already said in comments - it is not easy.

When you start looking for the games, soon you will notice a pattern. Most of the really successful games are multiplatform, meant for PCs too. Very successful projects usually include reboots and remakes of geeky games from the past. I concluded this is due to the demographics of gaming kickstarter benefactors - people who are real enthusiasts, regular gamers and people who really liked games in the past and now have enough money to get to play the games they want. Typical kickstarter visitor is a male 25-34 years old with no children, at least colledge degree and above average income \- this is of course kickstarter on average, not just gaming.

Smartphone gamer demographics are very different from those of regular games... I don't think many casual gamers are interested in crowdfunding a game, when they have plethora of simple and entertaining games (for free) in App Store/Play Store.
> 2 votes

---
Tags: game-industry, project-management, console, pc, fund-raising
---


# Question
Title: How to balance this Pokémon simulator metagame by feedback?
This is a Pokémon simulator where you build a team of 6 pokémon and battle with someone. Unfortunately, some Pokémon are stronger than others and only a few of the hundredth species are practical. I'm trying to create a metagame where all of them are competitive. For this, I am tagging a Pokémon with a parameter (level) that changes it's strength and scales up/down depending on the it's performance. That is, if the system detects Mewtwo is overperforming, it should decrease it's level tag until Mewtwo is balanced.

The question is: how can I identify if a Pokémon is causing an unbalance? The data I have is the historic of the battles (player 1, player 2, pokémon list, winner). The most basic solution I can think of is victory/loss counting.

# Answer
> 3 votes
I've played Pokemon competitively in the past, and if your program is very much so inspired by Pokemon, an automatic system will be difficult.

With Pokemon, there are a few things to consider. Damage, Status Effects, Resistance, and just honest player skill. Testing for damage will work fine for Pokemon like Gallade, but not at all for Pokemon like Butterfree. Butterfree doesn't do alot of damage, but the status effects still make it a top choice.

I think the best way to implement a system would be to first rank your players. As Byte56 suggested, an Elo system will work. Then from your top 10% players (10% is just an arbitrary number), look at the frequency of Pokemon used. If you see that Mewtwo is being used in 90% of your top 10% player, you can guess there is a balance issue. From there I would do a break down of which moves tend to be most popular. In competitive Video Game Pokemon, there are tendencies for the top players to use specific builds. If you see that 90% your 10% top players use Mewtwo, and 80% of them use Psychic, then you can assume that Psychic is overpowered. So an automatic damage reduction might help balance.

But then there is the caveat of Psychic can also cause confusion in 10% of it's uses, so maybe a lowering of Psychic's confusion chance might be in order. This will just depend entirely on how complicated you want to make your game, because honestly, Pokemon is a seriously deep game.

With your level slider, I believe your system should work with rating the players, but always remember the case of the Lvl 1 Rattata that defeated the Lvl 100 Dragonite.

;tldr - Rank your players. Look at the top performers for trends. Adjust values accordingly.

# Answer
> 1 votes
You could implement something similar to the Elo rating system, which is used to calculate the relative skill levels of different players. Applying this to the pokémon instead of the players, would allow you to see how they compare to the pokémon to each other and adjust accordingly.

I don't have any idea how pokémon works, but you mention that the battles have a list so I guess there are multiple pokémon per battle? Without more information on how much time each of them played or some metric that tells you their involvement in the battle I guess you would just have to divide the wins/losses evenly among the pokémon in the list when calculating their score.

Do keep in mind that balancing is notoriously difficult. And you'll still need to find some way to factor the player's skills out of the equation.

# Answer
> 0 votes
This is a fairly old post, but I've been wanting to do something similar. My idea was to scale the base stats of each pokemon so they all equal each other. That would make a weak pokemon like Magikarp with only 200 stat points be able to compete with legendaries that have 600+ stat points.

For example, Magikarp has a Base Stat Total (BST) of 200 and the individual stats for HP/ATK/DEF/SATK/SDEF/SPD are 20/10/55/15/20/80. Mewtwo has a BST of 680 and the individual stats are 106/110/90/154/90/130.

If they were both scaled to have 600 BST, for example, Magikarp's stats would be 60/30/165/45/60/240 and Mewtwo's would be 94/97/79/136/79/115. They would both still have unique stats and moves to use, but they'd have the potential to do as much damage.

To scale a stat value, you use simple cross-multiplication: (original stat value) * (scaled BST target) / (original BST) = (scaled stat value). So for Mewtwo's HP of 106 to 94, you do 106 * 600 / 680 = 94.

Anyway, you've probably already made your simulator or abandoned the project, but I thought I'd add my 2 cents. I've been thinking about this awhile, and I haven't been able to find any simulators out there that try to make all the pokemon equal.

---
Tags: mathematics, balance, statistics
---


# Question
Title: Will changing app name in iOS app store affect/reset app ranking?
I want to change the name of my app but was wondering if that would change/affect/reset the ranking it already has. Anyone know?

# Answer
There should be three names of your app:

1. Bundle Identifier - this is the main ID
2. Bundle Display Name - this is displayed in iPhone
3. App Name - this is probably the one in the iTunes/App Store

I believe you can change the App Name during uploading and update (with the updated Bundle Display Name) and if you don't change the Bundle Identifier all reviews and rankings should remain the same. Users will also automatically receive this update. This is most likely dependent on Apple approval after the update.

Hopefully this is still valid with the App Store changes.

---

Also I have seen this many times as a user.
> 4 votes

---
Tags: ios, appstore, ranking
---


title: Manipulating Perlin Noise

text:
# Question
Title: Manipulating Perlin Noise
I've been learning about Procedurally Generated Content lately (in particular, Perlin noise). Perlin noise works great for making things like landscapes, height maps, and stuff like that. But now I am trying to generate structures more like mountain ranges (in 2D, as 3D would be way over my head right now) or underground veins of ores.

I can't manage to manipulate Perlin Noise to do this. Making a cut off point (i.e. using only the tops of the 'mountains' of a heightmap) wouldn't work, because I would get lumps of mountains/veins. Any suggestions?

Thanks,
Numeri

# Answer
> 8 votes
Perlin noise is great for many things - localised terrain, clouds, waves - but when it comes to mountain ranges it's somewhat lacking. The problem is that the output looks like, well, noise. Mountain ranges however are the result of tectonic plates pushing against each other, forming ridges, and so look somewhat like ripples on fabric or paper that's scrunched inwards, albeit very noisy:

**A ridge**

**This is what real mountains look like when you're far enough up**

There's no way a single Perlin noise generator, no matter how well tweaked, will recreate these features. Hence my suggestion to use a multi-phase generator, with something to create those ranges, and Perlin noise to add the fine detail like peaks.

Have a look at libnoise, an open source terrain generation library. It uses a composite generator, which includes one that generates ridges. Here's a sneak peek of what it's capable of:

Now compare this with a typical Perlin noise generator, and you can see how it's much better at resembling mountain ranges. This just looks like blobs to me:

# Answer
> 4 votes
You might want to have a look at Inigo Quilez' website. Especially his article on advanced perlin noise and terrain raymarching could be interesting.

---
Tags: procedural-generation, perlin-noise
---


# Question
Title: What would be the most simple following target and neighbors avoidance algorithm in 2D space on plane?
I have ~20 or more enemies and they need to follow a target and avoid to go on top of themselves. I mean follow a target and avoid to collide with each other. Area, on which they are walking, is just a rectangle plane in 2D space. What would be the most simple and efficient algorithm for this? Thanks.

# Answer
This is frequently referred to as flocking or a boids simulation. It's an algorithm that combines three behaviors to simulate the motion of a group:

**Separation**: steer to avoid crowding local flockmates **Alignment**: steer towards the average heading of local flockmates **Cohesion**: steer to move toward the average position of local flockmates

The combination of those three will create a good approximation of a group moving together. These behaviors are described well in the GDC99 paper Steering Behaviors For Autonomous Characters (Craig W. Reynolds). Additionally there's a few Java demos of flocking and some other steering behaviors in action here. The other behaviors include a path following steering behavior and a follow the leader behavior that can be useful to you for having a group move along a path.
> 11 votes

# Answer
I think you want steering behaviors, specifically Flocking. This enables you to have entities that will flock towards a certain point / target - if you can combine this with Avoidance behaviors you should be able to achieve what you want.
> 0 votes

---
Tags: 2d, algorithm, ai, performance, collision-avoidance
---


# Question
Title: Displaying performance data per engine subsystem
Our game (Android based) traces how long it takes to do the world logic updates, and how long it takes to a render a frame to the device screen.

These traces are collected every frame, and displayed at a constant interval (currently every 1 second).

I've seen games where on-screen data of various engine subsystems is displayed, with the time they consume (either in text) or as horizontal colored bars.

I am wondering how to implement such a feature?

# Answer
You basically time your function calls and then store those timings in some kind of database. You can then add a debug overlay mode to your game and display those timing values.

Niklas Fryholm's wrote a post on the bitsquid engine's development blog which I used as a starting point:

http://bitsquid.blogspot.de/2011/05/monitoring-your-game.html

When you have the basics working most of the further work is identifying what data you want to collect and how you want to display it.

I found looking at screenshots from RAD's Telemetry quite helpful in this regard: http://www.radgametools.com/telemetry.htm
> 2 votes

---
Tags: android, software-engineering, performance, first-person-shooter, debugging
---


# Question
Title: How do I make good guy attacks only hit bad guys and vice versa?
My game has many different type of good guys and many different type of bad guys. They will all be firing projectiles at each other but I don't want any accidental collateral damage to occur for either alignment. So bad guys should not be able to hit/damage other bad guys and good guys should not be able to hit/damage other good guys.

The way I'm thinking of solving this is by making it so that the `Unit` instance (this is javascript, btw), has an `alignment` property that can be either `good` or `bad`. And I'll only let collision happen if the

```
class Attack

    boolean didAttackCollideWithTarget(target)
        return attack.source.alignment != target.alignment and collisionDetected(attack.source, target)

```

This is pseudo-code, of course.

But I'm asking this question because I get the sense that there might be a much more elegant way to design this besides adding yet another property to my `Unit` class.

# Answer
## Collision Filtering

A more robust situation that scales into many layers is to use filtering, which is not the same thing as grouping.

This works best by giving every object 2 bitmasks.

```
Category
Mask

```

And only trigger a collision if the below is true.

```
(filterA.maskBits & filterB.categoryBits) != 0 &&
(filterA.categoryBits & filterB.maskBits) != 0;

```

Its easiest to default the Mask to 0xFFFF which results in it colliding with everything. And default the Category to 0x0001. objects collide with the categories in the others mask will there be a collision.

Another way to think of it is each object has a type and a list of all the types it can collide with. Only when two objects both collide with the types of each other is there a collision. You could have the same behavior having a list of enums instead of a mask but a mask in an order of magnitude faster.

## Scenario you describe

I like to take advantage of enums in this situation.

So say we have.

```
enum Categories {
    GoodGuy =           0x0001,
    BadGuy =            0x0002,
    Bullet =            0x0004,
    GlassWall =         0x0008,
    Lazer =             0x0010,
    All =               0xFFFF
};

```

Bullet shot by a good guy

```
 Category = Bullet
 Mask = BadGuy | GlassWall

```

Good Guys

```
 Category = GoodGuy
 Mask = All

```

Bad Guys

```
 Category = BadGuy
 Mask = All

```

Which results in the below when a Bullet shot by a good guy hits another good guy.

```
(All & GoodGuy) != 0 && <-- Passes
(GoodGuy & (BadGuy | GlassWall)) != 0; <-- This would fail

```

But it will hit bad guys.

```
(All & BadGuy) != 0 && <- Passes
(BadGuy & (BadGuy | GlassWall)) != 0; <-- Passes

```
> 6 votes

# Answer
I had the same problem at my current project (in Java). After a couple tries is solved it by creating four lists. This solution is created in Java and for a 2D Game but should also work, in a similar way, in JavaScript

```
public static main (String [] args)
{
    private List<Bullets> bullets_GoodGuys = new LinkedList <Bullet>(); //List of all bullets fired by good guys
    private List<Bullets> bullets_BadGuys  = new LinkedList <Bullet>(); //List of all bullets fired by bad guys
    private List<Guys> goodGuys  = new LinkedList <Guys>(); //List of all good guys
    private List<Guys> badGuys  = new LinkedList <Guys>();  //List of all good guys

    init();
    ...
    while(game_is_running)
    {
        ...
        for(int i=0;i>=goodGuys.length;i++)
        {
            for(int j=0;j>=bullets_BadGuys.length;i++)
            {
                if(goodGuys.get(i).getBounding().interacts(bullets_BadGuys.get(i).getBounding()))
                {// If a good guy was hit by a bullet from a bad guy
                    goodGuys.get(i).getDamage();
                    bullets_BadGuys.remove((bullets_BadGuys.get(i));
         }   }   }
       for(...) //same for the bad guys
       {...}
}

```

pseudo-code

```
class Guys
{
   private float xkoordinate;
   private float ykoordinate;
   private BufferedImage look;
   private Rectangle bounding = new Rectangle(xkoordinate,ykoordinate,look.getWith(),look.getHight())
   ...
}

```

pseudo-code, same for the class Bullets

This might not be the best or fastest solution but it will help you in the moment. I’m sorry that I cannot give you a solution in JavaScript but I hope I could help you

By the way my English isn’t the best but I hope you could follow my explanation
> 2 votes

---
Tags: collision-detection, architecture, javascript, game-mechanics, projectile-physics
---


title: Geometry Shader : points + Triangles

text:
# Question
Title: Geometry Shader : points + Triangles
I have different Shaders and for each Shader a instance of the `ShaderClass` class, which initializes the Shaders, Renders the Shaders, etc.

I use most of the `Shaderclass`es without Geometry Shader, but in one Shader Class i also use a Geometry Shader.

The problem is, that when I render one object with the `Shaderclass` that uses the Geometry shader, all other object are rendered with the same geometry that I create in the Geometry Shader. Can you help me?

Is it possible that I have to use a Geometry Shader for each object, when I use one for one object?

I use DirectX 11 with C++.

# Answer
After using the geometry shader, you'll need to do `GSSetShader(NULL, NULL, 0)` to disable it. Otherwise the geometry shader will remain active during all rendering afterward.

If you use DX11 tessellation shaders (hull & domain shaders) you'll similarly need to set them to NULL when you don't want tessellation anymore.
> 3 votes

---
Tags: c++, directx11
---