title: XNA Block engine Block update problem

text:
# Question
Title: XNA Block engine Block update problem
I'm pretty new to programming games (this is my 1st program in XNA), and I ran into a problem. I want to make a block engine, and this far I have a chunk, and I can move around it with the camera while random blocks are constantly removed from the chunk. My problem is that every time I'm rebuilding the chunk: clearing the vertexlist than adding the required sides of the cubes to it (I only add sides if the neighbor is inactive), the game freezes up for a short time. My chunk only have 800-1200 triangles this way so it shouldn't really tax the computer (FPS is between 50-60), I guess the rebuilding delays the camera movement. I will post my code, could anybody give me some advice on it? (for example would it help if I would make a separate thread for rebuilding the chunk? )

I won't add the Block class (it has a bool if its active or not), and the Dev\_Messages class (FPS and triangle display), but the other 3 classes might be relevant.

Thanks in advance!

```
namespace Chunk
{

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

        Camera camera;
        Dev_Messages dev;

        Chunk chunk;

        //TESTING
        bool animate = true;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            camera = new Camera(this, new Vector3(0, 0, 40), Vector3.Zero, Vector3.Up);
            chunk = new Chunk(GraphicsDevice);
            dev = new Dev_Messages(this);

            Components.Add(camera);

            base.Initialize();
        }

        protected override void LoadContent()
        {
        }

        protected override void UnloadContent()
        {

        }

        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            if (animate == true) chunk.Update(gameTime.ElapsedGameTime.TotalMilliseconds);

            if (Keyboard.GetState().IsKeyDown(Keys.D1)) animate = false;
            if (Keyboard.GetState().IsKeyDown(Keys.D2)) animate = true;

            dev.Update(gameTime);

            base.Update(gameTime);
        }

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

            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            GraphicsDevice.BlendState = BlendState.Opaque;

            chunk.Draw(camera);

            dev.Draw(chunk.getTriangleCount());

            base.Draw(gameTime);
        }
    }
}

```

**CHUNK CLASS:**

```
namespace Chunk
{
    class Chunk
    {
        private const int DIM_X = 8;
        private const int DIM_Y = 8;
        private const int DIM_Z = 8;

        Block[,,] block = new Block [DIM_X, DIM_Y, DIM_Z];

        Random random = new Random();
        int rnd1, rnd2, rnd3;
        double TIME = 0;

        private float R = 1;
        private Vector3 POS = new Vector3(0,0,0);

        private VertexBuffer vertexbuffer;
        private List<VertexPositionColor> vertexlist;
        private GraphicsDevice device;
        private BasicEffect effect;

        public Chunk(GraphicsDevice device_) {
            device = device_;
            effect = new BasicEffect(device);
            vertexlist = new List<VertexPositionColor>();

            for (int x = 0; x < DIM_X; x++) {
                for (int y = 0; y < DIM_Y; y++) {
                    for (int z = 0; z < DIM_Z; z++) {
                        block[x, y, z] = new Block(true);
                    }
                }
            }

            Build();
        }

        public int getTriangleCount() {
            return vertexbuffer.VertexCount / 3;
        }

        public void Build() {
            Color c1 = new Color(155, 255, 155);
            Color c2 = new Color(0, 50, 0);
            Color c3 = new Color(0, 150, 0);

            for (int x = 0; x < DIM_X; x++) {
                for (int y = 0; y < DIM_Y; y++) {
                    for (int z = 0; z < DIM_Z; z++) {
                        if (block[x, y, z].IsActive()) {

                            POS = new Vector3(2 * x + 1, 2 * y + 1, -2 * z - 1);

                            //FRONT
                            if ((z > 0) && (block[x, y, z-1].IsActive() == false) || z == 0)
                            {
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X - R, POS.Y + R, POS.Z + R), c1));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X + R, POS.Y + R, POS.Z + R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X - R, POS.Y - R, POS.Z + R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X - R, POS.Y - R, POS.Z + R), c2)); //verts[2]
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X + R, POS.Y + R, POS.Z + R), c2));//verts[1]
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X + R, POS.Y - R, POS.Z + R), c3));
                            }

                            //BACK
                            if ((z < DIM_Z - 1) && (block[x, y, z + 1].IsActive() == false) || z == DIM_Z - 1)
                            {
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X + R, POS.Y + R, POS.Z - R), c1));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X - R, POS.Y + R, POS.Z - R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X + R, POS.Y - R, POS.Z - R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X + R, POS.Y - R, POS.Z - R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X - R, POS.Y + R, POS.Z - R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X - R, POS.Y - R, POS.Z - R), c3));
                            }

                            //TOP
                            if ((y < DIM_Y-1) && (block[x, y+1, z].IsActive() == false) || y == DIM_Y-1)
                            {
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X - R, POS.Y + R, POS.Z - R), c3));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X + R, POS.Y + R, POS.Z - R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X - R, POS.Y + R, POS.Z + R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X - R, POS.Y + R, POS.Z + R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X + R, POS.Y + R, POS.Z - R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X + R, POS.Y + R, POS.Z + R), c1));
                            }

                            //BOTTOM
                            if ((y > 0) && (block[x, y - 1, z].IsActive() == false) || y == 0)
                            {
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X + R, POS.Y - R, POS.Z - R), c1));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X - R, POS.Y - R, POS.Z - R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X + R, POS.Y - R, POS.Z + R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X + R, POS.Y - R, POS.Z + R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X - R, POS.Y - R, POS.Z - R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X - R, POS.Y - R, POS.Z + R), c3));
                            }

                            //LEFT
                            if ((x > 0) && (block[x-1, y, z].IsActive() == false) || x == 0)
                            {
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X - R, POS.Y + R, POS.Z - R), c1));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X - R, POS.Y + R, POS.Z + R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X - R, POS.Y - R, POS.Z - R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X - R, POS.Y - R, POS.Z - R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X - R, POS.Y + R, POS.Z + R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X - R, POS.Y - R, POS.Z + R), c3));
                            }

                            //RIGHT
                            if ((x < DIM_X-1) && (block[x + 1, y, z].IsActive() == false) || x == DIM_X-1)
                            {
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X + R, POS.Y + R, POS.Z + R), c1));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X + R, POS.Y + R, POS.Z - R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X + R, POS.Y - R, POS.Z + R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X + R, POS.Y - R, POS.Z + R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X + R, POS.Y + R, POS.Z - R), c2));
                                vertexlist.Add(new VertexPositionColor(new Vector3(POS.X + R, POS.Y - R, POS.Z - R), c3));
                            }

                            vertexbuffer = new VertexBuffer(device, typeof(VertexPositionColor), vertexlist.Count, BufferUsage.None);
                            vertexbuffer.SetData(vertexlist.ToArray());
                        }
                    }
                }
            }
        }

        public void Update(double time) {
            TIME += time;
            if (TIME > 1000)
            {
                rnd1 = random.Next(0, DIM_X);
                rnd2 = random.Next(0, DIM_Y);
                rnd3 = random.Next(0, DIM_Z);

                if (block[rnd1, rnd2, rnd3].IsActive() == true)
                {
                    block[rnd1, rnd2, rnd3].setActive(false);

                    vertexlist.Clear();
                    TIME = 0;
                    Build();
                }
            }
        }

        public void Draw(Camera camera) {

            effect.World = Matrix.Identity;
            effect.View = camera.view;
            effect.Projection = camera.projection;
            effect.VertexColorEnabled = true;

            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();

                device.SetVertexBuffer(vertexbuffer);
                device.DrawPrimitives(PrimitiveType.TriangleList, 0, vertexbuffer.VertexCount / 3);
            }
        }

    }
}

```

**CAMERA CLASS:**

```
namespace Chunk
{

    public class Camera : Microsoft.Xna.Framework.GameComponent
    {
        public Matrix view {get; protected set;}
        public Matrix projection {get; protected set;}
        public Vector3 cameraPosition { get; protected set;}

        MouseState originalMouseState;

        Vector3 cameraDirection;
        Vector3 cameraUp;

        float leftrightRot = 0;
        float updownRot = 0;
        const float rotationSpeed = 0.003f;

        public Camera(Game game, Vector3 pos, Vector3 target, Vector3 up)
            : base(game)
        {
            //Build camera view matrix
            cameraPosition = pos;
            cameraDirection = target - pos;
            cameraDirection.Normalize();
            cameraUp = up;

            //projection matrix (FOV, Aspect ratio, near/far clipping)
            projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
            (float)Game.Window.ClientBounds.Width / (float)Game.Window.ClientBounds.Height, 1, 300);
        }

        private void UpdateViewMatrix()
        {
            Matrix cameraRotation = Matrix.CreateRotationX(updownRot) * Matrix.CreateRotationY(leftrightRot);

            Vector3 cameraOriginalTarget = new Vector3(0, 0, -1);
            Vector3 cameraRotatedTarget = Vector3.Transform(cameraOriginalTarget, cameraRotation);
            Vector3 cameraFinalTarget = cameraPosition + cameraRotatedTarget;

            Vector3 cameraOriginalUpVector = new Vector3(0, 1, 0);
            Vector3 cameraRotatedUpVector = Vector3.Transform(cameraOriginalUpVector, cameraRotation);

            view = Matrix.CreateLookAt(cameraPosition, cameraFinalTarget, cameraRotatedUpVector);
        }

        public override void Initialize()
        {
            UpdateViewMatrix();

            // Set mouse position and do initial get state
            Mouse.SetPosition(Game.Window.ClientBounds.Width / 2, Game.Window.ClientBounds.Height / 2);
            originalMouseState = Mouse.GetState();

            base.Initialize();
        }

        public override void Update(GameTime gameTime)
        {
            Vector3 moveVector = new Vector3(0, 0, 0);

            // Move forward/backward
            if (Keyboard.GetState( ).IsKeyDown(Keys.W))
                moveVector += new Vector3(0, 0, -1);
            if (Keyboard.GetState( ).IsKeyDown(Keys.S))
                moveVector += new Vector3(0, 0, 1);

            // Move side to side
            if (Keyboard.GetState( ).IsKeyDown(Keys.A))
                moveVector += new Vector3(-1, 0, 0);
            if (Keyboard.GetState( ).IsKeyDown(Keys.D))
                moveVector += new Vector3(1, 0, 0);

            // Ascend / Descend
            if (Keyboard.GetState().IsKeyDown(Keys.Space))
                cameraPosition += new Vector3(0, 1, 0);
            if (Keyboard.GetState().IsKeyDown(Keys.LeftControl))
                cameraPosition += new Vector3(0, -1, 0);

            float TimeDiff = (float)gameTime.ElapsedGameTime.TotalMilliseconds / 10f;

            //Move
            AddToCameraPosition(moveVector * TimeDiff);

            //Mouse Look
            MouseState currentMouseState = Mouse.GetState();
            if (currentMouseState != originalMouseState) {
                float xDifference = currentMouseState.X - originalMouseState.X;
                float yDifference = currentMouseState.Y - originalMouseState.Y;
                leftrightRot -= rotationSpeed * xDifference * TimeDiff;
                updownRot -= rotationSpeed * yDifference * TimeDiff;
                Mouse.SetPosition(Game.Window.ClientBounds.Width / 2, Game.Window.ClientBounds.Height / 2);
            }

            UpdateViewMatrix();

            base.Update(gameTime);
        }

        private void AddToCameraPosition(Vector3 vectorToAdd) {
            Matrix cameraRotation = Matrix.CreateRotationX(updownRot) * Matrix.CreateRotationY(leftrightRot);
            Vector3 rotatedVector = Vector3.Transform(vectorToAdd, cameraRotation);
            cameraPosition += rotatedVector;
            UpdateViewMatrix();
        }

    }
}

```

# Answer
I think you recreate the vertexbuffer after each new block in the three for-loops in the Build() method. Just try to recreate the vertexbuffer only one time after this loops ;)
> 0 votes

# Answer
You might want to redesign the build method wherein you're not instancing new objects. One reason for the delays, is probably the amount of new objects you are recreating every time during the chunk update.

I experienced this when coding Techcraft. Feel free to look through earlier commits of the code there. http://techcraft.codeplex.com
> 3 votes

---
Tags: xna
---


# Question
Title: How to make an articulated mob in Minecraft?
I am attempting to make a sea serpent, and I want to know how to make it be able to turn in any place, or at each 'segment', somewhat like the snakes in mocreatures. I know how to make mobs in general, rendering and modelling, as well as AI, so it's just this single element.

I am using Forge if that helps.

# Answer
I would look into the model class, particularly the Ender Dragon model class, to see how the wings are animated.

If you want a good place to start, looking at the chest model class can help. It shows the barebone basics of how a multi-boned/part mob works, with each 'box' having a different rotation around whatever axis, allowing you to rotate it somewhat like this:

```
public ModelRenderer segment;

public ModelSnake() {
    this.segment.addBox(0.0F, -5.0F, -14.0F, 14, 5, 14, 0.0F);
    this.segment.rotationPointX = 1.0F;
    this.segment.rotationPointY = 7.0F;
    this.segment.rotationPointZ = 15.0F;
}

public void renderAll() {
    this.segment.render(0.0625F);
}

```
> 2 votes

---
Tags: models, minecraft-modding, modding
---


title: moving from XNA to LWJGL

text:
# Question
Title: moving from XNA to LWJGL
Hi StackOverflow people!

I would like to know how easy it could be to move from XNA to using LWJGL.

Just wanted to throw this out there because of the rumors that MS is shutting down XNA and having an interest in checking out gamedeveloping in Java.

Thanks in advance for your interest.

# Answer
> 3 votes
Well, how easy it is will vary from person to person. I can speak from experience, as I made the same switch (well, kind of) a couple of months ago (due to the same rumors).

I decided to learn how to use the OpenTK library (definitely worth checking out if love C# as much as I do), but that kind of has the same learning curve as LWJGL (I have created some applications using that as well, but I always struggle with Java).

Now first you need to know a couple of differences between the two frameworks:

* XNA uses Direct3D, LWJGL uses OpenGL
* XNA is a "proper" framework, LWJGL is a wrapper

Now I have not chosen the last term to debase LWJGL, I just couldn't find a better term for it.

The first thing doesn't mean a lot, since XNA is an abstraction layer, and you don't have to use Direct3D directly yourself, XNA will take care of that. With LWJGL, however, you will have to have some knowledge about OpenGL, since you will be directly interacting with it.

This will mean that you will have to implement more things for yourself, so creating an abstraction layer yourself is probably a good idea (LWJGL doesn't have the `SpriteBatch` class, for example).

Apart from that, it won't be that difficult. Interacting with graphical hardware works in a similar fashion for all frameworks, so if you already know the basics of vertex buffers and shaders, you'll probably be able to master LWJGL in a couple of months of off and on coding.

# Answer
> 0 votes
Java lacks some features(useful for gamedev) that C# has:

1. Operator overloading: In XNA, you can treat vectors like numbers: Position += Velocity. In Java, you have to use methods: Velocity.add(Position), or store vectors as two floats.
2. Value types: In XNA, you can have Vertex struct. Array of these can be send directly to OpenGL. In Java, you have to use array of primitives. Also, value types are useful for optimization: they don't need Garbage Collector, need less memory, and may be sometimes faster because of the CPU cache.

---
Tags: xna, c#, java, lwjgl
---


# Question
Title: Coordinates different between Tiled editor and my game
So I have been using Tiled map editor to create my map for my game. I'm using Libgdx to load and draw the map.

The problem is that the coordinate from objects placed in tiled do not seem to be the same when they are using in my game. It seems to be just the y value, as I have tried a few different positions and the x value seems to be okay.

I think it may be because Libgdx coordinate systems starts in the bottom left instead of the top left, but I'm not sure. And I'm not sure how to get around it.

In Tiled:

In game:

The black square is being drawn at the x and y values grabbed from the object.

I get the values from this function once the map loads:

```
    public Vector2 getStartingPosition()
{
    for (TiledObjectGroup group : map.objectGroups) {
        for (TiledObject object : group.objects) {
            if ("playerSpawn".equals(object.name))
                return new Vector2(object.x, object.y);
        }
    }

    //Was not found, return default spawn
    return new Vector2(0,0);
}

```

# Answer
Thanks for everyones help, but I have found the answer on another forum. I thought I would post the answer here for anyone else who may have issue:

You need to set the y value of the object to:

```
y = mapHeight - tilesize - y;

```
> 0 votes

---
Tags: java, libgdx
---


# Question
Title: Lerp vs Vector math: one better than the other?
In Unity3D (all versions, I believe), there is a static function for the Vector3D class called "lerp". It interpolates a point between two points a point, based off a provided percentage related to the desired distance between the two.

Alternatively, I could just get the direction I want to go as a point, subtract it from my current position, Normalize() the resulting vector, then multiply that times a speed value.

So:

* Is one way faster than another?

and

* Is there a third better/faster/easier/more efficient way I don't know about?

Thanks.

# Answer
> 4 votes
Velocity and lerping are for different purposes. Lerping is great when you *know* you're going to end at the target in a given time; it's good for many UI animations, for example.

Use velocity when what you have is the speed of movement and the *intent* to get to a target at that constant speed. Using the velocity let's you smoothly change directions mid-course, slow down or speed up, etc. I had a place I was lerping vectors and changed to steering (velocty/force) because then I could make objects twist and "dodge" each other if they crossed paths.

In general, use lerp for static animations, use velocity (or full physics) for in-game character/object movement.

# Answer
> 1 votes
In the two situations you give, the former will always go whatever percent you enter in regardless of distance and in the second you'll always go the distance (speed * time) you enter in regardless of end goal distance.

Calculating a speed and multiplying by the normalized vector will give you a consistent speed of travel toward the destination at the cost of normalizing (which uses sqrt). This is a pretty straightforward way of doing what you want and has the advantage of making it easier to store current momentum for if the target position changes.

Using Lerp will allow you to travel a percent distance between the two points very easily, but it will not only be dependent on the end point, it will also vary behavior on framerate if you do so repeatedly while updating the source position and leaving the destination. This is not an issue if you only update the percent value over time like you mention in your comment while leaving the start and end points the same. That being said you can do an extremely cheap elastic band effect by giving Lerp a fixed percentage and moving the start point to the current.

Overall they are two different tools with different purposes that *can* be used to the same effect (as per your example). While Lerp is going to be the faster between the two, the actual effect probably won't be felt unless you're doing it a lot (for instance, if you were doing it for every particle in a very busy particle system). To see if the speed difference matters for your purposes: try it, measure, then see if it's enough actively concern you.

As to the last part of your question, take a look at Vector3.MoveTowards. I'm pretty sure it's doing basically what you describe in your first example behind the scenes, but it's set up in a fashion similar to Lerp with the third piece being a distance instead of a percentage.

# Answer
> 0 votes
For velocity, you probably need directional vector (normalization). With lerp, velocity would depend on distance between two points (maybe you want that).

Normalize may be slower because it performs sqrt.

---
Tags: unity, vector
---


title: Bezier curve not drawn correctly

text:
# Question
Title: Bezier curve not drawn correctly
I'm trying to draw a bezier curve using 3 points. If I use the quadratic form:

I get this result:

And I believe it's correct.

Now since I need to draw it with a variable number of points, I'm trying to apply the explicit definition:

This is the code that implements it:

```
typedef struct Point2D
{
    GLfloat x;
    GLfloat y;
    Point2D operator+(GLfloat c) const
    {
        return {x+c, y+c};
    }
    Point2D operator+ (const Point2D& other) const
    {
        return {x+other.x, y+other.y};
    }
    void operator+= (GLfloat c)
    {
        y+=c;
        x+=c;
    }
    void operator+= (const Point2D& other)
    {
        x+= other.x;
        y+= other.y;
    }
    Point2D operator* (GLfloat factor) const
    {
        return {x*factor, y*factor};
    }
    void operator*= (GLfloat factor)
    {
        x*=factor;
        y*= factor;
    }
}Point2D;

Point2D bezier(const vector<Point2D>& points, GLfloat u) // u is t
{
    Point2D point;
    unsigned int n= points.size();
    vector<int> factorials(n);
    // For efficiency, I put all factorials in an array instead
    // of recalculating them each time.
    GLfloat c1= pow(1.0-u,n-2);
    // This is (1-t)^(n-1)
    GLfloat c2= 1.0;
    // This is t^i , I'll progressively multiply it for u.
    factorials[0]=1;
    for(unsigned int i=1; i<n;i++)
    {
        factorials[i]= factorials[i-1]*i;
    }
    point= points[0] * (GLfloat)(n-1) * c1; // This is the first point
    for(unsigned int i=1; i<n; i++)
    {
        c2*= u;
        GLfloat bCoeff= factorials[n-1]/(factorials[i]*factorials[n-2]);
            // bCoeff is the binomial coefficient: n! / ( i! * (n-1)! )
        point+= points[i] * bCoeff * c1 * c2;
    }
    return point;
}

void display()
{
    glClearColor(0.75,0.75,0.75,1.0);
    glClear(GL_COLOR_BUFFER_BIT);

    glColor3f(1.0,0.0,0.0);
    glBegin(GL_POINTS);
    vector<Point2D> points{Point2D{200,200}, Point2D{400,400}, Point2D{600,200} };
    for(GLfloat u=0.0; u<=1.0; u+=1.0e-4)
    {
        Point2D point;
        point= bezier(points,u);
        glVertex2f(point.x,point.y); // For now I use the immediate mode
                                         // I'll put it in a vbo.
    }
    glEnd();

    glutSwapBuffers();
}

```

Unfortunately this is the result that I get:

Which I believe is incorrect. I guess I'm not applying correctly the explicit definition, but I don't know where's the mistake, I would like to know what I'm doing wrong.

# Answer
> 7 votes
It is indeed wrong for at least two reasons:

* you never update `c1`.
* you use `n! / ( i! * (n-1)!` instead of `n! / ( i! * (n-i)!`.

This means you'll need to reorganise your code. You might try something like this:

```
unsigned int n = points.size();

vector<float> v;
for (unsigned i = 0; i < n; i++)
    v.push_back(1.f);

/* (un1) is t^i, (un2) is (1-t)^i */
float un1 = 1.f, un2 = 1.f, inv_fact = 1.f;

/* At the end of the loop, we are still missing the
 * "n!" multiplication, but we can do it at the very
 * end instead. */
for (unsigned i = 0; i < n; i++)
{
    v[i] *= un1 * inv_fact;
    un1 *= u;
    v[n - 1 - i] *= un2 * inv_fact;
    un2 *= (1.f - u);
    if (i != 0 && i != n - 1) inv_fact /= i;
}

Point2D point{0,0};
for (unsigned i = 0; i < n; i++)
    point += v[i] * points[i];

return (1.f / inv_fact) * point;

```

# Answer
> 3 votes
You could also use my recursive approach to n-order bezier curves. This method can also be adapted for use with integers if needed.

```
class bezier{
    std::vector<Point2D> points;
public:
    bezier();
    void PushPoint2D( Point2D point );
    Point2D GetPoint( double time );
};

bezier::bezier(){}
void bezier::PushPoint2D( Point2D point ){
    points.push_back(point);
}
Point2D bezier::GetPoint( double time ){
    Point2D p;
    if( points.size() == 1 ) return points[0];
    if( points.size() == 0 ) return p;

    bezier b;
    for( int i = 0; i < points.size()-1; ++i ){
        p.x = ( points[i+1].x - points[i].x ) * time + points[i].x;
        p.y = ( points[i+1].y - points[i].y ) * time + points[i].y;
        if( points.size() <= 2 ) return p;
        b.PushPoint2D(p);
    }
    return b.GetPoint( time );
}

```

---
Tags: c++, opengl, mathematics, beziers
---


# Question
Title: Need physics algorithm for modeling ceiling collapse in voxel-based game
I'm looking for algorithms on how to model the physics of cave-ins/collapses for a game idea I am working on. The game allows the player to extensively mine 3D voxel-based asteroids, and I want areas that are insufficiently supported to collapse under their own weight. Making the problem even more challenging, gravity will be non-uniform (the direction it pulls will depend on where a given voxel is in relation to the asteroid's center of mass), and the number of voxels in the asteroid will be too large to model them all individually (I am using a sparse voxel octree to model the asteroid).

Hopefully, someone will be able to provide links to articles discussing suitable algorithms, or can provide ideas on how to solve the problem. If you need more details, please ask.

Edit 1: It does not need to be very accurate, I'm looking for something that would be a reasonable approximation for a Minecraft or Dwarf Fortress style game. I am mostly interested in how to determine where sections should break off when blocks are added or removed, moving the bodies after they break isn't part of this issue.

Edit 2: My initial idea was to calculate the force on each block then iteratively distribute the forces amongst neighbors. However, this would require an entry for each block, while only blocks on the surface have entries in the data structure. Modeling all blocks on the scale I want would likely be prohibitive - I would like to have bodies of at least 10,000,000 voxels, of which 200,000 will be on the surface and need to be stored.

# Answer
> 1 votes
You are making an artistic decision; that's the right way to approach it. You have a non-realistic medium, so you are picking and choosing what physics you want to apply anyway.

But this exercise is not difficult. Structural engineers pick and choose what kind of physics they care about enough to include them in their calculation of...whether or not a ceiling will collapse.

You could probably figure out enough math by extrapolating one-dimensions beam stress into two dimensions. There you can determine where stress exceeds the shear limit. I don't mean for this link to be smarmy, it's just a good google query for you: http://lmgtfy.com/?q=beam+stress

# Answer
> 1 votes
You note that you only represent blocks which are on the surface — I assume this includes ceilings. But we can assume that interior things are well-supported, i.e. not themselves the source of a collapse, and so they don't need to be considered!

Here is my idea for a model — I haven't tested it, and I'm sure a structural engineer could find plenty to criticize. It is designed to be efficient and use little data, but has the disadvantage of not representing horizontal forces (so a column will never buckle).

---

For each surface block, store a number (not a vector) which I'll call 'displacement'. This represents the infinitesimal displacement *downward* from an unloaded state of the same structure. It is intended only to manage breaking, and need not be graphically represented.

Whenever a block is disturbed, iteratively update these values (i.e. update neighbors and their neighbors until values stop changing much), applying two kinds of 'forces':

1. For each attached neighbor, a linear spring force based on the difference between this block's displacement and its neighbor's displacement.
2. A gravitational force, scaled by the total mass of this block *and every **interior** block directly above (opposite to gravity) this block* (e.g. count how many solid voxels a ray cast upward traverses before hitting an upper surface; apply a 'cone' correction if you're feeling fancy).

(Note that these are not actual *forces*, because this model does not include velocity. If I'm not confused, this should basically work as if the system is extremely damped.)

---

If the difference in displacement values between two neighbors becomes greater than a threshold, consider them to have broken apart — no longer affecting each other. (Depending on the material, the threshold should likely be relative to the direction of gravity; for example, for neighbors which are oriented (mostly) vertically, if the upper block has a higher displacement, they are under compression, whereas if the lower block has a higher displacement, that is tension.)

If the displacement of a group of blocks is constantly increasing, then that group is unsupported and should start actually visibly falling, which I recommend handling with a regular physics engine (or adjacent-voxel movement), independently of this system. I leave it to you to figure out how to detect that complete group.

# Answer
> 0 votes
Complex physics simulations that are based in situations other than those here on earth tend to require specialized implementations. Many physics simulations are able to be done efficiently due to estimations, and assumptions that are made about the context they will be simulating in. Unless you are writing the entire physics framework yourself, you may want to consider using something like PhysX, or bullet to provide rigid body simulation, and with clever use of constraints and restrictions you can create the illusion you want. The type of situation you refer to though isn't something you can simply achieve by implementing a single algorithm, it is a larger collection of physics principles working together.

---
Tags: physics, voxels
---


title: Resource transportation network

text:
# Question
Title: Resource transportation network
I've been writing a game in my free time, and I'm planning to add a transportation network based on a buildings demands and production. However, I'm not sure how to manage this efficiently, and most importantly with limited CPU time.

The two key issues are, how do I pair producers and consumers efficiently, and how do I route vehicles between them?

I have A\* working for path finding now, but how do I alter this to include the congestion that will occur from many transports? Perhaps as each vehicle is assigned to a road, that road's cost increases some given value?

An open source project that seems to have similar features is OpenTTD. They define the problem as a Multi-commodity flow problem, but don't give many more details. The paper that describes their algorithm is no longer linked unfortunately, and I feel it may be a bit complex.

# Answer
> 5 votes
### Short answer:

*Don't!*

### Longer answer:

OK, you are trying to compute complex path-planning, for multiple suppliers and demands. This is presumably going to involve some kind of peon/slave or worker/robot unit. However, in the same breath, you say you've got *limited CPU resources*.

I'd suggest you take a note from Shamus Young and figure out what you actually want to simulate in your game, and what can be safely faked. Remember, as Shamus puts it, *in videogame it doesn’t need to be right, it just needs to look right* \[sic\]

If this is a non-violent city simulation game, I'd guess that although players may find it cool to look at the little transports for a little bit, they have other, more important things to concentrate on, which affect gameplay. In that case, you'd be well on your way if you just faked something that looked kind-of OK. For example, if I recall correctly, *X-COM: Apocalypse* had actual, factual path-planning for the transports which the player controlled. i.e. Their base-to-mission taxis for the little soldiers. However, the little civilian taxis, buses, and ambulances, which scurried around on the main map, did so without any real path planning. If you zoomed all the way in, and got the camera angle *just so*, you'd see that they spawned behind buildings, so that they weren't normally visible spawning, and they disappeared behind other buildings, so that they could just travel in straight lines, and not use up precious path-planning CPU time. To further fake it looking cool, they spawned more ambulances and fire trucks beside buildings which were on fire, and less taxis in those vicinities. *So cool.*

However, if the transports are indeed a central, or strategic part of your gameplay, then by all means, add proper pathing for them. The peons in Warcraft, or any number of other strategy games come to mind. If they were faked only, players could not attack enemy transports and defend their own.

You asked if you could have a cost associated with congested roads, to avoid pathing many units over them. This would probably yield good results, and as far as I know, A\* and other search algorithms already have costs associated for each edge in your graph/map you're pathing through. The only thing that remains would be to increase the cost of an edge/node/whatever when a unit passes through it, or has a path that travels through it. The trick would be that its cost should be somewhat time-sensitive, so that it's not overly decongesting a road, when it doesn't need to be. For example, if transports A, B, and C all use road X, but ten seconds apart from each other, then they can all safely use it. Calculating the time at which any road/node/thing is occupied by a transport may be problematic, depending on how your pathing algorithms work.

Good luck!

---
Tags: algorithm, resource-management
---


title: Tile-based maps in AS3

text:
# Question
Title: Tile-based maps in AS3
I want to make a tile-based platformer in AS3.

I want my game to read an external maps file (in xml or json or somethimg similar) to draw a tile-based map.

I've seen loads of tutorials for this in AS2 and other languages, and the few I've found in AS3 are either incomplete or filled with extra unnecessary features. I just want to be able to draw a basic map from sprites in Flash.

Any links or information to point me in the right direction would be appreciated.

# Answer
> 1 votes
Leading library about isometric tile-system: as3isolib.

This is a really powerful tool. The best side of this library, is that you don't have to waste weeks on it, it has only a few simple functions, it is highly optimized and as you can see huge projects use this library.

There's a great tutorial on as3isolib on gotoAndLearn: Part 1, Part 2.

# Answer
> 1 votes
A while ago I shared the AS3 code (+sample project) for a TMX parser on my blog: http://blog.pixelpracht.net/?p=59

TMX is the map format used by the Tiled Map Editor which imho is one of the best engine-independant editors for tile based maps.

# Answer
> 1 votes
FlashPunk supports that, you can even import a map made with Ogmo Editor.

# Answer
> 1 votes
Various Flash game frameworks have this sort of functionality built in. The gist:

1) Load your map data. Lookup how to load XML/JSON in Flash.

2) Loop through the data in order to figure out where to place tiles.

2b) While looping through the data, instantiate the appropriate images and place them at the coordinates defined in the data.

Pseudocode:

```
var tileMap:Object = loadedJSON;
for each (var tileData:Object in tileMap) {
  var tile:MovieClip = new MovieClip from tileData.clip;
  tile.x = tileData.x;
  tile.y = tileData.y;
  addChild(tile);
}

```

(yes I know `new MovieClip from tileData.clip` isn't valid code. I said this is pseudocode; figure out how to instantiate MovieClips)

---
Tags: flash, actionscript-3, tiles, platformer
---


# Question
Title: Apply bone tranforms when importing FBX in XNA
Preconditions: I have some models, that does only contain some meshes and one texture. There is no animation within the model. An example: a model of a table.

I want to draw the Model with a custom effect, so I have to swap the effect after loading the model. In order to draw them correctly, I have to apply the bone transformation manually on each draw for each mesh and effect as can be seen here. So there are two questions:

1. Is there a option during import that allows my to apply the bone transformation on all vertices, so that during draw call I should not have to do this?
2. Is there a option during import that merges all vertices into a Vertex- and IndexBuffer, that allows me to draw the whole model with just one call?

I'm pretty sure that the build-in "Autodesk FBX - XNA Framework" does not support this features, but maybe there is an other imported available or an other possibility I missed.

The aim is to speed up rendering a little bit especially by using instancing. So having one VertexBuffer to draw at one time would be pretty nice.

# Answer
> 1 votes
Your first question can only be solved with a custom model processor. You could use something like this:

```
[ContentProcessor(DisplayName = "Custom Model Processor")
public class CustomModelProcessor : ModelProcessor
{
    public override ModelContent Process(NodeContent input, ContentProcessorContext context)
    {
        Matrix transformMatrix = //Whatever transformation you like
        BakeTransform(input, transformMatrix);
        MeshContent mesh = new MeshContent();
        //Initialize the MeshContent parameters (Name, Identity, etc.) how you like
        //f.e. use the values of the root node (input)
        MergeGeometry(input, mesh);
        NodeContent node = mesh; //Create a NodeContent from the mesh with all geometries
        return base.Process(node, context); //Process the new node instead of the input node
    }

    //This method transforms all vertices with the given transformMatrix)
    static void BakeTransform(NodeContent input, Matrix transformMatrix)
    {
        foreach(NodeContent child in input.Children)
        {
            MeshHelper.TransformScene(child, transformMatrix);
            BakeTransform(child, transformMatrix);
        }
    }

    //This method merges all the GeometryContent found in the input NodeContent
    static void MergeGeometry(NodeContent input, MeshContent output)
    {
        foreach (NodeContent node in input.Children)
        {
            MeshContent mesh = node as MeshContent;
            if (mesh != null)
            {
                foreach (GeometryContent geom in mesh.Geometry)
                {
                    output.Geometry.Add(geom);
                }
            }
            //Loop
            MergeGeometry(node, output);
        }
    }
}

```

For every model you import through the content pipeline you need to specify this processor as the processor for this piece of content. For your second question I don't have any idea of why you need this because it doesn't really matter whether you pass many small buffers, or one big buffer to the gpu. But it also could be implemented in a model processor by recursively adding the vertex and index buffers along with the geometry and everything else you need to the parent mesh. You should remember you can't use more than one material for this single big mesh, if you combine all the data into one big buffer.

-EDIT-

Added the code for merging the geometries to the code.

---
Tags: xna, models, loading, transformation, model-loader
---


# Question
Title: How do I protect my game with CD key / serial number?
So I've decided I want to keep pirated copies of my XNA game from accessing official game servers (which are moderated, so people who paid for the game will get the best experience) by disconnecting clients with wrong or generated, duplicate or banned CD keys (or serial numbers, since the game is digital and there are no CDs whatsoever).

How do I get that serial number protection system into my game (both clients and main authentication server), so it's not easily hackable?

---

Note that I have no experience with making good protection of that kind for software.

I've never done this before, but I understand the basics. I see why I can't do key checks on client, so it's fine by me to use login/pass authentication with one-time key entry.

Currently, the goal of this protection is to keep potential cheaters and disruptively behaving players out of official servers. Anyone can play on private servers with or without a key, but the chance they may get undesirable experience with other players is greater. I guess it's easy enough on purchasing players, since they have to be online to play on official servers.

Because hacking the client is too easy, I'm going to protect only the initial registration (and possibly server-side authentication) procedures, so nobody can steal the keys while they're being transfered.

---

See also:

How should multiplayer games handle authentication?

# Answer
Basically, you have three requirements:

1. it should not be easy to use the same key for multiple client instances,
2. it should not be easy to generate new valid keys, and
3. it should not be easy to steal the key of a legitimate client.

The first part should be pretty straightforward: just don't let two players log into the same server with the same key at the same time. You can also have the servers exchange information about logged-in users, or contact a shared authetication server, so that even using the same key for different players on different servers at the same time will fail. You will also probably want to look for suspicious patterns of key use and, if you determine that a key has been leaked, add it to a list of banned keys.

---

For the second part, one way is to simply maintain a database of all valid issued keys. As long as the keys are long enough (say, 128 bits or more) and chosen randomly (using a secure RNG), the odds of anyone managing to guess a valid key are essentially zero. (Even much shorter keys can be safe if you use some kind of rate limiting on failed login attempts to stop attempts to find valid keys by brute force.)

Alternatively, you can generate keys by taking any unique identifier and adding a message authentication code (such as HMAC), calculated using a secret master key, to it. Again, as long as the MAC is long enough, the odds of anyone who doesn't know the master key being able to guess a valid MAC for any ID is negligible. One advantage of this method, besides removing the need for a key database, is that the identifier can be any unique string, and can encode information about the client the key was issued for.

One problem with using MACs is that the official game servers (or at least the authentication server) need to know the master key in order to verify the MAC, which means that, if the servers are hacked, the master key might be leaked. One way to mitigate this risk could be to compute several MACs for each ID, using different master keys, but only store one of the master keys on the game servers. That way, if that master key is ever leaked and used to generate fake IDs, you can revoke it and switch to another master key. Alternatively, you could replace the MACs with digital signatures, which can be verified using only the public half of the master key.

---

For the third part, one approach is to make sure that the client won't send its key to anyone without verifying that the recipient really is a legitimate official server. For example, you could use SSL/TLS (or DTLS) for the login process, issue custom certificates for your game servers and only have the client trust certificates issued by you. Conveniently, using TLS will also protect the client keys (and any other authetication data) from eavesdroppers e.g. on public WLANs.

Unfortunately, this approach won't let third-party servers verify client keys even if they want to. You could work around this by setting up an official authentication server that third-party game servers can make use of, e.g. by having the client log in to the authentication server and receive a random one-time token which they can use to log into the game server (which then submits the token to the authentication server to verify it).

Alternatively, you could issue actual client certificates, or something like them, to your clients. You could either use an existing protocol (like TLS) that supports client certificate authentication (recommended) or implement your own, e.g. like this:

* The client certificate consists of an arbitrary ID string, a public/private key pair and a digital signature of the ID and the public key using the master key.
* To log in, the client sends their ID, public key and signature. The server replies with a unique challenge string (preferably including a server ID and a timestamp, which the client should verify), which the client signs with the private key (to prove that they know the key) and sends the signature to the server.
* The server checks both signatures, proving that the ID + public key form a legitimate client key (since they were signed with the master key) and that the client key actually belongs to the client (since the client could sign the server's challenge with the private key).

(This protocol could be further simplified by having the client generate the "challenge", consisting of a server ID and a timestamp, and sign it. Of course, then the server needs to verify that the ID and timestamp are valid. Also note that this simple protocol, on its own, won't stop a middleman attacker from being able to hijack the client's session, although it will prevent them from obtaining the client's private key needed for future logins.)
> 25 votes

# Answer
There's no 100% savety, but you could start with a rather simple approach:

* You'll need some way to verify generated keys, for example included checksums. Of course, this must not be too easy to figure out.
* Optional (but recommended) there'd be a server side database verifying the keys with a database of all given out keys so you can't generate keys, even if you happen to have the algorithm (let's ignore bruteforcing it).

From there on you can have two different approaches, but in either way something is very important:

* Don't verify the key on the client side. This is very important, because it's actually rather easy to decompile stuff written in .net/XNA. If you have to ask for the key or pass it (login or registration) hash the key (with an added salt etc.) and send it to the server.

As for the actual paths:

* Require the hashed key (see above) to be sent during the authentication/login procedure.
* As an alternative (IMO the better one, although many don't like this sort of "DRM"): Don't use the key in the client at all. Instead, require the user logging in to an account and require a valid CD key (this requires the database mentioned above) to create accounts. This is how modern games, e.g. any pay-to-play MMORPG handles this.

Personally, I'd go with the account approach due to a simple reason: In the end, you can't keep people from stealing CD keys (bruteforcing, reverse engineering or scamming). As such People could just create a new key to continue playing or to lock out others from the game. With account bound keys noone is able to do anything with a key that is already in use. In case someone bought a key someone else generated, you could still transfer the account ownership assuming there's sufficient proof of this.
> 16 votes

# Answer
Pangea Software -creator of several Mac games- has written a topic about copy protection in their (now free) game development book. The book also explains how to deal with pirated keys and other hacks people use. The book has a focus on development of Mac games, but the ideas might still be useful for other platforms. Included with the book is source code for each chapter, part of the download below. There's also source code (written in C) included related to copy protection.

The book can be downloaded here.
> 1 votes

---
Tags: security
---


# Question
Title: Preserving Cocos2D context between UIKit screens
My app is designed to use Cocos2D in the "main game screen" but the rest of the screens are in UIKit. While I feel that this isn't ideal, I really don't have time to port the rest of the screens into Cocos2D for the time being.

One of the problems I face is that I am required to load all the textures each time I enter the main game screen, and discard them once I leave Cocos2D-land (and repeat the process all over again)... or am I?

I am actually wondering if I could preload all the textures needed in a `CCTextureCache` during startup, even when the EAGLView and context hasn't yet been set up until I visit the main screen (and in doing so preserve the texture cache contents). But whenever I try this the app crashes.

Any way in which I can do this?

# Answer
How are you implementing mixing UIKit with Cocos2D?

The approach I use is to create a `UINavigationController` in the application `didFinishLaunching...` method and add the Cocos2D director as its root view controller.

```
navigator = [[UINavigationController alloc] initWithRootViewController:director];
[navigator setNavigationBarHidden:YES];

```

This way, using standard methods on the navigation controller, you can freely swap between UIKit view controllers and whatever Cocos2D is displaying without fully "shutting down" Cocos2D and flushing all its resources.
> 0 votes

---
Tags: ios, cocos2d
---


title: How to scale a texture in OpenGL/LWJGL?

text:
# Question
Title: How to scale a texture in OpenGL/LWJGL?
How would I take a texture and render it to a specific size? The texture I'm rendering has a 1:1 ratio so I want to be able to render the whole image like if the window is wide then put black outlines and the left and right and render the texture in the middle and if the window is taller (I don't see why it would be) then do the same with the texture by rendering lines at the top and bottom and rendering the texture in the middle. Does anyone know how to do this?

# Answer
You don't really need to change the texture at all, just change the size of the quad you're drawing the texture on. Make sure they maintain the correct aspect ration, and make the quad fit the constraints of the screen. Just re-size the quad to fit the screen and draw the texture full size on the quad.

Altering the texture based on the screen aspect ratio is much more difficult.
> 2 votes

---
Tags: opengl, 2d, textures, rendering
---


title: 2D js physics engine for HTML4

text:
# Question
Title: 2D js physics engine for HTML4
Is there any engine for Javascript like box2dweb that does not use Canvas? I need to build a game that works in HTML4 browsers.

# Answer
> 3 votes
There's nothing wrong with Box2D web - perhaps just the way you are trying to draw the data. Are you using the debugRenderer?

**Box2D - A web port**

Physics simulations are always decoupled from the rendering routines (or they should be!). This is because they typically work within their own spatial regions that calculations are done in. This is metric in the case of **Box2D** but I wouldn't doubt if some other physics engine out there uses something else.

Rendering stuff out from physics data is another story - but to answer your question: **all the good ones!** However, what might NOT work (and won't in the case of Box2D) is their debug renderer. You'll need to implement your routine to render objects with physics bodies - re-implementing the HTML5 Canvas debug drawerer many physics engines ship wiith (including Box2D) if you want a debug view of the objects.

---
Tags: 2d, javascript, jbox2d
---


# Question
Title: How do I linearly interpolate between two vectors?
I have a velocity vector where my client is at and where its going, and I have the same vector that comes from the server telling where the client should be. Sometimes its a bit different, so I want to interpolate between my current position to the server correct position.

The black arrow is the client velocity vector, the red arrow is the client velocity vector on the server and the blue arrow is the one that I want to calculate and interpolate to.

How do I calculate the blue vector? Then, how can I linear interpolate between them?

# Answer
> 19 votes
Blue vector can be calculated easily: red - black (the sign between vectors is minus). But if you want just to interpolate between black and red vector, you don't have to calculate it. Linear interpolation is just linear combination. So you can just take: alpha * black + (1 - alpha) * red, where alpha has to be from interval \<0,1\>. If alpha will be 1, then you will get black vector, when alpha is 0, you will get red vector.

And if I understood it right, you will interpolate between these vectors in time. So just choose right increment of alpha in time.

Did I understand you right? Or did you meant something completelly diffent?

# Answer
> 12 votes
Taking this picture:

AB is the red vector from A to B.

Say P is 25% of the way from A to B. The basic way to get to P from the origin is

```
A + ( B - A ) / 4
= 3/4 A   +   B / 4

```

So 3/4 A and 1/4 B.

Another way to find that is saying you want a vector 75% "close" to A, and 25% "close" to B. (A vector that is 100% "close" to A is just the A vector.)

So you would also be able to find P as:

```
A*t + (1-t)*B

```

With t=0.75 (to say 75% "close" to A)

```
0.75A + 0.25B

```

So a simple LERP function in C for a Vector3f class would be:

```
static Vector3f lerp( const Vector3f& A, const Vector3f& B, float t ){
  return A*t + B*(1.f-t) ;
}

```

---
Tags: mathematics, vector, interpolation
---


# Question
Title: Is Carmack right about PC performance? And does Windows 8 address his concerns?
Here John Carmack claims that PCs are still slower that current gen console hardware because of the overhead.

> "A lot of it's driver overhead issues, where there's so much that we do in the game, all of this dynamic texture updating where on the console we say 'alright, we've got a new page of data', we put that page in and update the page table that points to that.
>
> "On the console that may just be a matter of writing it to memory, it's like 'here's the texture, let's calculate exactly where this part of the page table is' and then we just poke it right in there," he explained.

Is the situation really that dire? And are there any features or changes in Windows 8 planed that will improve the current state of the PC Gaming ?

# Answer
> 30 votes
Console: static hardware that never varies across every single iteration. Home PC: hardware that changes from day to day, with a million different chip designs.

Console: closed system that lives in its own, secure environment from birth to death. Home PC: wild west, barroom brawls and your OS is the sheriff keeping everyone from getting shot.

Carmack: writing a system that depends on slinging around large texture blocks and is apparently sad that he doesn't get to personally write a hardware interface to every single graphics chip and OS variant from the last 5 years. Not to mention that he also apparently wants to give customer support to millions of people, hundreds of thousands of whom will have some kind of compatibility issue that Id must solve for them.

What's there to improve, given that on home PCs you have to support tens of different chipsets that have to work flawlessly against millions of programs written across the past decade or more? Personally I think that it's a miracle that the house of cards keeps standing!

Not much of an answer I know, but PC gaming is actually quite good and easy to develop for outside of certain esoteric optimization issues. A better question might be why are consoles so extremely limited?

# Answer
> 12 votes
What John Carmack really wants is to write his own graphics drivers. He lived and worked in the pre-Direct3D/OpenGL days, when the game was responsible for talking to every little piece of hardware that existed.

AMD actually made a similar statement, about how APIs are getting in the way of high-end graphics.

I don't know if Carmack's numbers are right, but his general statement is true: performance is being sacrificed on the PC. But what is gained is vendor neutrality to a very great degree. The ability to write the same code that works on different hardware.

There is the potential for some middle ground. Something that is thinner than D3D/OpenGL, but still allows for a reasonable degree of abstraction. The problem is that what a "reasonable degree of abstraction" means changes from hardware generation to hardware generation. A reasonable abstraction for one set of hardware is no longer reasonable for another. And while AMD and NVIDIA have been keeping relatively close to one another in basic graphics functionality, there are still lots of low level differences. And that doesn't even count Intel, who is way behind the both of them in even basic graphics functionality.

I imagine that Intel would jump at the chance to have such an API though, because they are absolutely *terrible* at implementing drivers. This way, they could just write a thin client.

As to whether Windows 8 will address this, that seems unlikely. Not unless it comes with a Direct3D 12 or some other API that allows lower-level access.

---

Well, now we have Direct3D 12, Apple's Metal, and Vulkan on the way. So it seems that some form of middle ground was discovered. And with the more low-level memory capabilities of D3D12/Vulkan, Carmack will apparently get his wish.

# Answer
> 6 votes
It's reasonably safe to assume that Carmack knows what he's talking about, but you need to realise that he's referring to a very specific problem domain which may not even exist outside of the stuff he's currently working on. My understanding is that his current engine uses completely dynamic texturing, so obviously the ability to efficiently update dynamic textures is something of a sticking point for him. The specific capability he's referring to - just being able to grab a pointer to texture memory and write directly to it, instead of having to go through API layers - is what I'll present as evidence for my argument, which is that he's right in the context of the specific problem he's referring to, and may even be right in the general case, but the general case would be to a somewhat significantly lesser degree to his special case.

# Answer
> 4 votes
From this interview, it appears that what he's talking about isn't throughput, it's latency. At 60FPS, ideally you have 16ms to put a frame on the screen *which has reacted to user input*. This basically means that the user "feels" a lag of 16ms between taking an action and seeing it appear on screen. Because that "lag" is equal to the frame rate, it's about as good as you can get, therefore everything is ideal.

Keep in mind here that LCD monitors & TVs also introduce lag, sometimes more than 16ms *on their own*. In this case (although not generally, Carmack cares a lot about LCD lag) he's ignoring any effects introduced by the LCD and pretending you're running on a CRT monitor, which has no lag.

Drivers are generally fairly efficient in that they keep the pipes filled, but they generally have latency issues. This means you can render stuff to a much higher quality, but there's a short lag between taking an action and having it appear on screen. This is a notable difference in attitude between Carmack and others: Carmack cares about your user input getting to the screen fast, whereas others care about maximising the pretty. If he's an old fogey, it's purely in that respect, not because he wants old fashioned hardware wrangling.

If you've played games like Battlefield 3 (or even Half Life), some of you will get motion sickness, where you wouldn't from a game like Quake. BF3 uses the full power of your PC efficiently (i.e. high framerates), but it treats your input as a second class citizen (i.e. high lag). Lag is also very important in things like VR or other biometrics. Obviously, from a gaming perspective, you get a much tighter feel for your movement when you have less lag.

This stuff is actually completely fixable in drivers, but it needs far more intricate and well thought out APIs. You can also often trade off efficiency for better latency. What I'm saying is that to dismiss Carmack is obviously a silly thing to do, but you also need to understand what it is he's saying.

---
Tags: performance, windows
---


title: Skysphere to Skybox Texture Conversion

text:
# Question
Title: Skysphere to Skybox Texture Conversion
I am working on a hobby project and implemented a skybox, no big deal. Now I bought (licensed) a few really nice sky textures. Unfortunately the textures are projected for a skysphere.

I could implement a skysphere handling/rendering, but I figure rendering a box is way more efficient. (That may actually not matter on modern devcies though.) So I decided to transform the textures into 6 textures for a skybox.

My hodge podge solution to convert the textures is I create a scene in blender and render out the appropriate 6 views. If you ask google that is aproptatly the common sollution.

**It there a tool that can do the conversion in a more automated way?**

# Answer
Note, that there is no pixel-to-pixel projection (one pixel can map into several pixels etc).

You should implement a geometric ray/cube intersection. It sounds complicated, but it is very easy. Choose a pixel on sphere map. From that pixel, you compute azimuth and elevation. Compute unit-length 3D vector, pointing from the center of the sphere to your pixel. Now scale that vector, so the largest coordinate is 1. Now you have coordinates on cube, so put your pixel color onto that coordinate in cube.

It would be better to do it backwards - request a pixel on cube and then look for that pixel in sphere map, so you don't have "empty spaces" in your cube map.

If you are looking for a tool, here is a discussion about it http://forum.quest3d.com/index.php?topic=46542.0
> 2 votes

---
Tags: textures, skybox
---


# Question
Title: Best way to develop a level from Top down image using 3dmax
I have to create a game level from a top down view of an area. I used a plane converted to an editable poly to do the job. I used edges to create the top view of roads, walkways and parks so that i can extrude/edit them later.
My problem is the curves in the road look blocky I tried appying mesh smooth modifier on the final model but that interfered with material mapping. Again i tried it on the plane without the extrusions and still the modifier does not work(The roads loose their shape). I know one way to solve the problem is to add more vertices on the curve and transform their location to create a more natural curve but i have a lot of curves so before doing it manually i need to know if there is a tool that refines the curves. Also i need to know if there is a better or proper way of doing the task.

# Answer
There are many ways of doing this, depending on what your final result wants to look like, but for the majority they all start with using the line tool - found in the spline section, this tool has the ability to change the control points to bezier, which means you have full control over the curve. You can also adjust the amount of points in the curve between each control point allowing you to make completely smooth curves.

You could draw the entire road (both sides and end caps) with this and apply something like a surface modifier to create a simple flat road.

Or you create a slice of the road's shape, so it includes curbs and paths etc.. you can use the line as a path and loft the shape along it.

Experiment with both methods on a small curve to see what effect works best for your purpose.
> 1 votes

---
Tags: 3d, models, 3dsmax
---


title: How can I solve this animation

text:
# Question
Title: How can I solve this animation
At the moment I have a simple static texture. Now I want to animate my sprite. The texture is a simple human. When the user press the enter button, the human gets into state2. This is the standart state during gameplay. If the user presses now "space" the sprite should get into state4(4th texture). This would be very unsmooth, so I decided to make a State3(ist just displayed very short to make the animation smooth). Now the sprite is in state4. If the user now releas the "space"-key the sprite should return into State2. For smoothness there is State3 short between.

**State1** "*press enter*" --\> **State2** --- "*press space*" --\> (short **State3** for smoothness) --\> **State4** --\> "*release space*" --\> (short **State3**) --\> **State2**

I hope you understand what I mean :)

michi

# Answer
Here is a simple class that you can reuse if you do it right, you can for example set a counter that counts down whenever the player is moving and create an animation from a "Sprite Strip"

```
public class SpriteAnimation : Microsoft.Xna.Framework.DrawableGameComponent
{
    int Rows, CurrentRow, Columns, CurrentColumn, X, Y, Width, Height;
    Texture2D Texture;
    SpriteBatch SpriteBatch;
    Rectangle destRectangle, sourceRectangle;

    public SpriteAnimation(int rows, int columns, Texture2D texture, SpriteBatch spriteBatch, Game game)  : base(game)
    {
        this.Rows = rows;
        this.Columns = columns;
        this.SpriteBatch = spriteBatch;
        this.Texture = texture;
        this.Width = this.Texture.Width / this.Columns;
        this.Height = this.Texture.Height / this.Rows;

        SetPosition(0, 0);
        SetFrame(0, 0);
    }

    public void SetPosition(int x, int y)
    {
        X = x;
        Y = y;

        destRectangle = new Rectangle(X, Y, Width, Height);
    }

    public void SetFrame(int row, int column)
    {
        if (row >= 0 && row <= (Rows - 1))
        {
            CurrentRow = row;
        }

        if (column >= 0 && column <= (Columns - 1))
        {
            CurrentColumn = column;
        }

        sourceRectangle = new Rectangle((CurrentColumn * Width), (CurrentRow * Height), Width, Height);
    }

    public override void Update(GameTime gameTime)
    {
        base.Update(gameTime);

        KeyboardState state = Keyboard.GetState();

        if (state.IsKeyDown(Keys.Space)) { /* SetFrame(0, 1) */ }
    }

    public override void Draw(GameTime gameTime)
    {
        base.Draw(gameTime);

        SpriteBatch.Begin();
        SpriteBatch.Draw(Texture, destRectangle, sourceRectangle, Color.White);
        SpriteBatch.End();

    }
}

```

If you check the link above that I include "Sprite Strip", you see that they're divided into columns and rows and that's what you use them for. For your animation, create a texture that has all four states and then you can jump between them whenever you need. So if you have all the different state textures on one row, then row = 1, columns = 4. Then you can extend this class to make it handle an animation yourself.
> 0 votes

---
Tags: xna, textures, animation, monogame
---


# Question
Title: Loading a vertex shader compiled by Visual Studio 2012
I've got an extremely simple vertex shader that Visual Studio 2012 compiles into a .cso file. Now I want to load this file and create a vertex shader on the graphics device using the `ID3D11Device::CreateVertexShader` function.

So far I have the following code:

```
ifstream vs_stream;
size_t vs_size;
char* vs_data;

vs_stream.open(vsCompiledPath, ifstream::in | ifstream::binary);
if(vs_stream.good())
{
    vs_stream.seekg(0, ios::end);
    vs_size = size_t(vs_stream.tellg());
    vs_data = new char[vs_size];
    vs_stream.seekg(0, ios::beg);
    vs_stream.read(&vs_data[0], vs_size);
    vs_stream.close();

    result = device->CreateVertexShader(&vs_data, vs_size, 0, &m_vertexShader);
    if(FAILED(result))
    {
        return false;
    }
}
else
{
    return false;
}

```

I seem to be able to load the file fine, I get sane values in `vs_size` and `vs_data` however `CreateVertexShader` returns `E_INVALIDARG` and sets `m_vertexShader` to null.

How can I fix this error?

*note that I can't use anything in the `d3dx*` headers since they are not supported in the Windows 8 App store*

# Answer
I found the error:

`result = device->CreateVertexShader(&vs_data, vs_size, 0, &m_vertexShader);`

Should be

`result = device->CreateVertexShader(vs_data, vs_size, 0, &m_vertexShader);`

(I wrongly dereferenced the pointer to the data)
> 2 votes

---
Tags: shaders, directx11
---


# Question
Title: Deploying MonoGame without OpenAL or Installer
I just shipped my first working MonoGame in-development game to one of my friends. He got some OpenAL DLL crashes, until he installed OpenAL.

Is there a way to include the OpenAL dependencies somehow with my game? I noticed Visual Studio already copies MonoGame, OpenTK, Tao.SDL, etc. to the `bin` directory.

**Edit:** XNA/MonoGame/VisualStudio already creates all the required DLLs, content, etc. in `bin`; it's only OpenAL that doesn't appear (there's no DLL). What's the best way to handle this *without creating an installer?*

# Answer
> 1 votes
I haven't tried this, but you could attempt to put the openal32.dll and wrap\_oal.dll files along with the rest of your bins. It should technically work, but again I have not tested this.

# Answer
> 8 votes
Just run the OpenAL installer inside of your install process.

You should be deploying your game with some sort of installer anyway to include libraries you might have and do other legwork, so just include another step in your build process to install OpenAL with the silent flag. For OpenAL this is:

> /S or /s or -S or -s The installation runs in silent mode. Nothing will be displayed.

Reference

This should be all you need to ensure every user has OpenAL installed before they try and run your game.

---
Tags: monogame, deployment
---


title: SDL_types.h file not found using xcode

text:
# Question
Title: SDL_types.h file not found using xcode
Getting this error when trying to use SDL\_mixer...

SDL\_types.h file not found..

I am including all the correct files as far as I can tell and have included the frameworks (both SDL and SDL\_mixer) to my /systems/library/frameworks folder and it compiles well until I add SDL\_mixer.h to my project. What should I do?

Here is main.cpp

```
#include <SDL/SDL.h>
#include "SDLMain.h"
#include "SDL_mixer.h"

int main(int argc, char ** argv)
{
    SDL_Init(SDL_INIT_EVERYTHING);
    Mix_Chunk song;
    //Initialize SDL_mixer
    if( Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ) == -1 )
    {
        return false;
    }

    song = Mix_LoadWAV("song.wav");
    SDL_SetVideoMode(1000, 500, 32, SDL_SWSURFACE);
    SDL_Event event;
    bool done = false;
    while(!done)
    {
        while (SDL_PollEvent(&event))
        {
            if (event.type == SDL_QUIT)
            {
                done = true;
            }
            if (event.type == SDL_KEYDOWN)
            {
                if (event.key.keysym.sym == SDLK_UP)
                {
                    Mix_PlayChannel( -1, song, 0 );
                }
            }
        }
    }
    SDL_Quit();

    return 0;
}

```

Thanks

# Answer
This is only a guess, but as far as I know you should include SDL as `<SDL.h>`. As I can see that you include SDL as `<SDL/SDL.h>` and SDL Mixer as `"SDL_mixer.h"`, the problem is that the header of `SDL_mixer.h` includes `<SDL_types.h>`, but in your case it would have to be `<SDL/SDL_types.h>`.

You should either extend the include search path to include the SDL folder (prefered) or alter the SDL\_mixer.h to refer to `SDL/SDL_types.h` (hacky).
> 1 votes

---
Tags: sdl, xcode
---


# Question
Title: How to structure (the code in) a multiplayer game
I'm working on a rather small project where we will be developing a small engine, a client, a server and an editor of some kind. It's a component-based 3D engine with basic systems like Rendering, Simple-Physics, etc.

So far, after a fair amount of thought I've decided to structure the engine as a library. It'll contain the classes for all of the components and the sub-systems, but will not run them. Instead it will be included into another project that will initialize the engine and run the game loop. I've started calling that second project the "host application."

I see the host application as the "game" or the "editor" with the engine kind of looking like a strap-on jetpack of goodies.

The reason for this (in my mind) is to allow the engine to be reusable, and so I can develop our editor, game, model viewer, etc. using the engine without having duplicate code every which way.

This is all working out well thus far, however when considering the typical client/server model for a multiplayer game a few questions come up.

In one respect I can treat the client and server as separate projects, both referring to the engine, in the other respect I could develop the client and server as one project with a bunch of switches and a command-line argument to denote which "mode" the game should be in.

Could one of you insightful awesome people shed some light on the pro's and con's of these methods, or perhaps suggest a better way?

# Answer
> 12 votes
Ok I am taking a stab at the issue, because I am in exactly the same situation.

## Engine vs. Libraries

This is one thing I often come across. Sure when you build a game you need an "engine". And many novice developer will look at the Quakes and Unreals and think that a engine is a monolithic piece of software that is multiple of millions lines of code. But these engines come from large companies and large companies tend to build large systems.

Over the years I have found that when I write a library that does exactly one task and knows nothing about an "engine" as the most useful. The reason is because the library can be used in any context. Years later I tend to reuse a library unaltered from a previous project, but any code that was in the Engine is basically impossible to extract.

It may be sensible to build libraries (or use third party libraries) that solve one task and then integrate them into an "engine". The engine is then only glue between the bits and serves to implement a consistent handling and the almighty `run` method.

## Simulation vs. Presentation

It makes sense to think about simulation (i.e. game logic) and presentation (rendering, sound), before asking about client and server. The reason being, that the server needs only to handle simulation, but the client needs to handle simulation (for local prediction) and presentation. You don't want to have code for visual effects running on the server, just because you think the physics are only done on the server.

It makes sense to package the engine into a central library or multiple libraries and have the client and server link that, since they are going to share much code. But you want to keep is somewhat modular, so you do not need to install presentation bits on a dedicated server setup. (But you can get away with it though.)

## My Design

Ok this is my current approach and it works quite well, but it is my approach and may not fit your needs.

The meat of my engine is implemented in libraries that are fully independent from the engine. I use some common libraries such as ODE for features that are fully realized by other people.

The engine is structured in the way that you have a central Engine class, but that does nothing meaningful. It is extended by Services, each service doing one special task, such as rendering or physics simulation. The systems are actually encapsulating a library. Entities, that are very specific to the actual game then use the systems to do anything non trivial. The important bit here is that, entities are expected to properly behave in the absence of a service. This enables one code stack to live in the server, client and editor.

The code is then separated in a base module that defines the basics, such as the Engine, Service and Entity base cases. Each service then lives in it's own module. The client and server then only load and link against the services they actually require.

I implemented the editor as a optional service in the client, that is loaded on demand when a specific command line argument is set. But this is a matter of taste and it clearly could be done as separate executable or the Engine class ditched completely and only the entities used directly.

---
Tags: c++, multiplayer, project-management
---


# Question
Title: Using two FBOs results in the second FBO having nothing drawn to
I'm writing a deferred renderer, and I use two FBOs: the first one for G-buffer (color, normal, depth) and the second one for lighting (light output), so the first one has three textures bound and the second one has just one.

Now, the geometry pass works just fine and all the three textures are populated correctly. After this, I try to render a full-screen quad in the lighting pass, but nothing comes to the screen - everything is black. I've even tried to use the diffuse shader program in this pass to be sure it's not a shader problem, and it's not - nothing gets drawn no matter which shader I use.

Here's some code (I've pruned out the non-relevant code)-

**G-buffer initialization**

```
// Setup buffers and textures
// FBO initialization
geometryFboId = GL.GenFramebuffer();
GL.BindFramebuffer(FramebufferTarget.FramebufferExt, geometryFboId);

// Texture initialization
diffuseTexture = GL.GenTexture();
normalTexture = GL.GenTexture();
depthTexture = GL.GenTexture();

// Diffuse texture
GL.BindTexture(TextureTarget.Texture2D, diffuseTexture);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, scrWidth, scrHeight, 0, PixelFormat.Rgb, PixelType.UnsignedByte, IntPtr.Zero);
GL.FramebufferTexture2D(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, TextureTarget.Texture2D, diffuseTexture, 0);

// Normal texture
GL.BindTexture(TextureTarget.Texture2D, normalTexture);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, scrWidth, scrHeight, 0, PixelFormat.Rgb, PixelType.UnsignedByte, IntPtr.Zero);
GL.FramebufferTexture2D(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment1Ext, TextureTarget.Texture2D, normalTexture, 0);

// Depth texture
GL.BindTexture(TextureTarget.Texture2D, depthTexture);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, scrWidth, scrHeight, 0, PixelFormat.Rgb, PixelType.UnsignedByte, IntPtr.Zero);
GL.FramebufferTexture2D(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment2Ext, TextureTarget.Texture2D, depthTexture, 0);

DrawBuffersEnum[] drawBuffers = new DrawBuffersEnum[] { DrawBuffersEnum.ColorAttachment0, DrawBuffersEnum.ColorAttachment1, DrawBuffersEnum.ColorAttachment2 };
GL.DrawBuffers(3, drawBuffers);

GL.BindFramebuffer(FramebufferTarget.FramebufferExt, 0);

```

**Lighting buffer initialization**

```
lightsFboId = GL.GenFramebuffer();
GL.BindFramebuffer(FramebufferTarget.FramebufferExt, lightsFboId);
lightsTexture = GL.GenTexture();

GL.BindTexture(TextureTarget.Texture2D, lightsTexture);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgb, scrWidth, scrHeight, 0, PixelFormat.Rgb, PixelType.UnsignedByte, IntPtr.Zero);
GL.FramebufferTexture2D(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, lightsTexture, 0);
DrawBuffersEnum[] drawBuffers = new DrawBuffersEnum[] { DrawBuffersEnum.ColorAttachment0 };
GL.DrawBuffers(1, drawBuffers);
GL.BindFramebuffer(FramebufferTarget.FramebufferExt, 0);

// Setup a target texture for the render
lightingTexture = GL.GenTexture();
GL.BindTexture(TextureTarget.Texture2D, lightingTexture);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgb, scrWidth, scrHeight, 0, PixelFormat.Rgb, PixelType.UnsignedByte, IntPtr.Zero);
GL.BindTexture(TextureTarget.Texture2D, 0);

```

**Render call**

```
// Bind geometry pass
diffuseShader.Enable();
GL.UniformMatrix4(diffuseShader.GetUniformLocation("view"), false, ref Camera.main.modelview);
GL.UniformMatrix4(diffuseShader.GetUniformLocation("projection"), false, ref Camera.main.projection);
GL.BindFramebuffer(FramebufferTarget.FramebufferExt, geometryFboId);

// Render the scene
currentScene.Render();

// Clear shaders and framebuffer
Shader.ClearShader();
GL.BindFramebuffer(FramebufferTarget.FramebufferExt, 0);

// Bind lighting pass
lightingShader.Enable();
GL.BindFramebuffer(FramebufferTarget.FramebufferExt, lightsFboId);
// Misc. parameter passing here

// Render a full-screen quad
quadRenderer.Render();

// Clear shaders and framebuffer
Shader.ClearShader();
GL.BindFramebuffer(FramebufferTarget.FramebufferExt, 0);

// Render output
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
GL.ClearColor(0f, 0f, 0f, 0f);

quadRenderer.Render(gBuffer.DiffuseTexture, QuadRenderer.QuadPosition.TOP_LEFT);
quadRenderer.Render(gBuffer.DepthTexture, QuadRenderer.QuadPosition.TOP_RIGHT);
quadRenderer.Render(gBuffer.NormalTexture, QuadRenderer.QuadPosition.BOTTOM_LEFT);
quadRenderer.Render(gBuffer.LightsTexture, QuadRenderer.QuadPosition.BOTTOM_RIGHT); // Draws just black

```

Hopefully I didn't miss anything important here. I've checked both FBOs, and they are "complete". I've tried to pass a texture to the quad renderer, but it doesn't seem to matter. I've also tried to replace the lighting shader and lighting passes with the geometry ones, and still nothing.

# Answer
I think I am missing something, here. The basic algorithm for deferred rendering is as follows:

```
bind geometry buffer
bind geometry shader
for each geometry
   render geometry

unbind geometry buffer
unbind geometry shader

bind frame buffer
bind light shader
bind textures from geometry buffer

for each light
   bind/setup light
   render area of effect subsitute

unbind light shader
unbind frame buffer
unbind textures from geometry buffer

bind post processing effects shader
bind textures from frame buffer
render one full screen quad

```

Geometry part is probably in `currentScene.render()` but I am totally missing the iteration over all lights. And can't make anything of the last five lines.

A very good, but a but old article on the subject is Image Space Lighting over at gamedev.net
> 2 votes

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


title: Sound activated particlesystem

text:
# Question
Title: Sound activated particlesystem
I am trying to make a particle system that is activated by sound. Like emitting on the beat resizing on the beat and such things. I found some nice tutorials on how to make things like Windowsmediaplayer visualsynths but they dont really help me to convert it to a particle system.

Anysuggestions how i could do this ?

# Answer
You need to read the audio spectrum and get the desired frequencies for example a bass beat would be in the range of 40 - 100 hertz then you can start doing complex algorithms with it but's that's the basics.

You might need to create a optimized version or precomputed particle driver from the audio to do this in real time.

To get the spectrum you'll need to read about discrete Fourier transforms (http://www.fftw.org/, there's probably a C# wrapper around, if not wouldn't be that hard to make one)
> 2 votes

---
Tags: c#, unity, sound, particles, visualization
---


# Question
Title: How does professional audio fit into game design?
Do game designers typically seek the help of specialized music/audio specialists for soundtracks and sound design? Is there a general need for professional audio work in game design, or is that something that only big budget game studios have a need for?

How would an audio engineer/musician/sound design type get involved with making game design projects?

I'm talking about someone who can record dialogue, create and record custom music and sound effects, and create a mix to fit all these elements together in a polished way.

# Answer
To be fair, there are a lot of resources I've seen on various game development websites; the forums at gamedev.net come to mind, and there is a list of other websites available here. Generally speaking, you either put together a resume and portfolio, and let people come to you, or you go asking around at specific companies, which is riskier and brings on higher expectations, but shows more initiative and drive.

As far as professional-quality audio production being only in the domain of "big budget game studios", this is only true on the notion that independent game studios simply cannot afford the audio production costs for games that are statistically far less likely to be commercially viable. If a studio has the resources and the will, they'll spend whatever they can afford on audio, but since most independent studios work on shoestring budgets either from previous successes, fundraisers, or personal contributions, many won't push for more expensive sound production.

If you're looking to prove your mettle with a first-try game project, and you're willing to offer discounts or special agreements with independent studios or game projects, then you'll probably see a few more buyers come your way from mid- to low-budget territory. But like everything in game development, deciding whether or not to hire a quality sound production team is a calculated risk, with the goal being to improve the overall player experience through better sound. For an audiovisual-experience game like Journey, this plays a major role in driving the point of the game; for smaller titles, sound effects and music may be an afterthought, or done with whatever resources are available. Just keep in mind that many developers just want good-quality audio on the cheap... though of course, the smattering of indie games of the last few years with compelling music and good-quality audio is leading to some significant changes in this area.

Just keep in mind that the most important thing is to have a strong, diverse portfolio of prior work; no one will hire an audio engineer with top-of-the-line equipment and no clue how to use any of it. (In fact, if I were in such a position, I'd rather hire a kid off the street if he hacked a Game Boy to remake new audio for Super Mario Bros., just because of his knowledge and drive.) As far as portfolio pieces go, any work that you have with relevance to the game, the studio, the genre, or just for game-related audio projects in general (fan-made soundtracks, custom compositions of game music, VO projects, sound effects, etc) will probably be best.
> 3 votes

# Answer
> Do game designers typically seek the help of specialized music/audio specialists for soundtracks and sound design?

Not designers specifically (as a designer is a specific role within game development) but it is common to use dedicated professionals for audio work, yes.

> Is there a general need for professional audio work in game design, or is that something that only big budget game studios have a need for?

There is a demand, but it's not very high.

* Hobbyists and independents will often use free or Creative Commons sound effects and music, or might use a tool to generate basic effects for themselves.
* Mid-sized studios will probably not have anyone in-house for audio, and will probably buy or contract the music and use pro sound libraries for FX.
* Larger studios may have a sound person on full-time, if they have enough concurrent projects to make it worthwhile. They will still often contract out the music, although some will take on a full-time musician.

So the issue is that there aren't many full-time people who work with audio in the games industry. There are a lot of composers vying for the same small pool of jobs, which means there are a lot of people offering their music for free, driving the price down and making it harder for composers to make a living. And on the sound design front, it's often just not so essential a role. You can buy in a couple of pro libraries and use them, and pretty much the only people who will notice they're stock effects are other audio professionals.

Being able to do both music and other audio may help, especially in the mid-sized companies.

> How would an audio engineer/musician/sound design type get involved with making game design projects?

Create a good, accessible, portfolio and pitch it to people. Network. Be prepared to do very cheap or free work in order to prove that you can deliver on projects. Familiarise yourself with game specific tools (eg. FMOD Designer, WWise) and concepts (layering and fading music loops to accommodate in-game changes, heavily compressing music so it never drowns out sound effects).
> 1 votes

---
Tags: sound, audio, music
---


# Question
Title: Render video from file to DirectX11 texture
Is there a way to render a video from file (avi, mp4, etc...) to a texture in a directx11 environment?

If so, how?

# Answer
Yes, first you need to read the container (avi, mp4 etc) and then decodee it's contents that can be h264 for example) and then you'll get an rgb output that can be copied over into a texture like you normally would do, if the video is not HD you could do this every frame to play it back.

You can use libffmpeg to read the video, but it's a little tricky i recommend you if the video is not too big to convert it into raw RGB data that you can read easily in your app.
> 5 votes

---
Tags: directx, directx11, video
---


# Question
Title: Did old games like Golden Axe or Street or Rage use tilemaps?
I am wondering if old games like Golden Axe (genesis) or street of Rage (genesis) used tilemaps or background bitmaps for the levels.

I could not find any resource that explain this and searching around in the web I can find background images, but I never found any tilemap for the levels. This off course, does not answer the question, but it looks like they used background bitmaps for the entire level.

But I am not sure if it was practical for those old consoles to store such "big" images and render those.

Does anyone knows a bit of programming on those old systems and knows how those "perspective" levels were built?

# Answer
Yes, they use tilemaps (more precisely : small `8x8 hardware tiles`). The main reason is that background scrolling and sprites display on most 16-bit consoles are `hardware accelerated` (there is a dedicated hardware chip for that, `VDP` in case of genesis). The only way to use that feature on genesis is to divide the background and sprites into small 8x8 tiles (even for displaying a single full screen logo).

Video memory (VRAM) was *very expensive* at that time and using small 8x8 tiles allow some tiles to be reused at different locations on the screen. Even if genesis can render games up to `320×480` resolution, there is not enough video memory (64KB) to hold a full frame.

Here is an example for Sonic (same goes for background) :

This main character is made using several 8x8 sprites, that stick together by moving on the screen at the same time. Same for background which is a 2D array of tiles.

Some consoles allow several `layers of tiles` (aka `planes`) to be displayed at the same time (maximum two for genesis). They usually have the same size (a little bigger than the screen) but can be scrolled independently. This is mostly used for `parallax scrolling` . These layers can give you the *illusion* that there is "huge bitmaps" moving on screen while they are actually independent layers of tiles.
> 20 votes

# Answer
Games of that age had to make use of very constrained memory. The Sega Genesis had only 64kb of video ram and only a few MB of ROM per game cartridge. They simply hadn't got the resources for large bitmaps. So they used tilemaps whenever possible and reserved large images for special occasions (boss fights or other memorable key areas of the game).
> 6 votes

# Answer
I would guess that they are using tile maps/sprite sheets for their textures, as you rightly guessed I think it was impracticable for them to use those large background images

equally you can see a lot of repetition in areas which shows the use of modular textures
> 2 votes

# Answer
I think you mean parallax scrolling http://en.wikipedia.org/wiki/Parallax\_scrolling for "perspective" levels
> 2 votes

---
Tags: tilemap
---


# Question
Title: Distribute circles evenly on Screen - circle packing
I want to evenly distribute a random amount of circles with random diameter on the screen for. This level doesn't scroll so the users screen resolution sets the limits. Further I would like the circles to be as big as possible to fill out the screen.

I have no problem writing the code for collision detection and so on, my problem is the basic theory to solve this kind of problem.

My current approach doesn't work properly because the problem could be the following thing, where (1) is the first circle and (2) is the second circle and | is the "wall" or screen edge.

`(1) (2)|`
So if 1 and 2 overlap, I would move 1 half of the overlapping distance to the left, 2 with the other half to the right. I then see that 2 is already at the wall and can't be moved, so 1 must move the whole overlapping distance to the left.

How would I correctly approach this situation?

# Answer
> 2 votes
Here is a very simple way to do what you want.

1. Pick a random point inside the rectangle (screen) & instance a 1-radius-circle at that point.
2. Grow the radius of that circle till it satisfies these criteria:
    * Does not overlap any of the other chosen circles.
    * Does not extend outside the rectangle.
    * Touches at-least one other chosen circle or a rectangle boundary.
3. Choose the circle if it satisfies these criteria.

Repeat 1-3 till you get sufficient circles covering the rectangle. You can optimize and tweak this as needed. For e.g. you might want to specify a range of accepted radii, or you might want to choose the radius based on the number of surfaces/circles it touches, etc, etc.

# Answer
> 2 votes
There was a game in the Ludum Dare "Evolution" contest that had various circles evolving (growing) when colliding with other circles. The code in that game should provide a good example of how to solve what you are asking.

Here is the link to the game: http://www.ludumdare.com/compo/ludum-dare-24/?action=preview&uid=14673

---
Tags: mathematics, physics
---