title: Problem draw SkyBox behind my sun - XNA

text:
# Question
Title: Problem draw SkyBox behind my sun - XNA
I try to create a small and simple 3D games on XNA.

I recently started to add a skyBox after added a sun in my game with the sample by Microsoft here http://xbox.create.msdn.com/en-US/education/catalog/sample/lens\_flare . The problem is , after add a skybox . My sun reacts strangely, it is no longer displayed. And occasionally, it bug. Appears and disappears repeatedly. Certainly because the sun is behind my skybox.

## Youtube

I upload a video on YouTube of my problem too ;-) : https://www.youtube.com/watch?v=i8mdaibMqA4&feature=youtu.be

## Problem identical

My problem is same as this : OcclusionQuery: how to ignore some objects?

Here is my file "SkyBox.fx"

```
    float4x4 WVP;
    float4 TextureColor;
    float AmountColorMix;

    float Depth;

    TextureCube tex;
    sampler cubeSampler = sampler_state {
        texture = <tex>;
        AddressU = CLAMP;
        AddressV = CLAMP;
    };

    struct VertexShaderInput
    {
        float4 Position : POSITION0;
    };

    struct VertexShaderOutput
    {
        float4 Position : POSITION0;
        float3 PosTex   : TEXCOORD0;
    };

    VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
    {
        VertexShaderOutput output;
        output.Position = mul(input.Position, WVP).xyww;
        output.PosTex = input.Position;

        return output;
    }

    float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
    {
        float4 color = texCUBE(cubeSampler,input.PosTex);

        return lerp(color, TextureColor, AmountColorMix);
    }

    technique Technique1
    {
        pass Pass1
        {
            CullMode = None;
            VertexShader = compile vs_3_0 VertexShaderFunction();
            PixelShader = compile ps_3_0 PixelShaderFunction();
        }
    }

```

Create and Draw the SkyBox (function)

```
        /* ********************************* */
        // Draw the SkyBox
        /* ********************************* */
        #region DrawSky
        public void DrawSky()
        {
            arcadia.Game.GraphicsDevice.SetVertexBuffer(skyVertices);
            arcadia.Game.GraphicsDevice.Indices = skyIndices;

            skyEffect.Parameters["WVP"].SetValue(Matrix.CreateTranslation(arcadia.camera.Position) * arcadia.camera.View * arcadia.camera.Projection);
            skyEffect.Parameters["TextureColor"].SetValue(arcadia.lensFlare.ColorSun.ToVector4());
            skyEffect.Parameters["AmountColorMix"].SetValue(0.25f);
            skyEffect.CurrentTechnique.Passes[0].Apply();

            arcadia.Game.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, number_of_vertices, 0, number_of_indices / 3);

        }
        #endregion

        #region Creating a basic VertexBuffer
        void CreateCubeVertexBuffer()
        {
            Vector3[] cubeVertices = new Vector3[number_of_vertices];

            cubeVertices[0] = new Vector3(-1, -1, -1);
            cubeVertices[1] = new Vector3(-1, -1, 1);
            cubeVertices[2] = new Vector3(1, -1, 1);
            cubeVertices[3] = new Vector3(1, -1, -1);
            cubeVertices[4] = new Vector3(-1, 1, -1);
            cubeVertices[5] = new Vector3(-1, 1, 1);
            cubeVertices[6] = new Vector3(1, 1, 1);
            cubeVertices[7] = new Vector3(1, 1, -1);

            VertexDeclaration VertexPositionDeclaration = new VertexDeclaration
            (
                new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0)
            );

            skyVertices = new VertexBuffer(arcadia.Game.GraphicsDevice, VertexPositionDeclaration, number_of_vertices, BufferUsage.WriteOnly);
            skyVertices.SetData<Vector3>(cubeVertices);
        }
        #endregion

        #region Creating a basic IndexBuffer
        void CreateCubeIndexBuffer()
        {
            UInt16[] cubeIndices = new UInt16[number_of_indices];

            //bottom face
            cubeIndices[0] = 0;
            cubeIndices[1] = 2;
            cubeIndices[2] = 3;
            cubeIndices[3] = 0;
            cubeIndices[4] = 1;
            cubeIndices[5] = 2;

            //top face
            cubeIndices[6] = 4;
            cubeIndices[7] = 6;
            cubeIndices[8] = 5;
            cubeIndices[9] = 4;
            cubeIndices[10] = 7;
            cubeIndices[11] = 6;

            //front face
            cubeIndices[12] = 5;
            cubeIndices[13] = 2;
            cubeIndices[14] = 1;
            cubeIndices[15] = 5;
            cubeIndices[16] = 6;
            cubeIndices[17] = 2;

            //back face
            cubeIndices[18] = 0;
            cubeIndices[19] = 7;
            cubeIndices[20] = 4;
            cubeIndices[21] = 0;
            cubeIndices[22] = 3;
            cubeIndices[23] = 7;

            //left face
            cubeIndices[24] = 0;
            cubeIndices[25] = 4;
            cubeIndices[26] = 1;
            cubeIndices[27] = 1;
            cubeIndices[28] = 4;
            cubeIndices[29] = 5;

            //right face
            cubeIndices[30] = 2;
            cubeIndices[31] = 6;
            cubeIndices[32] = 3;
            cubeIndices[33] = 3;
            cubeIndices[34] = 6;
            cubeIndices[35] = 7;

            skyIndices = new IndexBuffer(arcadia.Game.GraphicsDevice, IndexElementSize.SixteenBits, number_of_indices, BufferUsage.WriteOnly);
            skyIndices.SetData<UInt16>(cubeIndices);

        }
        #endregion

```

# Answer
> 2 votes
Finally i solve and fix the problem by myself .

Add

```
GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;

```

before draw the skyBox

And Add

```
arcadia.Game.GraphicsDevice.DepthStencilState = DepthStencilState.Default;

```

after finish draw the skyBox

Full Code:

```
#region DrawSky
public void DrawSky()
{

    arcadia.Game.GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;

    arcadia.Game.GraphicsDevice.SetVertexBuffer(skyVertices);
    arcadia.Game.GraphicsDevice.Indices = skyIndices;

    skyEffect.Parameters["WVP"].SetValue(Matrix.CreateTranslation(arcadia.camera.Position) * arcadia.camera.View * arcadia.camera.Projection);
    skyEffect.Parameters["TextureColor"].SetValue(arcadia.lensFlare.ColorSun.ToVector4());
    skyEffect.Parameters["AmountColorMix"].SetValue(0.25f);
    skyEffect.CurrentTechnique.Passes[0].Apply();

    arcadia.Game.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, number_of_vertices, 0, number_of_indices / 3);

    arcadia.Game.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
}
#endregion

```

# Answer
> 1 votes
One way of handling this is to modify the depth range in your viewport when drawing the skybox.

For XNA you would set both MinDepth and MaxDepth to 1, leaving the other members the same as your main viewport, like so:

```
Viewport.MinDepth = 1.0f;
Viewport.MaxDepth = 1.0f;

```

This will ensure that your skybox is always drawn to the back of the scene, and using this technique you don't need to worry about the skybox size at all: you could even draw it as a 10x10x10 cube around the view point and it would still work. This will also work well with any other kind of object you want to add in the sky (birds, etc).

Another way is to output a depth of 1.0f from your pixel shader, but that's generally not recommended as it can interfere with your GPU's early-Z optimizations.

---
Tags: xna, textures, shaders, skybox
---


# Question
Title: One draw call with one big mesh VS many draw calls with many little meshes
I have read that in order to optimize WebGL application, one should reduce an amount of draw calls. But does it mean that computing a one big mesh from all single meshes on CPU by modifying vertices position (which I heard is much slower than GPU while talking about matrix multiplications) and calling the draw call once would be faster than drawing every single mesh using model matrix inside GPU, calling the draw call for each one of them?

# Answer
*It depends.*

* If it's something static, such as an environment, then it might make sense to group it all together.
* For several independently moving/transforming objects, it's usually best to keep them separate, as per-vertex calculations are much faster on the GPU than CPU (the GPU can run several vertex calculations in parallel).
* If the objects are very small though (i.e. particles, billboards), it may be worth grouping them in a large mesh.

There's no general rule, it's all about finding the right balance.
> 1 votes

---
Tags: shaders, javascript, webgl
---


# Question
Title: How to prevent showing outside of Game Map ( Cocos2D-x ) ( Scrolling game )
I'm trying to make a tower defense game and it can zoom in/out and scrolling over my world map. How to scroll over the game and how to restrict it not to show outside of my map(black area).

At below I scroll over the map by using CCCamera but I don't know how I can restrict it.

```
CCPoint tap = touch->getLocation();
CCPoint prev_tap = touch->getPreviousLocation();
CCPoint sub_point = tap - prev_tap;

float xNewPos, yNewPos;
float xEyePos, yEyePos, zEyePos;
float cameraPosX, cameraPosY, cameraPosZ;

// First we get the current camera position.
GameLayer->getCamera()->getCenterXYZ(&cameraPosX, &cameraPosY, &cameraPosZ);
GameLayer->getCamera()->getEyeXYZ(&xEyePos, &yEyePos, &zEyePos);

// Calculate the new position
xNewPos = cameraPosX - sub_point.x;
yNewPos = cameraPosY - sub_point.y;

GameLayer->getCamera()->setCenterXYZ(xNewPos, yNewPos, cameraPosZ);
GameLayer->getCamera()->setEyeXYZ(xNewPos, yNewPos, zEyePos);

```

And for zooming I used such code:

```
GameLayer->setScale(GameLayer->getScale() + 0.002); //zooming in

```

# Answer
> 6 votes
**EDIT :** Multi-resolution bug fixed.

Here is my solution for you:

First of all Let's sync some **assumption**:

1. We have a layer ( Let's say `MapLayer` ) that includes game map background ( Let's name it `map`) and its content( map-related objects, e.g. towers and enemies).
2. I didn't use `CCCamera`. I tried to scale and move `MapLayer` instead.
3. bottom-left and top-right position of map before layer scale and after.

Here we go..

**1. `MapLayer.h` changes**

```
class MapLayer : public cocos2d::CCLayer
{
private:
    // this sprite define your visible area boundary
    CCSprite* map;
    CCPoint visible, origin;
    // 'currentCenter' is based on nonScaled-Layer-Size.
    // [0,0] => [map.width , map.height]
    // = keep pixle of GameLayer that you want to be shown in middle of screen
    // = (visible.x/2, visible.y/2) means you want to move map as left/bottom as possible
    CCPoint currentCenter;

    // Correct currentCenter value that MoveCenterTo don't show ouside of map
    CCPoint CorrectCenterPoint( CCPoint currentCenter, float layerScale );

    // Move this layer in order to make `center` point center of screen
    void MoveCenterTo(CCPoint center, float layerScale);
};

```

**2. `MapLayer.cpp` changes**

```
bool GameLayer::init()
{
    if (!CCLayer::init())
    {
        return false;
    }
    visible = CCDirector::sharedDirector()->getVisibleSize();
    origin = CCDirector::sharedDirector()->getVisibleOrigin();
    // We need to set GameLayer position according to left-bottom point
    this->setAnchorPoint(ccp(0, 0));

    // IMPORTANT: We assume Left-Bottom of map is in (0,0) of GameLayer
    map->setPosition(ccp(map->getContentSize().width /2,
                    map->getContentSize().height /2));
    currentCenter =  ccp(visible.x / (2 * this->getScale()),
                         visible.y / (2 * this->getScale()));

    ....
}

// presume : `center` is based on nonScaled-layer-size:  [0,0] => [map.width, map.height]
CCPoint MapLayer::CorrectCenterPoint( CCPoint center, float layerScale )
{
    CCPoint scaledCenter = center * layerScale;

    // mapSize = in-game size of map. ( Don't forget to multiply this to map->getScale() if you had scaled map)
    CCSize mapSize = background->getContentSize() * background->getScale();
    float scale = this->getScale();

    scaledCenter.x = max(scaledCenter.x, visible.x/ 2);
    scaledCenter.x = min(scaledCenter.x, mapSize.width*scale - visible.x/2);
    scaledCenter.y = max(scaledCenter.y, visible.y/ 2);
    scaledCenter.y = min(scaledCenter.y, mapSize.height*scale - visible.y/2);

    return (scaledCenter/layerScale);
}

// presume : `center` is based on nonScaled-layer-size:  [0,0] => [map.width, map.height]
void MapLayer::MoveCenterTo(CCPoint center, float layerScale)
{
    // Convert nonScaled-layer-size to scaled-layer-size
    // [0,0] => [0,0] ||| [map.width, map.height] => [map.width * S , map.height * S]
    CCPoint scaledCenter = center * layerScale;

    scaledCenter.x = -scaledCenter.x + visible.x / 2 + origin.x;
    scaledCenter.y = -scaledCenter.y + visible.y / 2  + origin.y;

    this->setPosition(scaledCenter);
}

void MapLayer::ccTouchesMoved(CCSet* pTouches, CCEvent* pEvent)
{
    CCTouch* touch = (CCTouch*)pTouches->anyObject();
    CCPoint location = touch->getLocation();
    CCPoint deltaMove = touch->getDelta();

    // 100 unit move of a 2x layer, feels 200 unit move. So we calculate Delta as 1/2 to match layer move with touch-move.
    // Therefore, if we move 100unit touch, we need to move 50unit the layer to show 100unit move in screen.
    currentCenter = currentCenter - deltaMove / this->getScale();
    currentCenter = CorrectCenterPoint(currentCenter, this->getScale() ) ;
    MoveCenterTo( currentCenter , this->getScale());

    // Processing Touches :
    CCPoint scaledCenter = currentCenter*this->getScale() ;
    CCPoint offsetFromCenterOfScreen = location - (visible / 2)  - origin  ;
    // 100 unit move of a 2x layer, feels 200 unit move. So we calculate Delta as 1/2 to match layer move with touch-move.
    // Therefore, if we move 100unit touch, we need to move 50unit the layer to show 100unit move in screen.
    CCPoint RealTouchLocationinLayer  = (scaledCenter + offsetFromCenterOfScreen)/this->getScale() ;
}

```

\** ***Zoom In/Out*** \** I don't enter in detail for zoom and just give you a working clue :

```
void MapLayer::zoomIn(CCTouch * touch)
{
    CCSize screenSize = CCDirector::sharedDirector()->getWinSize();
    // the offset of zoom-point and center of screen
    // for simplification I used touch location as zoom-point and make it center of camera for test.
    currentCenter = currentCenter + ( touch->getLocation() - visible/2 ) ;
    // here we increase scale some constant value in order to test
    this->setScale(this->getScale() + 0.5);
}

```

Hope Helps you. ;)

---
Tags: camera, cocos2d-x, scrolling
---


# Question
Title: How to design enemies pattern in non-bullet-hell shmups in Unity?
I am making a top down shooter.

Enemies will come in waves and attack in many different patterns (i.e. wave of 10 enemies flying in a elliptic curves, or a huge boss floating and shooting at you, etc.).

I'm thinking of 2 solutions:

1. Design paths using an animation tool
2. Hard-code paths

For the first solution, I think it will be faster to create the paths since I will be able to see them in the tool, but is it performant? There will be hundreds of flying patterns in my game.

I've also heard of BulletML, but looks like it's more for bullet-hell shmups, and there's no visual editor to design the patterns easily.

Are there other solutions to design path patterns for non-bullet-hell shmups which I haven't considered?

What are the pros/cons of each solution?

# Answer
> 0 votes
This is a job for scripting, and any kind of tool you use *should* produce some kind of script. Since we happen to be talking about Unity, that could be C#, JS, or even Boo.

---

Assuming there is no general tool for pathing (and there are, Simple Waypoint System being one example), you can build one yourself:

1. Write a few paths by hand and take note of the parts that could be parameterized.
2. Rewrite your example code in a way that you'll be able to fill in the parameters (like a more complicated mad lib)
3. Create data structures to hold/save/open that information.
4. Test that the data structures can fill in the blanks - this will become a "compile" button in your tool.
5. Create an interface to display/modify the paths.

You can then attach the behaviours produced by the tool to your objects.

It might be a bit of work up front, but if you're sure that you'll need to make hundreds of paths then it will be worth it in terms of making changes later.

---
Tags: unity, movement, tools, shoot-em-up
---


# Question
Title: Love2D : How can I keep up with lots of small sprites' collision data?
So I'm using a `SpriteBatch` to keep up with lots of small pieces for a falling-piece puzzle game. I have an array of `Quads` (for different color blocks), and they are randomly added to the aforementioned `SpriteBatch`. Right now, the game determines when the current piece has hit the ground, then that piece is stopped and a new piece spawns that the player now can control.

In order to figure out when to stop dropping the piece, I need to do a collision check. This shouldn't be hard, because I should only have to check the falling piece (unless the current falling piece causes a chain reaction). **But,** what type of data structure should I use? I can't use the position data of the individual `Quads`, because the boundary boxes will actually be a different size/shape than the pieces (think triangle pieces, but I will need to use a slightly skinnier rectangle to fit upside-down pieces in between right-side up pieces).

Should I just duplicate the `(x, y)` pairs using offsets with a width and height, and store them in an array, or am I missing a more obvious/efficient way? I'm guessing that the play screen could fill up with several hundred of these pieces, and if I add two player mode, double that.

EDIT: Here's what the Quad size issue is all about:

# Answer
Assuming all triangles are the same size I recommend you use a grid to keep track of the slots that are being occupied by a triangle. If the slot where the triangle is going to be next frame is occupied, then you have collision:

```
if slotThatIsNext.empty == false then
    thisSlot.empty = false
    thisSlot.triangle = thisTriangle
end

```
> 1 votes

---
Tags: collision-detection, sprites, lua, spritebatch, love2d
---


# Question
Title: 2D how to add graphics for liquid physics?
I was always wondering how to add the graphics to a a blob body for example, regardless of what engine or library you are using, i want to know (theoratically) how to move from this state : http://www.youtube.com/watch?v=qHvsER4Ou0w

to something like the blob in this video : http://www.youtube.com/watch?v=ssOaZ3Lrov0

thank you

# Answer
I think the easiest way to reproduce that case is to just generate a circle's geometry with many segments to give it nice bending capabilities then map the circle's texture coordinates directly to the blob texture.

Then, for the actual bending to happen, you take the rigid bodies' positions from the physics system and use those to distort their corresponding vertices in the circle.

To do this, you can, for example, get the angle of each rigid body relative to the center of the blob object, then find which vertices in the circle are affected by comparing their angle plus a threshold. Once you know what circle vertices need to be affected by which rigid bodies in the blob simulation, you can simply re compute the vertex of the circle's edge to be at the same distance from the center as the rigid body is.

To get the distance from the center in the blob simulation: float blobVertexDistance = distance(rigidBodyPosition, centerOfBlob);

To compute the new circle vertex position out of a distance and the angle: vec2 newPosition = vec2(cos(angle) * blobVertexDistance, sin(angle) * blobVertexDistance);

Let me know if something is unclear.

This technique works best if you use Triangle Strips to render the circle, if I am not mistaken.
> 1 votes

---
Tags: 2d, physics, graphics
---


title: What affects the size of APK files?

text:
# Question
Title: What affects the size of APK files?
The size of the .apk file built by Unity is larger than I expected. Is it image resolution, number of scenes, or something else?

# Answer
The things that take the most impact in the size of APK are the assets (audio files, images, models, config files, icons, and so on) and the libraries (jars and/or dynamic native libraries).

With this information, you can deduce that the more assets and scenes you have, the bigger it will be. Also, with big frameworks like Unity, there will always be a minimum fixed size cost for anything you build.
> 2 votes

---
Tags: android, unity
---


title: Simple rendering produces minor stutter

text:
# Question
Title: Simple rendering produces minor stutter
For some reason, this game loop renders the movement of a simple rectangle with no stuttering.

```
    double currTime;
    double prevTime = System.nanoTime() / NANO_TO_SEC;
    double FPSTIMER = System.nanoTime();
    double maxTimeDiff = 100.0 / 1000.0;
    double delta = 1.0 / 60.0;
    int processes = 0, frames = 0;

    while(true){
        currTime = System.nanoTime() / NANO_TO_SEC;
        if(currTime - prevTime > maxTimeDiff) prevTime = currTime;
        if(currTime >= prevTime){
            process();
            processes++;
            prevTime += delta;
            if(currTime < prevTime){
                render();
                frames++;
            }
        }
        else{
            try{
                Thread.sleep((long) (1000 * (prevTime - currTime)));
            }
            catch(Exception e){}
        }

        if(System.nanoTime() - FPSTIMER > 1000000000.0){
            System.out.println("Process: " + (1000 / processes) + "ms FPS: " + (1000 / frames) + "ms");
            processes = frames = 0;
            FPSTIMER += 1000000000.0;
        }
    }

```

But for this game loop, I get really minor stuttering where the movement does not look smooth.

```
    long prevTime = System.currentTimeMillis();
    long prevRenderTime = 0;
    long currRenderTime = 0;
    long delta = 0;
    long msPerTick = 1000 / 60;
    int frames = 0;
    int ticks = 0;
    double FPSTIMER = System.currentTimeMillis();

    while (true){
        long currTime = System.currentTimeMillis();
        delta += (currTime - prevTime) / msPerTick;
        prevTime = currTime;

        while (delta >= 1){
            ticks++;
            process();
            delta -= 1;
        }

        prevRenderTime = System.currentTimeMillis();
        render();
        frames++;
        currRenderTime = System.currentTimeMillis();

        try{
            Thread.sleep((long) ((1000 / FPS) - (currRenderTime - prevRenderTime)));
        }
        catch(Exception e){}

        if(System.currentTimeMillis() - FPSTIMER > 1000.0){
            System.out.println("Process: " + (1000.0 / ticks) + "ms FPS: " + (1000.0 / frames) + "ms");
            ticks = frames = 0;
            FPSTIMER += 1000.0;
        }

```

Is there any critical difference that I'm missing here? The one thing I noticed is that if I uncap the fps for the second game loop, the stuttering goes away. It doesn't make sense to me. Also, the second game loop came from Notch's Minicraft code with just my thread sleeping code added in.

# Answer
> 0 votes
I agree don't use sleep.

Use a timer based on system time

eg:

take system time snapshot (snapA),

compare it every loop frame to the current time in miliseconds or snapB.

some pseudocode

```
snapA = systemtime.milliseconds;

while(running)
{
     snapB = systemtime.milliseconds;

     if (snapB >= snapA+(1000/desiredframerate))
     {
         snapA = snapB
         drawFrame;
     }
     else
         continue;
}

```

This is a good way to do it by my tests in the past. This allows frames to drop (go missing) when necessary () but allow a other things to happen on other threads if this loop/thread hangs for any reason.

Eg: if your animation and movement within the scene is on one thread and this is on another, if this thread hangs (such is the nature of java) then the other thread continues allowing movement to continue and this thread will drop frames till it picks up the current frame from the scene. It also means that the animation/ movement isn't relying on the graphics frame rate.

java can be funny with threads. When we were taught about threads for our java oracle professional exam it was explained that sometimes the JVM will kill/sleep/join or continue a thread and I quote "because it feels like it" so be careful and don't sleep a thread unless precision is unimportant.

also

(Notch)

```
Thread.sleep((long) (1000 * (prevTime - currTime)));

```

is not the same as

(you)

```
Thread.sleep((long) ((1000 / FPS) - (currRenderTime - prevRenderTime)));

```

Logically speaking.

---
Tags: java
---


# Question
Title: Was there any equivalent of glVertex3f in Direct3D?
I know that OpenGL's `Vertex3f` is a bit old but I can't find any information about suitable equivalent for that function that was used in DirectX. Was there any equivalent in DX?

# Answer
No.

While Direct3D had, a long time ago, a concept of "immediate mode" and "retained mode" APIs, the D3D immediate mode was not the same as OpenGL's immediate mode (which is where the `glVertex3f` function sits).

Retained-mode D3D was a scene-graph-like API, and generally considered too high level to be useful. It was abandoned after Direct3D 3. Direct3D's immediate mode was a buffer style API; you'd fill up buffers and execute them. It was an API that perhaps lended itself to OpenGL-style wrappers, but there was never a function in D3D that was precisely equivalent to OpenGL's `glVertex3f` or related functions.
> 4 votes

# Answer
DirectX has its own set of math libraries that has progressively evolved over the generations. See this MSDN link for specifics on DirectXMath

http://msdn.microsoft.com/en-us/library/windows/desktop/ee415571(v=vs.85).aspx
> -1 votes

---
Tags: opengl, directx
---


# Question
Title: Generating multiple instances of one opengl object with random coordinates
Sorry if the question is dumb but my brain just cannot solve it for some reason..

So I've made one opengl object `public static Square ball = new Square(75,75);`

And I am trying to make it so that every so often a new ball appears on the screen

```
public void Loop(GL10 gl) {
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    gl.glLoadIdentity();
    long timeSinceStart = SystemClock.uptimeMillis();
    long deltaTime = timeSinceStart - oldTimeSinceStart;
    oldTimeSinceStart = timeSinceStart;
    if(deltaTime >= 15) {
        RandBall(gl);
    }}

```

code for RandBall()

```
   `public void RandBall(GL10 gl) {
     gl.glPushMatrix();
         gl.glTranslatef(rand.nextInt((1280 - 0) + 1) + 0,
                         rand.nextInt((720 - 0) + 1) + 0, 0);
         getBall().draw(gl);
     gl.glPopMatrix();
}`

```

but when I run the code it draws only one object and constantly changes its coordinates. How do I make it so that it draws multiple objects with different random coordinates? The solution is probably going to be an easy one but I just can't see it :/

# Answer
You are calling `glClear(GL10.GL_COLOR_BIT...` every time you enter `loop()`. You keep erasing the last ball drawn. To see each one you need to redrawn each ball every frame. Just store the position information created by `RandBall()` in a container such as `ArrayList`. Then after you call `glClear()` loop through the list and draw the ball at each position.
> 1 votes

---
Tags: java, android, opengl-es
---


title: Normal Mapping space confusion

text:
# Question
Title: Normal Mapping space confusion
I've been reading today about normal mapping. Up to now, the only normal mapping I encountered was with maps already in world space so I just extracted the info from the texture and transformed them with the normal matrix.

Now I wanted to try to use a normal map that is in tangent space, but I immediately became really confused.

What I've in my code up-to-now is

**Vertex Shader**

```
 ...
passedPosition = modelViewMatrix*vec4(vertexPosition,1.0);
 ...

```

**Fragment Shader**

```
 vec3 V = normalize(-passedPosition .xyz);   // Eye vector
 ...
 vec3 L_dir = passedPosition .xyz - lights[i].lightPosition.xyz;
 vec3 L = normalize(L_dir);
 ...

```

And then proceed with my lighting calculations.

All the tutorial I came across change all the light directions and the view vector into tangent space (in the vertex shader) and then extract the normal from the texture and keep going (in fragment). My issue here is that I'd like to avoid to access all my lights informations in the vertex shader, so my questions are:

* Does make sense to pass to the fragment shader the t,b,n vectors so that I transform the light directions there? Should I consider access all my lighting informations in vertex shader (I have an array of Light struct which has more than just the position) and then passed them on to the fragment shader? Is something I'd like to avoid, but if is much better I can think of it.
* There is a way to perform normal mapping that is more compatible with what I've now (snippets above posted).
* Should I consider change my calculations from view space to world space? In that case, how can I perform normal mapping?

Thanks

# Answer
> 3 votes
Yes, it does make sense to pass the tangent basis (the T,B,N vectors) down to the fragment shader, then transform the normal (from the normal map) to world space or view space and do all the shading calculations in that space. In fact that's probably the more common way to do normal mapping these days, I suspect.

I prefer world space for shading calculations as you then don't need to transform all your light positions/directions to view space each frame, and it also makes it easier to use things like pre-rendered environment cubemaps or spherical harmonics, which are in world space anyway. However, shading can be done perfectly well in view space also.

To do shading in world space, you would do the following:

* In the vertex shader, transform the TBN vectors by the object's local-to-world matrix (not including translation, since they're vectors, not points). Send the now world-space TBN basis down to the fragment shader. (Actually you don't need to transform B, you can just calculate it as B = N cross T.)
* Also calculate world-space vectors from the vertex to the camera and the light (just a subtraction) and send those down to the fragment shader as well. (Or this can be done in the fragment shader.)
* In the fragment shader, sample the normal map and use the TBN vectors to transform it into world space. Then do all the shading calculations (N dot L and so forth).

For view-space shading you would do the same thing; just substitute view space for world space in the previous steps. The only new step is that you need the light position to be in view space, so you have to calculate that somewhere, either on the CPU or in one of the shaders.

---
Tags: opengl, textures, glsl, normal-mapping
---


# Question
Title: How do I load Collada models into a WebGL app?
I have written some simple apps following the tutorials on http://learningwebgl.com. What is the simplest way to load and display Collada model files, particularly the files available from Google 3D Warehouse?

# Answer
Have a look at the opencollada site.

The SDK is licensed under MIT license and should get you a good start.

If you are planning to make a game (and not just a viewer app), you should run the converter offline (during the build) and load your optimized model format during runtime.

Parsing collada is inefficient and shipping collada files is just wasted space.
> 2 votes

# Answer
GLGE supports viewing Collada. However, I would suggest converting to JSON offline and using that instead.
> 1 votes

# Answer
You can convert the files, for example with Assimp or 3D Wayfinder.
> 0 votes

---
Tags: webgl, collada
---


# Question
Title: Are there 3D projections other than orthographic and perspective?
The question is pretty much in the title. Are there notable 3D projections other than orthographic and perspective that could be used in a 3D system such as OpenGL?

In particular, are there any that have a particular use in game design?

# Answer
> 23 votes
Yes, To name a few:

The Pannini projection, for example, can capture wide fields of view in *nice* ways. (totally just my opinion)

I think implementation details would be beyond the scope of this specific question.

---

EDIT: Thanks for the comment, I did misspell Pannini. And to make this edit worthwhile here are a few more:

* Paraboloid / Dual-Paraboloid (Useful for reflections, shadows, stained glass)
* Equirectangular (Can produce a world map view of a sphere)
* Spherical
* Sinusoidal

# Answer
> 15 votes
It depends on what you mean by "that could be used in a 3D system such as OpenGL". :)

Narrowly speaking, 3D graphics hardware and APIs like OpenGL only deal correctly with *linear* projections - projections that map straight lines in world space to straight lines on the image. They never distort something into a curved shape (unless it was curved to begin with). This is because GPUs depend on triangles having straight edges in order to rasterize them correctly on screen.

If we limit ourselves to linear projections, there aren't too many choices. In addition to the standard ortho and perspective, there are also "off-center" variations which are obtained by shearing the view frustum.

* An off-center ortho projection is called oblique projection and is often used for engineering diagrams but doesn't show up much in games.
* Off-center perspective projections are used in stereo 3D rendering, since it turns out that the left and right eye views fuse better in the brain if you shear the frustums instead of rotating them to focus on an object.

These projections can be represented with the usual 4×4 projection matrix and used in a 3D API without problems.

Then there are the nonlinear projections, which don't have the restriction of mapping straight lines to straight lines; they're allowed to distort things into curves. There are lots of these, including cylindrical, spherical, various types of fisheye, and others.

With nonlinear projections, you can't simply use a projection matrix; you have to somehow implement the projection yourself using shaders. One way is to write a custom vertex shader to do the projection per vertex. The GPU will still draw the triangle with straight lines between the vertices, so while small triangles will be pretty close to correct, larger triangles will be noticeably wrong. This can cause problems, and geometry may need to be subdivided very finely in order to render correctly.

A second approach to getting a nonlinear projection is to render the scene using a regular perspective projection first (maybe to a cubemap, which has a perspective projection for each cube face), then apply a post-process pixel shader to resample it to the desired nonlinear projection. This has the advantage of not requiring geometry modifications, but it can be more expensive due to the extra rendering work required, and the result can be blurry in some areas if the first-pass render doesn't have enough resolution. The post-process approach is used by Oculus Rift games, for example, to implement the nonlinear projection the Rift requires to work with its lenses.

# Answer
> 0 votes
I can't believe it but nobody has mentioned Isometric Projection which used to be quite common.

---
Tags: 3d, mathematics, graphics, projection, linear-algebra
---


# Question
Title: How to correctly implement player acceleration caused by player input
In my game I implement movement in the `Player` class like so:

```
// called from Player's update() method, which is called from the gameloop.
void move(){
    velocity.x += acceleration.x;
    velocity.y += acceleration.y;
    position.x += velocity.x;
    position.y += velocity.y;
}

```

Keyboard input affects the `acceleration` directly, for example:

```
// in Player, called from main gameloop.
void update(){
    if(playerInput.rightPressed()) (acceleration.x += 2);
    // .. etc
    move();
}

```

I think so far this is standard (if not, please say so).

Now my question:

During movement invoked by player input, I want the `acceleration` to be constant. So when the player presses the right arrow key, the `acceleration.x` will always be 2 - and not 2, and then 4, and then 6, etc.

I could easily acheive this be having `if(playerInput.rightPressed())(acceleration.x = 2)`, but then other forces acting on the entity will be ignored.

What is the standard way to implement this?

# Answer
> 3 votes
Generalising on concept3d's answer, you could make it possible to add and revoke *arbitrary* forces.

This is all LiveScript-flavoured pseudocode:

```
class Player
    -> # constructor
        this.forces = HashMap()
        this.mass = 1
    move : ->
        this.acceleration = sum(this.forces.values) / this.mass
        this.velocity += this.acceleration
        this.position += this.velocity
    add-force : (force) ->
        new-id = generate-some-random-string()
        this.forces.set(new-id, f)
        return new-id
    revoke-force : (force-id) ->
        if force-id == null { return; }
        this.forces.delete(force-id)

```

Same in English: Store each force separately, each by some generated ID. Return that ID as the force is added. Allow forces to be removed based on ID. Resolve forces to a total acceleration on game step.

Having instantiated a player, you could then add gravity like this:

```
gravity-force-id = player.add-force({ x : 0, y : 1 })

```

And similarly, a movement-input-force:

```
input-force-id = null

if player-input.right-pressed()
    input-force-id = player.add-force({ x : 2, y : 0 })
else
    player.revoke-force(input-force-id)

```

…or any other force at all.

# Answer
> 1 votes
> but then other forces acting on the entity will be ignored.

You can take other forces into consideration. Use different acceleration variable for each force and sum them. For example:

```
if(playerInput.rightPressed())(inputAcceleration.x = 2)

```

vec3 playerTotalAcceleration;

```
void move(){
    //Update acceleration
    playerTotalAcceleration  = vec3(0,0,0)
    foreach acceleration
       playerTotalAcceleration += acceleration[i] + inputAccelaration

    velocity.x += playerTotalAcceleration.x;
    velocity.y += playerTotalAcceleration.y;
    position.x += velocity.x;
    position.y += velocity.y;
}

```

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


title: Where should I put my game loop?

text:
# Question
Title: Where should I put my game loop?
I've seen some tutorials on programming a good game loop, but none mention **where** (in the game code) I should call it.

My guess is I should call it from the `main()` method. Am I right? Is there another way?

---

Second question:

I'm using Java, and my game loop is a method in the same class as `main()`. When I tried to call it, the compiler did not recognize the `gameLoop()` method, because it wasn't static. So I changed it to static, as well as `render()` and `update()`.

But it just doesn't make sense to me. What should I do in this case?

# Answer
You can not have a non-static method in Main, because there is no instance of the Main class (unless you create one).

The game-loop can be placed wherever you feel is a good place for it. There is no "right" or "wrong" way to do this. Only the way which is right or wrong for you and your current project. However, there are best practices which happen to be right more often than others.

A common technique is to put the game loop method into an own class named `Game` or similar and create a `new Game` in the main-method. An advantage of this architecture is that you can have multiple `Game`s which exist independent of each other.

You might also consider moving your `update`-method into a `GameState` class and your render-method into a `Renderer` class and pass the gamestate to it (`renderer.render(gameState);`). This allows you to reuse both components. You could reuse your graphic engine for an entirely different game by passing a GameState object with a different internal logic to it or you could replace your renderer with a different graphic engine. This would, for example, allow you to switch from a 2d engine to a 3d engine without having to change anything at the implementation of your game mechanics. You could also have different renderers for different views of the game state. A minimap, for example, could also be a different renderer. It also visualizes the current gamestate, just in a different way.
> 4 votes

# Answer
How think about reading example of another game engine's? Such as cocos2dx, libgdx. You can get some ideas from it.
> -2 votes

---
Tags: java, architecture, game-loop
---


# Question
Title: What are "local" and "global" rotations?
Each node in jME3 has local and global rotations, which can be expressed in quaternions.

What are they?

Documentation has no clues, about in which state rotations are zero?

# Answer
> 2 votes
jME3 uses a Scene Graph for rendering, which basically means that you have a tree structure of nodes where the leaf nodes are models.

Each level of node can have a different *local* Position/Scale/Rotation. To calculate the *global* P/S/R (that is, where a leaf node would *actually* be rendered) for a node you take it's parents global P/S/R and add that to the childs P/S/R.

In this way you can give a character a weapon, and if you move the character the weapon moves along with it automatically.

More information about jMonkeyEngine3's scene graph can be found here

A quaternion that represents no rotation when is called the Identity quaternion and is (X:0, Y:0, Z:0, W:1).

# Answer
> 1 votes
Local vs. Global coordinate spaces apply to all transforms: position, rotation, and scale. They can be thought of by imagining the movement you do when instructed "turn left" and you are, say, inside a bus facing the back of the bus; does that mean your left, or the left side of the bus? Your local coordinate system defines "left" to your left, but that direction is to the right side of the bus.

Now add in some abstract notion of "left" for the entire world, regardless of which way you or anyone else is facing; that is Global coordinates.

---
Tags: rotation, quaternion, jmonkeyengine
---


title: "Couldn't load font" LibGDX

text:
# Question
Title: "Couldn't load font" LibGDX
yesterday I started working om making custom sized fonts to my game, in game, using `FreeTypeFaceGenerator`, and yesterday it worked fine, except an exception I was going to handle today. When I loaded it up today, and tried to run it, it keeps crashing in the part where I create the FTFGen object, I have no idea how to fix this. How do I fix this, where do I even begin? I changed to font file and it gives me the same error it did yesterday, but I don't want the other file (Vivaldi), I need the one I'm testing (Viner Hand ITC). How do I fix this? I'm using .TTF files, not making a bitmapfont file.

I don't want to provide my own source code, but I'll post the same way, just change a couple of things: (I followed a guide located here )
The method recieves three parameters, A `FileHandle` of the font file, a `String` of the font name, and a `float` array with all the sizes which will then turn to size of the font using
`(int)(size*Gdx.graphics.getDensity())`
This is the code:

```
FreeTypeFontGenerator ftfGen = new FreeTypeFontGenerator(handle);
    for (float x : size) {
        PixmapPacker packer = new PixmapPacker(512, 512, Format.RGBA8888,
                2, false);
        FreeTypeBitmapFontData fontData = ftfGen.generateData(
                (int) (x * Gdx.graphics.getDensity()),
                FreeTypeFontGenerator.DEFAULT_CHARS, false, packer);
        Array<Page> pages = packer.getPages();
        TextureRegion[] textureRegions = new TextureRegion[pages.size];
        for (int i = 0; i < pages.size; i++) {
            Page p = pages.get(i);
            Texture texture = new Texture(new PixmapTextureData(
                    p.getPixmap(), p.getPixmap().getFormat(), false, false,
                    true)) {
                @Override
                public void dispose() {
                    super.dispose();
                    getTextureData().consumePixmap().dispose();
                }
            };
            texture.setFilter(Texture.TextureFilter.Nearest,
                    Texture.TextureFilter.Nearest);
            textureRegions[i] = new TextureRegion(texture);
            BitmapFont font = new BitmapFont(fontData, textureRegions,
                    false);
            FileHandle file = Gdx.files.local("Data\\VINERITC.TTF");
            FileHandle pixmapDir = Gdx.files.local("Data\\VINERITC");
            BitmapFontWriter.setOutputFormat(OutputFormat.Text);
            String[] pageRefs = BitmapFontWriter.writePixmaps(
                    packer.getPages(), pixmapDir, fontName);
            for (int j = 0; j < pageRefs.length; j++) {
                pageRefs[j] = fontName + "_" + pageRefs[j];
            }
            BitmapFontWriter.writeFont(
                    font.getData(),
                    pageRefs,
                    file,
                    new FontInfo(fontName, (int) (x * Gdx.graphics
                            .getDensity())), 1, 1);
            packer.dispose();
        }

    }

```

The error I am receiving is in this line of code:
`FreeTypeFontGenerator ftfGen = new FreeTypeFontGenerator(handle);`
Upon digging around in the code of LibGDX I found out that it is caused by this method, which uses a native method:

```
    public static Face newMemoryFace(Library library, byte[] data, int dataSize, int faceIndex) {
    ByteBuffer buffer = BufferUtils.newUnsafeByteBuffer(data.length);
    BufferUtils.copy(data, 0, buffer, data.length);
    long address = newMemoryFace(library.address, buffer, dataSize, faceIndex);
    if(address == 0) {
        BufferUtils.disposeUnsafeByteBuffer(buffer);
        throw new GdxRuntimeException("Couldn't load font");
    }
    else {
        library.fontData.put(address, buffer);
        return new Face(address, library);
    }
}

private static native long newMemoryFace(long library, ByteBuffer data, int dataSize, int faceIndex);

```

This part gives out the error:

```
long address = newMemoryFace(library.address, buffer, dataSize, faceIndex);
        if(address == 0) {
            BufferUtils.disposeUnsafeByteBuffer(buffer);
            throw new GdxRuntimeException("Couldn't load font");
        }

```

The `newMemoryFace` is a native method.

**I FOUND THE PROBLEM!** This line is the problem:

```
FileHandle file = Gdx.files.local("Data\\VINERITC.TTF");

```

This line caused a creation of a new TTF file, and thus cause a problem with the loading system, make sure if you use this to write  `.fnt`  and not TTF.

# Answer
To anyone who had run into this problem, it originates from the creation (at least for me) of another TTF file in the local directory (I.e. "myGDXGame-desktop"), and this causes a problem with the loading of the font. Make sure that this line, that is the save directory for the `.fnt` file, is not saving as `.TTF`
This was what's needed to be made:

```
FileHandle file = Gdx.files.local("Data\\VINERITC.TTF");

```

Changed to this:

```
FileHandle file = Gdx.files.local("Data\\VINERITC.fnt");

```
> 1 votes

---
Tags: libgdx, fonts
---


# Question
Title: Can I create an offscreen plain surface with a pointer to pre-allocated surface data?
I thought I read somewhere that one could create a 'offscreen plain surface' from an existing system memory buffer, but I cannot seem to find the reference anymore.

My use case is copying a frame from video memory to a pre-allocated buffer, and right now I perform this in two steps: copying to an 'offscreen plain surface' (`GetRenderTargetData`), and from that to a pre-allocated buffer. If I could create the surface from the pre-allocated buffer, it would save a copy. I am using Direct3D9Ex on Windows 7.

# Answer
There are no overloads for `CreateOffscreenPlainSurface` that take a pre-allocated memory buffer.

D3D will generally want to own the memory its resources, for various reasons. Even methods that accept "user" data pointers, like `DrawPrimitivesUP` tend to guarantee that the data referred to by the user pointer has been "completely accessed" by the time the function returns, which allows for the API to copy the data if needed.

If there was such a method of creating a surface with a pointer to the surface bits, you wouldn't actually avoid the copy by using it. You'd just avoid having to write the copy yourself; D3D would do it internally.
> 1 votes

---
Tags: c++, directx
---


# Question
Title: LibGDX collision detection on moving and rotating object (rectangle enemy)
i am trying to get collision dectection working properly but when i do it, the collision area keeps moving. no matter what i tried. there are 2 objects and the objects are moving and i cannot get the area of the collision to follow the enemy/object.

i am using the method below to see if the collision will work and it does not follow the enemy properly.

```
enemy class extends sprite {

```

the above is an example of how i am using the sprite extension.

the object/enemy is a sprite from libgdx the class is extended by sprite.

```
shapeRenderer.begin(ShapeType.Filled);
shapeRenderer.setColor(Color.RED);

shapeRenderer.rect(rect1.getX() + (rect1.getWidth() / 2), rect1.getY()  + (rect1.getHeight() / 2) - 2, rect1.getOriginX() - 1, rect1.getOriginY() - 4, 1.0f, 1.0f, rect1.getRotation());

shapeRenderer.rect(rect2.getX() - 10, rect2.getY() - 10, rect2.getWidth() - 10, rect2.getHeight() - 10, rect2.getOriginX(), rect2.getOriginY(), rect2.getRotation());

shapeRenderer.end();

```

this is in the enemy class collision check

```
rect.set(getX() + (getWidth() / 2), getY()  + (getHeight() / 2) - 2, getOriginX() - 1, getOriginY() - 4);

```

this is to see if the enemy is colliding

```
public boolean collides(Ball ball) {
 if (getX() < ball.getX()) {
 return (Intersector.overlaps(ball.getRect1(), rect));
  }
 return false;

 }

```

Any help will be really nice. thank you

# Answer
Is it possible that you're tracking location in two different places? I noticed in your code

```
shapeRenderer.begin(ShapeType.Filled);
shapeRenderer.setColor(Color.RED);

shapeRenderer.rect(rect1.getX() + (rect1.getWidth() / 2), rect1.getY()  + (rect1.getHeight() / 2) - 2, rect1.getOriginX() - 1, rect1.getOriginY() - 4, 1.0f, 1.0f, rect1.getRotation());

shapeRenderer.rect(rect2.getX() - 10, rect2.getY() - 10, rect2.getWidth() - 10, rect2.getHeight() - 10, rect2.getOriginX(), rect2.getOriginY(), rect2.getRotation());

shapeRenderer.end();

```

that you use a rect1 and rect2. Do these correspond to the sprites location as well?
> 0 votes

---
Tags: java, android, libgdx
---


# Question
Title: Is there an equation to determine when to invoke extrapolation in response to lag?
I've implemented interpolation to smooth character drawing in my networked game. But now I want to fall back on extrapolation if too much time has passed from a user sending an update and the interpolation buffer has been used up.

I'm just wondering if there is an equation that suites the following :

**If it has been X since this user's last update, extrapolate the user position using the current time.**

That determines the optimal amount of time for X.

I could try lots of different things like "we have surpassed the standard deviation of the last 100 moves + a constant", but I'm convinced there has to be an optimal strategy for deciding *when* we need to extrapolate. Surely this is a solved problem, is my thinking.

I've searched thoroughly but have found nothing. Also, for reference, I'm interpolating and extrapolating on the client.

# Answer
> 2 votes
It *is* a solved problem: choose a value or a formula that works well for your game. Playtest. Tweak the value. Iterate. Et cetera. There is no single value that works optimally for all games, and no formula to compute a value for a game.

Remember you're making a game, and you should choose solutions that serve the game (solutions that make it fun, and make it feel responsive, connected, and engaging) and not solutions that serve some *algorithm*.

---
Tags: algorithm, networking, extrapolation
---


title: Dynamic navigation mesh changes

text:
# Question
Title: Dynamic navigation mesh changes
I'm currently trying to convert from grids to navigation meshes for pathfinding, since grids are either too coarse for accurate navigation, or too fine to be useful for object tracking.

While my map is fairly static, and the navigation mesh could be created in advance, this is somewhat of a tower defense game, where objects can be placed to block paths, so I need a way to recalculate portions of the navigation mesh to allow pathing around them.

Is there any existing documentation on good ways to do this? I'm still very new to navigation meshes, so the prospect of modifying them to cut or fill holes sounds daunting.

**EDIT:** To be clear, I'm looking for solutions that use a polygon navigation mesh, not a grid. I currently use grids, but I'm trying to move away from using them. It is the efficient dynamic modification of that polygon mesh that I'm trying to figure out.

# Answer
I think you want Dijkstra's algorithm, which is also used for internet routing.

In short, you must create a graph where each edge is a path from one node to another. These could be pre-calculated if some of your geometry is fixed.

For each starting point, you will order the nodes according to their distance from the destination. Then apply Dijkstra's algorithm through the graph to build routing tables for each one. The first route in the table will be the shortest path. Each route after that will be a variation depending on which nodes are blocked. These extra routes could be calculated as necessary, provided their order is maintained in the table (they should be ordered by the sum of their edge lengths). You'll refer to these routes again when a node is changed (blocked/unblocked).

You can then add and remove nodes by splitting edges and moving the new midpoint, then recalculating from the origin node.
> 1 votes

---
Tags: path-finding, navmesh
---


# Question
Title: How write pixel by pixel with a fast way Allegro 5.01
I'm currently trying to do a black and white filter for my game in c++ with Allegro 5.01, I'm doing like this.

```
void    GameEngine::blackAndWhite()
{
    ALLEGRO_BITMAP *buffer  = al_get_backbuffer(this->windows);
    ALLEGRO_LOCKED_REGION *region = al_lock_bitmap(buffer, ALLEGRO_PIXEL_FORMAT_ARGB_8888, ALLEGRO_LOCK_READWRITE);
    unsigned char *ptr = static_cast<unsigned char *>(region->data);

    for (int x = 0; x != 640; ++x) {
        for (int y = 0; y != 480; ++y) {
        unsigned char   red;
        unsigned char   green;
        unsigned char   blue;

        this->getpixel(ptr, x, y, region->pitch, &red, &green, &blue);
        unsigned char result = (red + green + blue) / 3;
        this->putpixel(ptr, x, y, region->pitch, al_map_rgb(result, result, result));
        }
    }
    al_unlock_bitmap(buffer);
}

```

And putpixel and getpixel is like this.

```
void        GameEngine::putpixel(unsigned char *ptr, int x, int y, int offset_y,  ALLEGRO_COLOR color) {
    unsigned char   red;
    unsigned char   green;
    unsigned char   blue;
    unsigned char   alpha;

    ptr += (y * offset_y) + (x * 4);
    al_unmap_rgba(color, &red, &green, &blue, &alpha);
    *ptr++ = red;
    *ptr++ = green;
    *ptr++ = blue;
    *ptr = alpha;
}

void        GameEngine::getpixel(unsigned char *ptr, int x, int y, int offset_y,
unsigned char *red, unsigned char *green, unsigned char *blue)
{
    ptr += (y * offset_y) + (x * 4);
    *red = *ptr++;
    *green = *ptr++;
    *blue = *ptr++;
}

```

It's working, but it's really slow, I'm thinking it's slow because this operation is do by the CPU and not the GPU.

Is there a way for reduce the time of the operation with allegro or not ?

# Answer
> 3 votes
Allegro is very slow and unoptimized when drawing single pixels to a bitmap. even slower when that bitmap is the backbuffer of the screen: it is stored in video memory and the **CPU** is the one responsible to do that operation. The bitmap has to be copied to main memory to work on it, then it is sent back to the **GPU**, all this operations are **I/O bound** and are very *VERY* slow.

A fragment shader could be useful in this case, but your current version of allegro does not have support for them as they are part of the 5.1 branch.

A possible speed-up could be obtained if you copy the buffer to a **memory bitmap** and write in it all the pixels of the filter and then send that result to the graphics card, which is less work than making drawing calls pixel by pixel.

An easy way to make memory bitmaps that does not mess the allegro flags state is to use this helper function:

```
ALLEGRO_BITMAP *create_memory_bitmap(int w, int h)
{
    ALLEGRO_BITMAP *bmp;
    int flags = al_get_new_bitmap_flags();
    al_set_new_bitmap_flags(flags | ALLEGRO_MEMORY_BITMAP);
    bmp = al_create_bitmap(w, h);
    al_set_new_bitmap_flags(flags);
    return bmp;
}

```

That way you have less draw calls that need to call the GPU and the CPU (Only three this time I think), however, don't expect too much speed from this as it is still a very unoptimized function to have direct pixel access.

Source:

al\_create\_bitmap

\[al\_set\_new\_bitmap\_flags\]\[2\]

---
Tags: c++, allegro
---


title: How to render rounded shape perfectly?

text:
# Question
Title: How to render rounded shape perfectly?
I'm having issues rendering rounded shape figures. I have a Texture with different images in it and I get this whale figure from it with TextureRegion but the stroke of it looks pixelated.

The original whale image is 357x721 px and the program scalate it up or down depending on the device.

And I use TextureFilter to Nearest but it doesn't solve problem as I thought it would.

Does someone knows a bit about this issue?

```
    texture = new Texture(Gdx.files.internal("texturepack_nuevo.png"));
    texture.setFilter(TextureFilter.Nearest, TextureFilter.Nearest);

    pilar = new TextureRegion(texture,591,0,357,721);

    whale_1 = new TextureRegion(texture,0,0,591,323);
    whale_1.flip(false, true);

    whale_2 = new TextureRegion(texture,0,323,591,323);
    whale_2.flip(false, true);

    whale_3 = new TextureRegion(texture,0,646,591,323);
    whale_3.flip(false, true);

    TextureRegion[] whales = {whale_1,whale_2,whale_3};
    whaleAnimation = new Animation(0.15f, whales);
    whaleAnimation.setPlayMode(Animation.PlayMode.LOOP_PINGPONG);

```

# Answer
> 3 votes
You can't render a rounded shape perfectly on a computer screen; a computer screen is composed of discrete cells (pixels) so some approximation is always going to happen. It's just a matter of hiding that approximation so the result is visually appealing enough.

*Nearest* texture filtering is generally not what you want to create the appearance of smooth curves, because it simply chooses a color based on the closest integer boundary of a texel. *Linear* filtering (`TextureFilter.Linear` in libgdx) is more akin to what you want, since it will interpolate between the surrounding integer-boundary texel coordinates to arrive at a color. This can remove harsh edges, but often has the result of overcompensating and making those edges "blurry," especially for uneven scale factors.

If adjusting the filter does not provide the results you want, you may want to look into some methods of anti-aliasing.

# Answer
> 0 votes
You might also be interested in using vectors graphics. Vectors graphics use mathematical functions to describe objects rather then normal pixels. As such vector graphics are always as good as they can be on a given screen no matter how much you zoom in or out. You can look here for a number of software programs to generate vector graphics, now not every programming language supports vector graphics but most do.

---
Tags: android, game-design, libgdx, rendering
---


# Question
Title: Should I avoid rescaling models when rendering?
I am quite new to game development and currently developing a simple 3D game with MonoGame and Blender. The game is basically a 3D version of Pong.

At first I developed the models at a constant size (e.g. a sphere with radius = 1) and then added a scale when I rendered it to make it proportionate to the other objects within the world. That way it was easy for me to play around and find good sizes for the objects without having to go back to Blender.

However, when I started to work on collision detection, I realized that it now was a lot harder to figure out how large the object is, because I had to manually recalculate the size of the object in the game world according to the scale factors I used. I could not simply look at the model and take the size values from there.

While the calculations might have been rather easy with a simple sphere, it got trickier when I had models I scaled differently in different dimensions. For example I rescaled a cube to be 10 times longer than high.

Pretty much the same problem with rotation.

How is this usually done in projects? Is it better to create the model already in the final size in Blender, so you don't have to keep track of the objects size within your code? Or is it ok to scale the model in code? If yes, how do you keep track of the changes?

# Answer
> 3 votes
What you've described (authoring all your content to be normalized within a unit sphere) is not a common workflow. Generally, a reference frame is established within your modelling program (for example one modelling world unit is assumed to be one meter) and all objects are modeled against that reference frame. A building that is fifty times the height of a one-meter-tall character would be 50 units tall in your modelling program.

Keeping the relative size of objects intact in their source form is useful if your asset pipeline ever involves working with multiple assets as references within a larger scene, as is typical with many large games. For example, many cinematic sequences are authored by importing asset references for the various characters into a scene and manipulating them within that scene. This becomes more cumbersome if you then have to apply scaling factors to bring everything into correct relative frames.

It also means you have to store the appropriate scale for an asset somewhere, which is generally illogical if you could just store it implicitly in the asset data itself by modelling it at the actual size.

So basically, it is a far less confusing workflow to simply build assets at the proper size originally.

That said, it's entirely *doable* to build everything normalized and apply some scaling factor at runtime. It just introduces a lot of complexity for very little benefit (you're already transforming and rotating the geometry every frame, so scaling incurs no additional cost... but it also doesn't speed anything up). You can simply scale the pre-computed bounding volumes and other related shapes at runtime by the same factor you're scaling the render model by, if you want. It's just not very natural.

---
Tags: 3d, rendering, models, scale
---


# Question
Title: How do I create a HUD that appears to occupy 3D space/can animate?
I'm working with a group to try and make a first person space platformer in Unity, and was wondering if there would be anyway to create a HUD that moves and reacts to player actions, specifically looking around - similar to the way the HUD moves in Metroid Prime. I'd also like it appear projected onto the inside of a helmet.

I'm not entirely sure what best-practice would be in this situation. Should we just attach the GUI elements to transparent objects in 3D space, then parent them to the main camera, essentially building our HUD with actual objects; or is there another way that would be more efficient? I'm still very new to game development, but this is something we'd really like to have in our game if at all possible.

# Answer
Yes, you can just create the HUD as a series of 3D objects that are always rendered at a fixed position in view space in a separate rendering pass (so they don't compete with depth buffer tests and the like with "world" objects). Fixing the objects' position to the camera in some fashion is one way to do this.

You can achieve the "floating" effect by tracking the camera's current and previous view vector and interpolating between that over time, making sure to do your HUD elements aligned to the interpolated vector's view-space orientation at the not the true view vector's view-space orientation.
> 2 votes

---
Tags: unity, ui-design, hud
---


# Question
Title: How can I find the tangent and normal at an interpolated point on a Catmull-Rom/Hermite spline?
I have an implementation of a simple Catmull-Rom spline. It works, but I'm trying my hardest to be able to place vertices at extrusions along the curve. For this I need the normal (and tangent in the process) to be able to find the correct locations off of the curve. I cannot find any information anywhere, at least nothing that I can understand, on how to quickly calculate the tangent for a given t value on the curve. I've tried to do the derivative myself but I quickly realized I had no idea what I was doing.

How can I find the derivative/tangent/normal for a point at a t value on a Catmull-Rom spline?

Just to be extra clear, here is an incredibly rough picture of what I need.

I need to sample a point at a location along the curve and find an orthogonal vector, represented here by the blue lines. At the end of the blue lines I will place vertices. I have a working implementation of this already but it is for a bezier curve.

# Answer
> 7 votes
OK, I continued fiddling with it and I went ahead and just tried to do the math.

This is the equation I am using for the interpolation between two points:

> (2t³ - 3t² + 1) * p0 + (t³ - 2t² + t) * m0 + (-2t³ + 3t²) * p1 + (t³ - t²) * m1

p0 and p1 are the control points and m0 and m1 are their respective tangents calculated elsewhere.

Previously I said I had no idea what I was doing with the math, but that was only because the derivative route felt *too easy*, so I figured I must have been doing something wrong. I went ahead and tried it and implemented it anyway. This is the formula that results:

> p'(t) = (6t² - 6t)p0 + (3t² - 4t + 1)m0 + (-6t² + 6t)p1 + (3t² - 2t)m1

And wouldn't you know it works! Using this will give you the tangent vector at any interpolated t value on the curve.

From here the conversion to a normal is simple. In my case I'm in 3D and I don't need any special rotation, so I just have to do `Vector3.Cross(Vector3.up, tangent)`, and that gives a vector in a direction orthogonal to the curve on the x/z plane (in Unity).

Here's a visual to show what I was trying to achieve.

You can find some rudimentary source code here.

---
Tags: mathematics, splines
---


# Question
Title: How can I synchronize ocean waves over the network?
I've been performing a little bit of research in my spare time on ways to increase the interactivity of environments in a networked game or simulation.

One of my areas of research is fluid-dynamics and whether it would be possible to synchronize it over the network. I believe the short answer to that is - Yes of course you can. But there will obviously be trade-offs as there are with any network synchronization problem.

I was recently playing Battlefield 4 and a number of their maps have playable ocean areas with fully functional waves large enough to obscure entire boats during gameplay. It seems to work quite well as well.

My assumption here is that the ocean simulation is completely offline and each client performs synchronization with the server during initialization. This would allow all clients to run the exact same ocean simulation that appears to be dynamic but is in fact the same offline simulation every time.

Interaction with the ocean simulation appears to be only superficial with local splash/wave depression. I assume that is entirely local to the client and not synchronized.

**My question here is:**

Would the above be an appropriate way to synchronize fluid simulation over a networked game? If not, what would you suggest?

# Answer
Have you considered generating the waves from a 3d pearl noise generator? That way you can find the height of each wave using just a simple function call with time and exact position, as long as you synch the time across all machines the result should be synchronized waves. Now you only need to send updates whenever one of the waves interacts with something else (well if you do it right you don't even have to do that only when a player interacts with the waves).

So basically use a 3d noise map to generate your waves from and then tread the physics simulair to how you would treat the map (you don't pass the map every frame do you?)
> 3 votes

# Answer
You don't sync the simulation at all. Only the results.

Or in other words: Those waves wouldn't be synced over network (only start/intensity and such). Only things moved by the waves (players, vehicles, etc.) are synced as usual.

The waves themselves are calculated by the clients on their own with details/accuracy based on local settings.

You can't really sync the whole simulation (with all details/elements/nodes) as that would require you to transfer/sync lots and lots of data. If you only have to simulate the surface, consider it being a net or mesh of points.
> 1 votes

---
Tags: physics, networking, water, fluid-dynamics
---


# Question
Title: Inifinite scrolling draggable background for a 2D editor
I need to create something like blender's Node Editor for my 2D editor. Now I am not sure how to create the background so it is static infinite and draggable simillar to blender.

I need to make it so it doesn't wreck my GPU and that its infinite and can be zoomed in and out without a problem

Can anyone give me tips on where to start?

# Answer
This really depends on the complexity of your background as well the technology being used.

For example, when using DirectX or OpenGL, all you have to do is utilizing texture wrapping:

* Let's assume your background texture is 64x64 pixels in size.
* To cover an area that is 640 pixels wide, you'd use texture coordinates ranging from 0 to 10 rather than 0 to 1.
* With texture wrapping enabled, this will show your texture repeated 10 times horizontally.
* The same can be done vertically and when adding some zoom factor.

However, if it's about some grid, you might just want to draw the grid on your own using draw calls. Just make sure you only draw to the visible area of the screen (not everything that might be visible in some way). You could also cache these drawing calls to a texture. Using primitives (like lines) rather than textures has the advantage that you can make it more dynamically, like hiding fine grid lines based on zoom level or possibly even animate them (like flashing some important/active gridline).
> 1 votes

# Answer
You need to use 2 separate background images. When you are scrolling past the boundaries of the first one, you place the second background at the edge to create the *inifinite scrolling* effect. Here is a simple example written in Lua.

For example when scrolling to the right set the position of backgrounds like this:

```
background2.x = background1.x + background1.width

```

This will place background2 at the right edge of background1.

I recommend looking up *scrolling background tutorial* for specific implementations in your development language.
> 0 votes

---
Tags: 2d, editors
---


# Question
Title: Forces on entities: remove all each update step, or remove on demand?
Following the answer to my question here, the way I apply forces on an entity, is each entity has a Map of forces (Vectors) and their IDs. Every update step, the `acceleration` vector is set to the sum of all the forces. Forces can be removed by using their unique ID.

In psuedocode:

```
class Monster extends MovingEntity{
    Vector position, acceleration, velocity;
    Map<String, Vector> forces;
    // .. stuff omitted

    public void update(){
        acceleration = new Vector(0,0); // zeroing the accleration
        foreach force in forces{
            acceleration.add(force);
        }
        velocity.add(acceleration);
        position.add(velocity);
    }

    public void applyForce(Vector force, String id){
        forces.put(id, force);
    }

    public void removeForce(String id){
        forces.remove(id);
    }
}

```

This works fine, but here is my dilemma:

Currently, after adding a force I have to remember to remove it. For example, psuedocode to demonstrate the way player input is handled:

```
if(playerInput.leftPressed()) player.applyForce(new Vector(2,0), "left");
// applyForce() internally deletes the previous force with the same name.
else player.removeForce("left");
// have to remember to remove the force. sometimes a little complicated

```

This can also be annoying e.g. when using steering behaviors. An AI agent may want to `Seek` somewhere, which applies a force on itself. But when it's done Seeking, it must remove the force.

I'm wondering if it would be a good idea to empty the `forces` Map at the end of each update step. In the `update()` method from before:

```
    public void update(){
        acceleration = new Vector(0,0);
        foreach force in forces acceleration.add(force);
        velocity.add(acceleration);
        position.add(velocity);
        forces.empty(); // emptying the forces list
    }

```

Returning to the steering behaviors example, this way an agent doesn't need to remove the `Seek` force when it's done seeking. Each update step, as long as it calls `applyForce(..)`, it will Seek. But the first update step that it doesn't apply a force, there will be no force. All forces are deleted automatically. And since in games forces are constantly deleted and replaced with new ones, I think this seems natural.

---

What is your opinion? Reset all forces each update step? Or have entities and their environment manually remove forces when it's needed?

# Answer
> 2 votes
You could make a distinction between forces and impulses, and use one or the other depending on your needs

A force would stay applied as long as it's not removed (e.g. gravity), while an impulse would only be applied the frame it's sent (e.g. steering impulses).

You would then remove all impulses after each physics update, but keep the forces around.

---
Tags: physics
---


# Question
Title: How to design the attack class in an RPG game?
I am in the planning phase of a small RPG style game.

The character will have have a set of attributes, like strength, agility, etc which are represented as integers. The character also will have a set of attacks represented as an attack class.

On each attack I want it to do damage based on the characters attributes, eg: the attack "sword slash" will do 10 dmg + the value of the characters strength.

The way I was thinking to do this is to have an abstract attack class, which has an abstract Attack method, and for each attack I create one class that implements the Attack method.

```
public class SwordSlash:Attack
{
    public void Attack(Character attacker, Character defender)
    {
        defender.DoDamage(10 + attacker.Strength);
    }
}

```

I see that this will make it a nightmare to maintain.

Does anyone have an idea of how I can accomplish this in a nicer way?

What I think is the main problem is how to input the correct attribute, based on the attack.

# Answer
> 34 votes
You should probably go for a data-driven design here.

Make a generic Attack class which contains the parameters you want to work with - base damage, which stats affects the damage, a set of potential status effects... stuff like that:

```
public enum AttackStat
{
  Strength,
  Agility,
  Intellect
  // etc.
}

public class Attack
{
  private int baseDamage;
  private AttackStat stat;
  private double damageMultiplier;
  // ...and so on

  public void Attack(Character attacker, Character defender)
  {
    defender.DoDamage(baseDamage + attacker.GetStatValue(stat) * damageMultiplier);
  }
}

// Put a method on Character to fetch the appropriate value given an AttackStat:
public int GetStatValue(AttackStat s)
{
  switch(s)
  {
    case AttackStat.Strength:
      return strength;
    case AttackStat.Agility:
      return agility;
    // etc.
  }
}

```

Then, place your attacks in a file, e.g. an XML file, and load the data from there:

```
<Attacks>
  <Attack name="Sword Slash" damage="10" stat="Strength" multiplier="1" />
  <!-- More attacks here -->
</Attacks>

```

You could even extend this to draw values from multiple stats, say, a Fireball where the damage is calculated from both an Intellect and a Fire stat:

```
<Attack name="Fireball" damage="20">
  <StatModifier stat="Intellect" multiplier="0.4" />
  <StatModifier stat="Fire" multiplier="0.8" />
</Attack>

```

If you don't want to use the same basic damage formula for everything (e.g. calculate magic damage differently from physical damage), create subclasses of Attack for each formula you need and override Attack, and specify which type you want in your XML file.

# Answer
> 7 votes
You want to read Aggregate Objects via Components and Game Object Construction Rabbit Hole, from the **Replica Island** blog.

# Answer
> 1 votes
I would have a weapon class that has an attack method which you override with the behaviour you want. You can then also handle how the weapon looks in game, in inventory, how much it sells for etc in the same class.

# Answer
> 1 votes
I'm really new to this, but the way I'd do it is to create a generic attack class.

When one character instance wants to attack another character instance it would create an instance of the attack class, filled with the data required, and the ID of the character that created it. Adjustments from gear would then be applied to the attack object, using data that could be entered in an xml document or similar.

This class instance would then be wrapped inside another class, to provide hooks for the environment to determine range or similar. If the attack is valid the attack instance would be passed to the character being attacked, who would apply the effects.

Hope that made sense.

---
Tags: game-design, rpg
---


# Question
Title: How can I save a global high score for all players in AS3?
I am developing a game in which I want to make a scoring system where the global high score is stored and shared by all players.

I am using Flash and ActionScript 3. Until now I've used `SharedObject.getLocal("savename")` for saving score individualy but I cant figure out the way to store a common high score for all players.

# Answer
> 1 votes
You need to store the high score in some kind of shared persistent storage, either one you provide yourself or one provided by the portal hosting your game (if you are going that route, you'll want to consult their developer documentation; for example Kongregate's documentation on their leaderboards et cetera is here).

If you provide this yourself, you typically use a file or a database. There are projects, such as assql, that provide a mechanism to connect to SQL storage (in this case, MySQL) from ActionScript. You can also use ActionScript's methods for working with external data to hit a URL that is backed by a simply PHP script on your server which talks to a database on the server and recovers the high score. There are a surprising number of tutorials and posts about this scattered around the web, for example, this one.

The advantage to the PHP-based approach is that it puts all your database access on the server, rather than connecting to a DB directly from the client, which helps isolate you from a whole host of problems. You will of course want to further lock this down and make sure that users cannot submit bogus high scores simply by hitting, for example `http://example.org/submitscore?score=99999999999`.

# Answer
> 0 votes
You're going to need some sort of external server for the players to connect to over the internet. SharedObject means "shared between instances on this computer", but players on other computers have no access to this information.

You could do this with your own highscore server, but there are also third-parties that take care of this. I'm no longer familiar with what all is available; I know Mochi used to have a highscore server you could use but I don't know if that is still the case. You could also use the highscore API provided by Kongregate if you publish your game there.

---
Tags: flash, actionscript-3, leaderboards, scoring
---


# Question
Title: Exporting Blender bones' transform matrix
I use this simple python script to export bones transformation:

```
bones = armature.pose.bones
# for eaach bone in bones
SystemMatrix = Matrix.Scale(-1, 4, Vector((0, 0, 1))) * Matrix.Rotation(radians(-90), 4, 'X')
if (bone.parent):
  Export_babylon.write_matrix4(file_handler, "matrix", bone.parent.matrix.inverted() * bone.matrix)
else:
  Export_babylon.write_matrix4(file_handler, "matrix", SystemMatrix * bone.matrix)

```

I'm using a left handed Y up system but I should forget something about rotation because the result is not correct :(

Original (under Blender):

# Answer
OK I found the solution :)

It was related to the inversion of the parent bone. For those who have the same question, here is the final exportation code:

```
def export_bone_matrix(armature, bone, label, file_handler):
  SystemMatrix = Matrix.Scale(-1, 4, Vector((0, 0, 1))) * Matrix.Rotation(radians(-90), 4, 'X')

    if (bone.parent):
        Export_babylon.write_matrix4(file_handler, label, (SystemMatrix * armature.matrix_world * bone.parent.matrix).inverted() * (SystemMatrix * armature.matrix_world * bone.matrix))
    else:
        Export_babylon.write_matrix4(file_handler, label, SystemMatrix * armature.matrix_world * bone.matrix)

```
> 0 votes

# Answer
I am very interested in your bone layout for blender 3D meshes.
Let me guess are you creating meshes and add armature with root bones and
child bones applied to each distinct meshes?
If yes, then
\[1\]For the root bone controlled mesh, how do you position it in your OpenGL
code? By SystemMatrix * armature.matrix\_world * bone.matrix?
\[2\]For the child bone controlled mesh, do you position the mesh in OpenGL
code by (SystemMatrix * armature.matrix\_world * bone.parent.matrix).inverted() *
(SystemMatrix * armature.matrix\_world * bone.matrix) ?

I think for both above are for the final world coordinate of all bones, but
the position of meshes should not be identical to the position of bones which
control them.

Are you just write a simple OnenGL code to position the meshes by bones or you
can make the meshes transformed by the translate, rotate and scale of bones?
If you can succeeded in positioning the meshes in OpenGL by above python-exported
coordinate of bones, then there is no doubt that we can export the coordinate
of each bone in each frame in animation.

However, the Blender native build-in python script comes with it. I'd like to
export the displacement of translate, rotate, scale of each bone in each distinct
frame so that I can then transform the mesh by restoring the transformation matrix.

From within the graph editor in Blender, you can easily tell the all displacement
of transformation - translate, rotate, scale are all measured with respect to the
original value in frame 0. Hence, I believe that I can do it. Do you know how?

Many thanks, mjtsai
> 0 votes

---
Tags: blender, python
---


# Question
Title: Where do I store (or how do I refer to) textures for custom blocks?
I'm making my first foray into Minecraft modding on Ubuntu using Minecraft Forge. I'm finding it a little hard to get started as many of the tutorials seem to refer to older versions of Minecraft (e.g. that use the BaseMod base class, which now appears to be deprecated).

I've created a simple block type:

```
package net.minecraft.block;

import net.minecraft.block.*;
import net.minecraft.block.material.*;

public class RolyBlock extends Block {
    public RolyBlock(int par1, Material par2Material) {
        super(par1, par2Material);
    }
}

```

and added the following static initialiser to the Block class:

```
public static final Block rolyBlock = new RolyBlock(174, Material.rock)
                                      .setHardness(1.5F)
                                      .setResistance(10)
                                      .setStepSound(soundStoneFootstep)
                                      .setUnlocalizedName("rolyBlock")
                                      .setCreativeTab(CreativeTabs.tabBlock)
                                      .setTextureName("roly_block");

```

I created a 256x256 PNG file called `roly_block` and placed it in Forge's MCP folder, in the same location as the other textures. However, when I start Minecraft (v. 1.6.5) via Eclipse, it is unable to locate the texture:

```
2014-03-14 11:38:34 [SEVERE] [Minecraft-Client] Using missing texture,
unable to load: minecraft:textures/blocks/roly_block.png

```

I suspect this is because I put the texture in the directory

```
forge/mcp/temp/src/minecraft/assets/minecraft/textures

```

(where I found the other textures) where this `temp` folder is presumably a decompiled version of the Minecraft 1.6.5 .jar file. I can't actually remember how I ended up with this folder, though.

My question is: how do I add a new texture to my Eclipse mod development environment? Must I rebuild a .jar each time, and if so how? Or can I have Minecraft load textures from a directory?

(I'm a complete Minecraft newbie, so there are many things about the configuration/dev environment for Minecraft that are confusing me. For example if I run recompile.py from Forge's MCP folder, I get a swathe of errors relating to `IconRegister` not being found.)

# Answer
The `String` you pass to `setTextureName()` has a special format which isn't very well documented. If you just pass it a filename such as `roly_block`, it internally gets changed like so.

No mod is specified, so it assumes it's a default Minecraft file, and as you're calling it from a Block class, it knows you're talking about a Block texture and all textures are .png so it becomes:

```
"minecraft:textures/blocks/roly_block.png"

```

Which is then evaluated to the following file:

```
assets\minecraft\textures\blocks\roly_block.png

```

What you should use is the lower case Forge Mod ID followed by a colon, let's assume that's `rolymod`, you'd pass it the string:

```
"rolymod:roly_block"

```

Then in the same way, this will be evaluated to the file:

```
assets\rolymod\textures\blocks\roly_block.png

```

This makes it much easier to keep your assets separated from the defaults as well as other mods. You shouldn't need to rebuild your mod jar to test it either.
> 3 votes

---
Tags: minecraft-modding, assets, resource-management
---


# Question
Title: Can you specify which VBO/EBO to use with glDrawElements?
I'm creating a voxel-like game. I'm not sure if I am using VBO/EBO's correctly. I am creating a new VBO & EBO for every chunk. This is done once, but chunks call a render function in every block inside, and the block calls glDrawElements (Is there a more efficient way?). How can I specify which VBO & EBO each is supposed to use? Is this possible?

Thank you!

# Answer
Regarding "EBOs" that is the only binding that is important at the time that you call `glDrawElements (...)`. That is because a non-zero value assigned to `GL_ELEMENT_ARRAY_BUFFER` means that the pointer you pass to that function will point to memory owned by the buffer object you have bound to `GL_ELEMENT_ARRAY_BUFFER`.

Vertex Buffers are different, you only have to bind a buffer object to `GL_ARRAY_BUFFER` prior to calling `glVertexAttribPointer (...)`. Just like `glDrawElements (...)`, this function will setup a pointer to memory relative to the currently bound `GL_ARRAY_BUFFER`.

However, after `glVertexAttribPointer (...)` returns it no longer matters what is bound to `GL_ARRAY_BUFFER`; you already established what the source of the vertex pointer's memory is and changing the thing bound to `GL_ARRAY_BUFFER` after the fact will not change anything.

Long story short, your vertex pointers specify which VBO(s) is/are used and the `GL_ELEMENT_ARRAY_BUFFER` binding establishes the EBO. You can coalesce multiple buffers into one and then draw specific ranges at a time if you want to do this more efficiently (e.g. fewer buffer object binds). The thing is, buffer object bindings are a really cheap state to change - draw calls become expensive primarily because you change other more complicated things like textures or render targets.
> 2 votes

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


# Question
Title: How can I avoid type checking in the physics side of collision handling?
I have a class responsible for handling the physics side of collisions. When the collision detector spots a collision, it notifies both entities in the collision to take care of gameplay. It also notifies the `PhysicsGenerator` to take car of the physics of the collision.

I don't know if it's possible to avoid type checking in the `handleCollision()` method of `PhysicsGenerator`. What I wanted to do is apply a force on both entities in the collision to push them backwards. But I can only do this if they are `MovingEntities`. What if one of them is a `StaticEntity`? In this case it should be treated differently. I don't know how I can do that without using `instanceof` quite a lot.

How is this usually handled?

# Answer
> 1 votes
The general solution to doing things without type-checking is to move that functionality, in some way, behind an interface.

In this particular case, if both moving and static entities in your physics world shared a common IPhysicsBody interface that supported the ApplyForce method (or was the parameter to such a method), you could apply forces in your collision handling to all entities. Static entities would simply implement ApplyForce such that it did nothing, to reflect their inability to move in response to forces.

In some cases, having "empty methods" mandated by a base class or interface in a subclass is a sign of a poor class hierarchy design. It's hard to say whether this would make that the case for your code without knowing more about it. But that said, another approach is to do away with the concept of static and moveable objects at all, and just make moveability a property: a flag or a special value of mass that represents "infinite mass." Then you simply check for this ApplyForce and early-out. The advantage to this approach (other than a simpler/no hierarchy) is that you can temporarily make objects immobile if needed, which can be helpful.

---
Tags: physics, architecture, software-engineering
---


title: Inverse Explosion with Unity2d

text:
# Question
Title: Inverse Explosion with Unity2d
I am currently trying to make all other objects push away from the player when the player explodes. It currently works, but it pushes close objects a little and far objects very far. What I want is for close objects to get pushed back more than far objects. Here is the current code:

```
function explode () {
var all_rigidbodies = FindObjectsOfType(Rigidbody2D);

for (var r : Rigidbody2D in all_rigidbodies) {
    if (Vector2.Distance(r.transform.position, transform.position) < 6 && r.tag != "Player") {
        var px : float = r.transform.position.x - transform.position.x;
        var py : float = r.transform.position.y - transform.position.y;

        r.AddForce((Vector2(px, py) * 200), ForceMode2D.Force);
    }
}

```

Any ideas on how to inverse the vector or force, or better ways to achieve 2D explosions?

**EDIT:** Ended up just normalizing force so its all the same knockback

# Answer
I think if you change the last line to this it should work.

```
r.AddForce(Vector2(px, py).normalized * EXPLOSION_FORCE / Vector2.Distance(r.transform.position, transform.position));

```

normalize sets the vector to be length 1, then you multiply by some force and divide by the distance, so the further away it is, the less force is given.
> 3 votes

---
Tags: 2d, unity, javascript, physics, rigid-body-dynamics
---


# Question
Title: FBX SDK Getting Tangents and Binormals From a Mesh?
How do I import **tangent** and **binormal** data per vertex from a **FBX Mesh**. I already know how to get *Vertices*, *Normals* and *UVs* but how would I get **tangents** and **binormals**?

For example this is how I would get a vertex.

```
int vIndex = MyFbxMesh->GetPolygonVertex(triangle, vertex);
FbxVector4 Vertex = MyFbxMesh->GetControlPointAt(vIndex);

```

What about tangents and binormals? I searched everywhere on the internet and looked in their documentation but I still can't find a way.

# Answer
> 1 votes
A good link was given here which explains how to get tangents and binormals.

# Answer
> 1 votes
You may want to check the FBX SDK Documentation again. I managed to find `GetElementBinormal(int index)` and `GetElementTangent(int index)`, which are both part of the FBXGeometryBase class, which FBXMesh inherits from. Have you tried these? Because, if the documentation is correct (which, given past experiences, I tend to expect the worst, even with wealthier companies' documentation), those should be what you would need, if the data for the tangents and binormals are included with the mesh data.

To extract the data from the objects these methods return, you'll need to use methods found in `FbxLayerElementTemplate< Type >`, namely `GetDirectArray ()` and `GetIndexArray ()`, unless you want to manipulate the actual array, which there are a few methods in that class for that, as well. You need to look up the inheritance tree with these things, since a lot of the functions will be generalized for multiple class types, and will operate in similar ways on a wide variety of starkly different data structures.

---
Tags: c++, fbx, mesh, import
---


# Question
Title: Keeping ratio the same across devices on fixed screen game
My game is an Android game using OpenGL ES 2.0 (But this question could apply to any platform).

I have read many questions on here regarding ratio management, and also read many tutorials outside of this site, but I'm still really confused as to how to manage this.

My game is a **Fixed screen** 2d platformer. By fixed screen, I mean the player sees the whole screen at once and the screen doesn't scroll. All action takes place on this one screen (kind of like Bubble Bobble). Therefore scrolling is not possible as we need to see the whole play area.

On my development device, I've written everything to look perfect, like so:

What I've currently done is when the game is run on other devices, I resize my GLViewport so that I maintain ratio like so:

Obviously, this has it's own problem - namely, it wastes screen real-estate. Now, I would accept this reluctantly, if I couldn't find a better solution, however, Google's documentation states that it's not allowed (of sorts) see: App uses the whole screen in both orientations and does not letterbox to account for orientation changes.

So, finally, I just stretched it out to fit the screen like so:

This takes the whole screen, but frankly looks a little naff as everything is stretched.

Am I out of options? I see some similar games on the Play Store (ie, fixed screen) and they seem to look *identical* on different screens (and nothing is stretched) **and there doesn't appear to be any extra space**, but I have absolutely no idea how they achieve this. Would love to hear from someone who has dealt with this problem themselves or has any ideas on how best to proceed.

# Answer
You forgot to quote the important part of *FN-U2* for your question (emphasis mine):

> App uses the whole screen in both orientations and does not letterbox to account for orientation changes.
>
> **Minor letterboxing to compensate for small variations in screen geometry is acceptable.**

What you're doing here is perfectly fine, since it indeed can be considered *minor letterboxing*.

Even Google does it as well (e.g. YouTube). You can't avoid this.

What they don't want to see (or you to avoid) is writing apps that would look like they're having a thick black border around the whole screen, e.g. to avoid upscaling.

If you're still unsure, try watching a YouTube video in portrait orientation. You'll notice that they'll fill the available screen space with the video description, suggestions, and comments, rather than leaving that area blank. In this case they don't want the area outside the video to be unused/blank.
> 2 votes

# Answer
So one way you could manage the border drawing scheme is by first rendering some sprites/image using the whole available screen to fill the "no man's land" area not used by the game.

Thinking in therms of OpenGL, you could:

```
// set to the actual screen size in pixels:
int physScreenWidth  = ...
int physScreenHeight = ...

// clear the screen:
glClear(GL_COLOR_BUFFER_BIT);

// set viewport and the projection matrix to the actual physical screen resolution:
glViewport(0, 0, physScreenWidth, physScreenHeight);

float aspect = (float)physScreenWidth / (float)physScreenHeight;
SetProjectionMatrix(aspect, physScreenWidth, physScreenHeight); // pass it to your shader, glOrtho(), whatever...

DrawBackgoundBorder();

```

So lets say the code above drew something like this:

Next you would proceed to draw the actual game on top of it. No need to blend or anything, since we are doing simple 2D. Also important NOT to clear the screen.

```
// set to fixed virtual size the game uses:
int virtualScreenWidth  = ...
int virtualScreenHeight = ...

// size in pixel of the previously drawn border.
int borderWidth  = ...
int borderHeight = ...

glViewport(borderWidth, borderHeight, virtualScreenWidth, virtualScreenHeight);

float aspect = (float)virtualScreenWidth / (float)virtualScreenHeight;
SetProjectionMatrix(aspect, virtualScreenWidth, virtualScreenHeight);

DrawRestOfTheGame();

```

To get as a result something like this:

You can also enable GL scissors to disable rendering outside the virtual game screen area if needed, but as long as you don't draw things on top of the border again, this should not be needed. glScissor works pretty much the same as glViewport, only difference is that you need to enable/disable the global scissors state.
> 0 votes

---
Tags: opengl, viewport, aspect-ratio, screen-management
---