title: How should I plan RPG battle mechanics?

text:
# Question
Title: How should I plan RPG battle mechanics?
I'm working on two RPG battle mechanic ideas. I haven't chosen a game engine yet. Before starting to write code, how should I plan their details?

Should I draw and write on paper? Should I write a specification document? What game mechanic planning processes have others used?

# Answer
> 12 votes
The first (unasked) question is, should you be designing the battle mechanics of an RPG before any code has been written, in the first place? Probably, yes -- but be aware that if you're making an RPG on your own or in a small team, it is not the mechanics or game engine that is the challenging part, but the massive loads of sheer content you have to create in terms of every single level, character, NPC, dialogue tree, weapon, spell, treasure chest... I don't know you or your team, but I run into a lot of students who want to make RPGs because they love to play them, so my first instinct is to make sure you know what you're getting into!

Second, yes, I'd say that getting the game mechanics down on paper is a good first step. A good second step would be putting them in a state where you can actually test them "by hand" without writing code -- paper prototyping, in other words. Play out your combat system (or a simplified version if needed) as a tabletop game and see if it gives the player interesting decisions to make, and modify the mechanics accordingly until you reach the point where it works well. When the mechanics are fun, work on the balancing part, figuring out the exact formulas and numbers in such a way that the game is neither too easy nor too hard from a pure "stats" perspective. That would be a good time to work on the AI as well, to make sure that the enemies are choosing their moves in a way that dovetails with the stats-based challenge level. You can do all of this without writing a line of code, and it's a lot easier to change your mind and try out new mechanics when you can do it in five seconds with a pencil.

# Answer
> 4 votes
You should plan... as much as you need to. What are your goals with the planning? Usability? Edge case testing? Fun factor? Who is your audience for these plans? Is this something you're going to implement yourself later or are you going to be handing this off to someone else?

My recommendation is to look at it from the perspective of the user. What actions can they take at any given point in time. Maybe draw out some storyboards.

If you need to put some more specific thoughts down on paper, sure start doing that. But you should make your system flexible and data-driven enough that you shouldn't necessarily have to sit down and say "spell X does Y damage" before you start making the system since that would probably be best determined through playtesting.

# Answer
> 2 votes
If it's simple enough that you can do so, You should play it out on paper.

Even if it's complicated, with multiple distances, stances, cover, hit locations, what-have-you, you should see if there are any obvious pitfalls, and doing it with pen and paper is probably the fastest way. Run a combat scenario with your battle idea and see how it goes.

Sure, writing a document about it is probably a good idea, it will help you formalize and analyse your ideas, but do not feel constrained by the document.

# Answer
> 1 votes
I usually write systems for pen-and-paper RPGs, so bear that in mind when reading this.

## The Feel

First, I look at what kind of experience I want to create. Is there something I want to emulate? What sort of pace to I want to keep? How punishing should mistakes be? Should a lot of it be up to luck? You don't need (or want?) hard numbers here, but an overview.

## Interaction

Next, I like to think of how the player interacts with the situation. Do they pick from an a list of options in order? Do they expend resources? Do they have to pick their moments? Do they try to change the situation to suit them?

## Flow Charts

I find them quite handy. Map out your combat loop a little. Again, hard numbers are for another pass. Another thing is to plan out how quantities such as strength, damage, action points and so on link together. This is not the combat cycle, but a map of dependancies.

## Simulate

Write out a sample combat using your flow chart. Make up values that feel right, or use placeholders. What happens? Where did the player get to have an influence? Are there any parts where they could get bored, or where things spiral out of control? Could a lucky hit lock the opponent down completely?

## Back to the Charts

Look back at the chart and make any changes you think fit. If you can't follow it at this point, before the implementation intricacies, then it's probably going to be a bit much for a player (remember, you know it better than anyone!). Try pin down a few values.

## Narrow Things Down

I like to jot down a few ideas for containers, data structures (well, the pen-and-paper implementations of them), and ways to tie these back to the feel. I also look at single things which could swing the battle in radically different directions, in terms of experience - it may be worth changing them.

## Don't get too Attached

Sometimes an idea is really awesome, but hard to reconcile with the rest of the system. Rather than discard it entirely it may be worth smashing it to bits, working out why it works, then rebuilding it.

## The Grunt Work

Make a few prototype items, enemies, and so on. Concentrate on modelling archetypes. More complexity can be added later, as can more subtle differences.

Hope that helps.

# Answer
> 0 votes
Since the site doesn't let me upvote or comment Ian Schreiber, +1 to him.

If you intend to test the battle mechanics, a pen&paper test is the way to go. It is also the method recommended by Game Design Workshop: A Playcentric Approach to Creating Innovative Games.

Once you have that done, then you may try to implement it in an actual game (or just look for people interested in making a game to work together).

---
Tags: game-design, game-mechanics, rpg, planning
---


title: Converting from tile to pixel precision

text:
# Question
Title: Converting from tile to pixel precision
I was curious as to how you would go about converting from pixel to tile precision on a tile map. For example, let's say my map is comprised of 8x6 tiles, each of which are 50x50 pixels in size. If I could only get the current coordinates of my mouse in pixels, how would I go about finding which tile those pixels are contained in programmatically?

# Answer
> 2 votes
It's quite simple. Just divide your position with tile dimensions. Like this.

```
tileX = positionX / tileWidth
tileY = positionY / tileHeight

```

this will give you x and y tile, where your position is. This assumes that your top left tile is at 0,0 coordinates.

So, in your case, lets say coordinates are x:256,y:172

```
tileX = x / 50
tileY = y / 50

```

This would result

```
tileX = 5
tileY = 3

```

---
Tags: tiles
---


# Question
Title: Performance problems with many entities in AndEngine
I'm developing a rolling scene based game. I'm loading all the entities from a XML file and create them in the Loading Scene.

I recently increased the game width, and, by doing so, I now have about 300 entities (instead of about 100) in the whole level. This causes a performance problem: the game is "Lagging" \ "jumping" and everything moves slowly.

I'm loading the entities with the "LevelLoader".

I tried to add:

```
levelObject.setCullingEnabled(true);

```

before returning the object in :

```
public IEntity onLoadEntity(final String pEntityName, final Attributes pAttributes){...}

```

and also set Dithering in the engineOptions:

```
engineOptions.getRenderOptions().setDithering(true);

```

but it didn't help...

I'm implementing the sprite created from XML as Matin does in his tutorial:

http://www.matim-dev.com/full-game-tutorial---part-11.html

Is there a better way to handle such a high number of entities? Or is there another way to improve the performance?

# Answer
The good news is that there are many things that you can do. Bad news - there's no magic switch to set to true to make your game run faster.

1. Make sure that whatever you are doing in a loop is optimized. For example if you check in each loop cycle for some difficult condition for each sprite.
2. Dithering won't help you. Please first understand what it does :)
3. Culling helps a lot, but it is turned on by default, so you don't have to turn it on yourself
4. Instead of using many sprites (300 is not that much though), try SpriteBatch. This should help you the most in this case. I suppose you use a lot of entities that look the same. There's when the Sprite batch comes handy.

I expect you now ask: How to use the SpriteBatch? Well the link explains it, so please first go through the code there, try to understand it, implement it and if you hit a wall again, ask a new question specifically about it :)
> 1 votes

---
Tags: android, andengine
---


title: Where to implement textures for tiles?

text:
# Question
Title: Where to implement textures for tiles?
So I just learned the basics of Java and was ready to try to create a protoype game in the style of Civ. So a tile&turn based game.

I created an enum for the different tiles:

```
public enum TerrainTile{

 WATER(1), GRASSLAND(1), HILL(2), FORREST(2), BLANK(99);

private final int id;
private final int moveCost;
private boolean hidden = true;

private TerrainTile(int moveCost) {
    this.id = this.ordinal();
    this.moveCost = moveCost;
}

```

I made a JFrame:

```
public class MainFrame extends JFrame {

private MapPanel pnlMap;

public MainFrame(Terrain map) {

    setTitle("MyGame");
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    getContentPane().setPreferredSize(new Dimension(500, 500));

    pnlMap = new MapPanel(map);
    pnlMap.setPreferredSize(new Dimension(500, 500));
    add(pnlMap);

    pack();
    setLocationRelativeTo(null);

}

public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {

            BufferedImage mapImg = null;
            try {
                mapImg = ImageIO.read(MainFrame.class.getClassLoader().getResourceAsStream("frames/resources/map2.png"));
            } catch (IOException e) {
                e.printStackTrace();
            }

            Terrain map = new Terrain(mapImg);
            System.out.println("Terrain created:");
            map.printTerrain();

            JFrame frame = new MainFrame(map);
            frame.setVisible(true);

        }

```

And a JPanel for the map:

```
public class MapPanel extends JPanel {

private final Terrain map;

public MapPanel(Terrain map) {
    this.map = map;
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

}

```

when I wasn't sure where to save the textures for the tiles. Should I just read out the array of the map and do a switch statement to define inside the MapPanel class which texture to draw or should the textures better be implemented inside the enum?

# Answer
Take a look at this.
It's common to have a single image for all your tiles and draw a different part of it at rendering.
You can then draw your tiles like this :

```
int mx = tileId % numberOfTileCols;
int my = tileId / numberOfTileRows;

graphics.drawImage(image, x, y,
    x + tileWidth, y + tileHeight,
    mx * tileWidth,
    my * tileHeight,
    mx * tileWidth + tileWidth,
    my * tileHeight + tileHeight, this);

```

This way you can store a single texture in the MapPanel but get rid of the huge switch statement.
> 2 votes

---
Tags: java, 2d
---


# Question
Title: LibGDX - draw bullet physics bounding box
I am very new to game development and I am trying to debug my 3d collision bounds. Could somebody give me an example on how to draw the collision bounds of an object in libGDX?

I assume it has something to do with `btIDebugDraw` but I can't find any examples on how to draw them.

# Answer
> 2 votes
You can use the `setDebugMode()` method of the `BulletWorld` class. The argument that you specify is an `int` depicting the mode. For example, you can use `world.setDebugMode(btIDebugDraw.DebugDrawModes.DBG_MAX_DEBUG_DRAW_MODE )` to draw every single debug option available. You can find a list of other modes from Bullet Physic's documentation here.

# Answer
> 3 votes
This approach works well for LibGDX 1.2.0

First of all you must create new instance of `DebugDrawer` and set debug mode you need:

```
debugDrawer = new DebugDrawer();
debugDrawer.setDebugMode(btIDebugDraw.DebugDrawModes.DBG_MAX_DEBUG_DRAW_MODE);

```

Set this drawer to your `btDynamicsWorld` instance:

```
world.setDebugDrawer(debugDrawer);

```

Display debug data in ApplicationAdapter.render() method:

```
debugDrawer.begin(camera);
world.debugDrawWorld();
debugDrawer.end();

```

---
Tags: libgdx, bullet-physics
---


# Question
Title: Irradiance cubemap to spherical harmonics conversion
What are advantages of using spherical harmonics instead of irradiance cubemap? Are there any common used methods for conversion?

# Answer
## General Description

**Quick Note** irradiance maps are the image of the world around a point (environment map) which has been recalculated so each pixel is actually the sum of incident lighting on a surface with a given normal. When given a surface you can use the normal to do a texture lookup to get the indirect illumination value.

OK, so your irradiance cubemap is most likely stored as some form of compressed image.

One common lossy compression method for images is to do a fourier transform on the data and store the results. The fourier transform maps a waveform to a series of functions so we can compress a waveform to a simple set of coefficients. You can look at each colour channel as a waveform from the first pixel to the last which is why this works.

The spherical harmonic is essentially the same thing. The difference is that it's a mechanism for doing this process with functions which lie on a sphere rather than a 2D wave form.

In this respect, they're not really different, they are just different ways of encoding image data. Ofcourse, when we talk about using them we talk like they are completely different things, because we use them differently.

To put this simply, it's not really SH vs I cubemap, we're really talking about irradiance maps stored as spherical harmonics vs irradiance maps stored in a cubemap texture.

## Advantages of SH

If you're using an irradiance map, you probably loading the image in then working with the image uncompressed and doing texture lookup based on surface normal. Typically with SH you are only loading and storing the coefficients and uncompressing the stored image when needed using these coefficients. So it has a smaller memory footprint.

It is, of course possible to map the entire image to a small set of compressed data and use that in the same way, but if you're doing that, spherical harmonics are easier to work with and probably work better given that they are designed for just this kind of data set.

The main impact of this smaller memory footprint is that you can use a lot more of them, so instead of one map for each scene, you can have one set of coefficients for every vertex of every object or cubic volume in the scene - which gives less detail than the environment map but a better representation across the scene geometry as it can vary more.

Of course any advantage really does depend on what you want to get on the screen and what your requirements are.

Check out this paper - "Using an analytic expression for the irradiance in terms of spherical harmonic coefficients of the lighting, we show that one needs to compute and use only 9 coefficients, corresponding to the lowest-frequency modes of the illumination".

In other words, irradiance maps don't vary a lot, they're low frequency, so few coefficients (9 doubles I think) are all thats required in SH to get back to something pretty close to the real irradiance values.

## Map to SH Conversion

There is a directx function available which will do the conversion.

**Note** in some cases people store SH per vertex, in others it's done per world volume (cubemap) and some people do it per volume but storing the light propagating from the volume rather than the light incident to it. I'm sure there are many other ways of storing the light transport in a scene I can't think of and for many reasons I don't know about. So I think, really, it comes down to; what do you want to get from your irradiance and at what level of detail?

## General Links

Good old GPU gems talk about using it.

And here is an excellent document on the topic from Robin Green.

And a personal favourite - Crytek spherical propagation volumes.

A paper from lionhead as well.
> 3 votes

---
Tags: lighting, cubemap, spherical-harmonics
---


# Question
Title: If filled polygon cannot be drawn via libgdx ShapeRenderer , then what is the work around?
I know most of you would suggest me to draw a filled polygon by using combination of triangles and rectangles , but that is not possible for complex shapes . I want to basically draw a generic shape on screen , here it is

The above shape needs to be drawn in generic form , i.e -\> the width of each trapezium's upper edge is fixed . -\> the lower edge of the overall compound shape is a constant unit greater than upper edge. -\> this whole compound shape can have arbitrary length and thus number of individual trapeziums that compose the compound shape is not fixed. I wish to draw each colored trapezium as a filled polygon . Is there any way of achieving this

# Answer
Copied from here: https://stackoverflow.com/questions/15733442/drawing-filled-polygon-with-libgdx

Basically, you define a PolygonSpriteBatch using a PolygonSprite and a PolygonRegion:

```
PolygonSprite poly;
PolygonSpriteBatch polyBatch;
Texture textureSolid;

```

You then create them like this, giving the region a texture and the 4 corners coordinates (for the texture, you can load a plain solid colored texture, gray or red in your case):

```
PolygonRegion polyReg = new PolygonRegion(new TextureRegion(textureSolid),
  new float[] {
    x1, y1,
    x2, y2,
    x3, y3,
    x4, y4
});
poly = new PolygonSprite(polyReg);
poly.setOrigin(oX, oY);
polyBatch = new PolygonSpriteBatch();

```

And draw it like this:

```
polyBatch.begin();
poly.draw(polyBatch);
polyBatch.end();

```

Hope I helped!
> 2 votes

---
Tags: libgdx, android
---


title: Tilemap graphic rendering

text:
# Question
Title: Tilemap graphic rendering
Say i have 10 towns in my world map. the world map right now is just a very large Tilemap. I'm curious as to what the standard is. I think it would be much more efficent to have a Tilemap for each town. If i want to walk from one town to another in the large tilemap I dont have an issue, but how can i do this if i had a Tilemap for each town? when is it best to load the upcoming Towns Tilemap?

# Answer
> 1 votes
Having one large tilemap is certainly the simplest way to go, but as you stated, it would be more efficient to have one for each zone and have the entire map cut down to a couples of square regions. It would allow you to free resources when a region is leaving the screen and reduce the range of the loops needed to draw all the tiles (though this can be easily implemented on a single Tilemap to draw only a portion of it).

To implement multiple Tilemap, you would probably need to save the x, y, width and height of each Tilemap relative to the original big Tilemap. This way, you can do rectangle collision to check if you need to load a given region and with the x and y coordinates, you can draw the tiles to the right cells, even when drawing multiple tilemaps.

Summary: It would be more efficient, but you would have to add systems to detect whether or not a givent TileMap needs to be loaded and drawn. The simplest solution would be to stick with the large Tilemap. And always remember this programming quote: "If it's not broken, don't bother fixing it". As long as the large Tilemap works and don't reduce the performances significantly, don't change it.

---
Tags: java, tilemap
---


title: Tilemaps and colour overlays

text:
# Question
Title: Tilemaps and colour overlays
I am currently developing an isometric tile game for android. I am currently working on how I to handle rendering the tiles in an efficient way. So I was wondering about the possibility of using a small set of grey-scale tile images with different coloured overlays, rather than many coloured tile images.

Has this been done before? Is it do-able in android? How would it affect efficiency?

# Answer
I don't know what you want to use to render the games, but in general, that is possible. In Monogame for example it is just changing the "Color.White" to the color you want (e. g. Color.Green) What you are trying to archive in the image above won't be possible using a pure tile-based approach: Some tiles on the border between the green and the original are split. I guess you have to make a zig-zag border so it doesn't go through tiles, but only through the spaces between those tiles. The water (I guess it's water in the top corner?) would also be rendered on it's own, because the behavior is quite confusing: when viewed in the original, it is gray (which is logic), but then, it turns blue on the green overlay. So you have to implement the water differently from the tile system (or at least store the color of the water somewhere, most of the rendering code can be shared for sure)
> 2 votes

---
Tags: android, tilemap, isometric
---


# Question
Title: How to add a constant horizontal force just like gravity?
I want to add a constant horizontal force, just like gravity to a projectile or a sphere moving in 3d space, which will make the projectile or ball or sphere or whatever be influenced by this force so that it will curl in the direction of the constant horizontal force. I have this code which will add force to the object on swiping the screen, but it doesnt drift/curl or whatever you may call it:

```
var anglex : float;
var angley : float;
var elevationAngle : Vector3;

function FixedUpdate () {
    if(Input.touchCount>0 && Input.GetTouch(0).phase == TouchPhase.Ended)
               {
                    var touchdeltaposition: Vector2 = Input.GetTouch(0).deltaPosition;
                    anglex = touchdeltaposition.x * Time.deltaTime *2.0;
                    angley = touchdeltaposition.y * Time.deltaTime *5.0;
                    Debug.Log(angley);
                    elevationAngle = Vector3(anglex,angley,0);
                    rigidbody.velocity = transform.TransformDirection(Vector3(anglex,angley,angley ));
                    var elevation : Vector3 = Quaternion.Euler(elevationAngle) * transform.forward;
                    rigidbody.AddRelativeForce(elevation);
                  }
           }

```

I feel this is simple, but I'm just not able to turn the crank.

# Answer
You add a constant force by doing pretty much what you're doing already.

The problem you're likely having is a debugging one, or your expecting more force to be added then you're actually adding. Keep in mind that if you want the force to affect the object, you'll probably want to apply a larger force when the touch has ended.

Remember that how much the object moves from the force is dependent on the mass of the object, so you'll probably want to ensure the mass of the object isn't too high as well.
> 1 votes

# Answer
All you need is the object to have a velocity. Then, every tick you add your force (gravity) to it's velocity, and add your velocity to it's position.
> -1 votes

---
Tags: unity, vector, physics
---


# Question
Title: Bullet physics weird behavior. Jittering and drifting with btBoxShape
I'm dropping a simple box onto a plane from 100 units and my solution using Bullet Physics is giving me some weird behavior. The dimensions of the box are {2, 4, 1}.

When the box hits the ground it jiggles up and down, drifts off to the side, and finally settles by sinking 1.5 units into the ground.

When I reduce the fall height to about 5 units the box doesn't sink into the ground, and the sideways drift is less pronounced.

When I declare a `btSphereShape` instead of a `btBoxShape` the problems go away. It should be noted that I'm developing for iOS with Objective-C file that interphases my code with Bullet.

Here's my code:

```
- (void)setUpPhysicsWorld { //This sets up the physics world and plane shape:

    collisionConfiguration = new btDefaultCollisionConfiguration();
    dispatcher = new btCollisionDispatcher(collisionConfiguration);
    broadphase = new btDbvtBroadphase();
    solver = new btSequentialImpulseConstraintSolver;
    dynamicWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);

    btTransform t;
    t.setIdentity();
    t.setOrigin(btVector3(0, 0, 0));
    btStaticPlaneShape *planeShape = new btStaticPlaneShape(btVector3(0, 1, 0), 0);
    btMotionState *motion = new btDefaultMotionState(t);
    btRigidBody::btRigidBodyConstructionInfo info(0.0, motion, planeShape);
    btRigidBody *planeRigidBody = new btRigidBody(info);
    dynamicWorld->addRigidBody(planeRigidBody);
    [self addBlock];

}

- (void)addBlock {

    btTransform t;
    t.setIdentity();
    t.setOrigin(btVector3(0, 5, 0));

    /* Actual declaration of the box shape. For some reason, when I change this
    to a btSphereShape, all the problems go away. */
    btBoxShape *boxShape = new btBoxShape(btVector3(1, 2, 0.5));
    btVector3 inertia(0, 0, 0);
    boxShape->calculateLocalInertia(1.0, inertia);

    btMotionState *motion = new btDefaultMotionState(t);
    btRigidBody::btRigidBodyConstructionInfo info(1.0, motion, boxShape, inertia);
    blockRigidBody = new btRigidBody(info);
    dynamicWorld->addRigidBody(blockRigidBody);

}

- (GLKVector3)getBLockLocation {

    dynamicWorld->stepSimulation(1/60.f, 10, 1/300.0);

    btTransform trans;
    blockRigidBody->getMotionState()->getWorldTransform(trans);

    return GLKVector3Make(trans.getOrigin().getX(), trans.getOrigin().getY(), trans.getOrigin().getZ());

}

```

Can anyone tell me what's wrong here?

# Answer
> 1 votes
Maybe try giving the objects and/or the plane some friction:

```
btRigidBody::btRigidBodyConstructionInfo info(1.0, motion, boxShape, inertia);
info.m_friction = 0.9f;
blockRigidBody = new btRigidBody(info);

```

---
Tags: ios, objective-c, bullet-physics
---


# Question
Title: sdl: unlock mouse in fullscreen mode and make it useable on another monitor
Is it possible to unlock the mouse in fullscreen mode so that you can use it on a another monitor? I read trough the SDL documentation, but I couldn't find anything related to my problem.

# Answer
> 1 votes
This is for SDL 2, but have you showing the cursor cursor and seeing if it can escape?

function for creating a cursor:

```
int SDL_ShowCursor(int toggle)

```

so it would be like this

```
SDL_ShowCursor(1);

```

look more into it here:

http://wiki.libsdl.org/SDL\_ShowCursor?highlight=%28%5CbCategoryMouse%5Cb%29%7C%28CategoryEnum%29%7C%28CategoryStruct%29

personally I do not have a second monitor so I cannot help you

# Answer
> 1 votes
In SDL 2 there is also `SDL_Get/SetWindowGrab` which returns/sets whether or not the window is grabbing the mouse. I think this is what you want.
https://wiki.libsdl.org/SDL\_SetWindowGrab?highlight=%28%5CbCategoryVideo%5Cb%29%7C%28CategoryEnum%29%7C%28CategoryStruct%29

# Answer
> 1 votes
For SDL2 (don't use SDL1 anymore):

```
// to configure the window
SDL_SetWindowFullscreen(my_window, SDL_WINDOW_FULLSCREEN_DESKTOP);

// to unlock the mouse
SDL_SetWindowGrab(my_window, false);
SDL_SetRelativeMouseMode(false);

// to lock the mouse
SDL_SetWindowGrab(my_window, true);
SDL_SetRelativeMouseMode(true);

```

That first sets the window to the "fake" fullscreen that is just a resolution-sized borderless window. This is necessary on Windows and some Linux setups to have a mouse cursor that can freely enter and leave the window on a multi-monitor setup.

---
Tags: c++, sdl
---


title: Reducing the level of detail of a mesh

text:
# Question
Title: Reducing the level of detail of a mesh
I am importing an extremely detailed mesh (provided by a client) and it consists of something like 16 million triangles. For rendering performance I've been using the ID3DXMesh interface's Optimize and OptimizeInPlace methods. I'm using GenerateAdjacency with an epsilon of around 0.0025, and there doesn't seem to be much optimizing going on. Even with an epsilon of around 50.0 there's no significant increase in performance.

Am I misunderstanding Optimize? Isn't it supposed to get rid of unused faces based on the adjacency buffer? If that isn't the case, what other methods/algorithms/libraries could I use that would reduce level of detail?

Here's my code:

```
this->m_pMesh->GenerateAdjacency( 0.0025f, l_ulpAdjacencyBuffer );
this->m_pMesh->OptimizeInplace( D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT |D3DXMESHOPT_VERTEXCACHE, l_ulpAdjacencyBuffer, 0, 0, 0);

```

# Answer
The short answer is "Poly count is not what Optimize is optimizing".

The D3DXMesh Optimize routine performs the following

(1) It attribute sorts the mesh, which means ensuring all faces sharing the same attributes are grouped together. Any shared vertices that appear in multiple attribute groups are duplicated.

(2) Faces are optimized for the post-transform vertex cache per the algorithm in this paper. This primarily reorders the faces into strips of triangles paying attention to the vertex cache size. This reorders the index buffer.

Hoppe, H.; "Optimization of mesh locality for transparent vertex caching", ACM SIGGRAPH 1999 Proceedings. Link

(3) Vertices are optimized for the pre-transform vertex cache which means the vertex buffer is sorted in order of use by the associated index buffer

BTW, there's a shared-source version of many of these methods available on CodePlex in the DirectXMesh library including the mesh optimization algorithm mentioned above.

No where in here does it 'simplify' the mesh or reduce polygon count. As a side-effect of this optimization, degenerate faces and unused vertices are removed. But that's it. You could use the legacy D3DX9 D3DXSimplfyMesh function which uses vertex and edge decimation, but I don't know how great it will work on your meshes.

For games and other real-time scenarios, most folks build custom level-of-detail models or use a commercial tool like SimplyGon.
> 1 votes

# Answer
It seems you have a contradiction in requirements.

You have not given me much to go, but I'll hazard a guess: you're working with medical or other scientific data that is being supplied in an outrageously inefficient format (as medical or scientific data tends to be).

The client needs to be able to import any model of their choosing in your simulation, whether it's 1,000 or 10,000,000 triangles. This implies that the renderer should be optimized to handle those large polycounts, by chunking or streaming the model or perhaps some other clever hacks.

But the simulation should also run in real-time.

If you are not allowed to touch the client's data, this seems an impossible task. If the client supplies Wavefront .obj's for example, the textual data could run into the hundres of megabytes. All that has to be read and parsed before even being transmitted to the videocard.

A much better solution would be to supply the client with a model converter. This converts their models (.obj) to your format (optimized binary), leaving the client's data intact while you're able to run the simulation in real-time. A good starting point would be to look at Horde3D's binary representation. The engine is open source and the binary model format is really quite good. Bonus: a converter already exist to go from COLLADA to Horde3D.

As for your original question: there are many algorithms that will optimize a model's polycount for you, but they are very context-specific. What works for one situation (triangulated data from voxels) might not work at all for another situation (architectural prototype exported from AutoCAD).
> -1 votes

---
Tags: c++, directx9
---


title: How to efficiently change VBO size?

text:
# Question
Title: How to efficiently change VBO size?
I have created a menu class and now I'm working on getting it to render using OpenGL's VBO's. The menu is fairly simple, it has a number of buttons, the user can press up and down to highlight the desired button and then press ENTER to go to the selected buttons sub-menu which is just another instance of my menu. It should be noted that it doesn't need to have the same amount of buttons as the previous one. Pretty basic.

What I've come up so far is this:

```
//setting up the buffers and variables
int amountOfVerticesButtons = this.menu.getCurMenu().getNoButtons() * ShapeRenderUtils2D.VERTICES_RECT;
FloatBuffer vertexBufferButtons = BufferUtils.createFloatBuffer(amountOfVerticesButtons * VERTEX_SIZE);
FloatBuffer colorBufferButtons = RenderUtils.createColorBuffer(0.5f, 0f, 0.5f, amountOfVerticesButtons);

int amountOfVerticesBorders = this.menu.getCurMenu().getNoButtons() * ShapeRenderUtils2D.VERTICES_FRAME;
FloatBuffer vertexBufferBorders = BufferUtils.createFloatBuffer(amountOfVerticesBorders * VERTEX_SIZE);
FloatBuffer colorBufferBorders = RenderUtils.createColorBuffer(0.3f, 0f, 0.45f, amountOfVerticesBorders);

//filling up the buffers
for (int i = 0; i < MAX_BUTTONS_PER_PAGE && i < menu.getCurMenu().getNoButtons(); i++) {
    //buttons
    vertexBufferButtons.put(ShapeRenderUtils2D.getRectVertices(new Point(point.x, point.y + (i * (BUTTON_HEIGHT + BUTTON_SPACING))), MENU_WIDTH, BUTTON_HEIGHT));

    //button borders
    vertexBufferBorders.put(ShapeRenderUtils2D.getFrameRectangle(new Point(point.x, point.y + (i * (BUTTON_HEIGHT + BUTTON_SPACING))), MENU_WIDTH, BUTTON_HEIGHT));
}

vertexBufferButtons.flip();
buttons_handles = RenderUtils.createHandles(vertexBufferButtons, null, colorBufferButtons, amountOfVerticesButtons);

vertexBufferBorders.flip();
borders_handles = RenderUtils.createHandles(vertexBufferBorders, null, colorBufferBorders, amountOfVerticesBorders);

```

This code is run once in the constructor and it sets up the VBO for my buttons, and creates a color array with one color for each button.

My question is:

When the user presses ENTER, a new menu becomes active. The new menu doesn't have to have as many buttons as the previous one, so the old VBO is worthless, because it is of different size. I detect that the menu changes and what I basically do is to run the above code again, for the new menu, but at the end before I flip and create Handles I first do:

```
RenderUtils.deleteHandles(buttons_handles);
RenderUtils.deleteHandles(borders_handles);

```

Which removes the handles to the old VBO's. And then I create new ones just like I did the first time, but this time with correct size.

This seems very ineffective. Is there a better way to do it? Is there a better way to change an existing VBO's size?

EDIT: Please note that I've got everything else done with the menu. I only have problems with the VBO rendering. Also, there may be a very large amount of buttons, with many sub-menus that also contain large amounts of buttons, so creating a separate VBO for each case is not possible.

# Answer
By no means you need to recreate the buffers every time. Why don't you create all your buttons once and then draw them as needed? Buttons are immutable things.

Suppose you had a class `Button`, that incorporates all the stuff needed to draw a button, such as textures and the vertex buffer:

```
class Button {

    Texture texture;
    VertexBuffer buttonVerts;
    ...

    // draw this button using OpenGL.
    void draw(float x, float y);

    // load a file that describes this button's layout.
    // also loads texture and creates the vertex/index buffers.
    void init(string filename);
}

```

You only need to create your button "templates" once, and then every menu can share them. Supposing each button can be loaded from a file that describes its layout:

```
Button pushButton = new Button();
pushButton.init("push_btn.xml");

Button radioButton = new Button();
radioButton.init("radio_btn.xnl");

etc ...

```

That only have to be done once. Then you just distribute them to the menus:

```
// Menu with 2 push-buttons and a radio-button
Menu menu1 = new Menu();
menu1.addButton(pushButton);
menu1.addButton(pushButton);
menu1.addButton(radioButton);

```

And when the menu is drawn, all you will have to do is iterate the menu buttons and draw them:

```
function Menu.draw()
{
    // draw the menu background, etc...

    // now draw each button:
    for each Button btn in menuButtons
    {
        btn.draw(pos.x, pos.y);
    }
}

```

**EDIT:**

So, initially I misunderstood the difficulty the OP was having. The issue was how to pack all vertexes pertaining the buttons in a single VBO and draw them separately.

For indexed geometry, a good option would be to use `glDrawElementsBaseVertex`, which allows the specification of a vertex offset (`basevertex`) of where to start drawing.

For unindexed geometry (raw triangles and triangle-strips/fans), the approach is even simpler. `glDrawArrays` takes a `first` parameter which is the initial vertex to start drawing from. So the drawing of a button would become something in the lines of:

```
GLint firstBtnVertex = (vertsPerButton * buttonIndexInVBO);
glDrawArrays(GL_TRIANGLES, firstBtnVertex, vertsPerButton);

```
> 1 votes

---
Tags: opengl, java
---


# Question
Title: Picking a local origin as the centroid of given three points in 3D
Given three points non-collinear `P`, `Q`, `R` in 3D, I need a generic method to generate `x'`, `y'`, `z'` unit vectors that behave like origin of local coordinate system.

`x'` and `y'` vectos should be on the plane that is defined by `P` `Q` and `R`.

The part that I could not figure out was:
After calculating the centroid `C`, I can pick `x'` as `normalize(vec(PQ) + vec(PC))` but could not figure out how to generate `y'` and `z'`.

The method should be generic. I know this is possible without rotations etc. but how?

I'm going to write a program in Java, so I'd appreciate answers with step-by-step.

# Answer
The cross product of two vectors is a vector orthogonal to them both. If you have two vectors contained in a plane, the cross product of them gives you the vector that is normal to that plane. Knowing that, you can construct your desired coordinate system by exploiting that property.

Let's start finding two vectors defining your plane. For example, PQ and PR. We can already take one of them as your x' vector, but any vector inside that plane would be correct. You want it normalized:

```
x' = normalize( PQ )

```

As I said, the cross product of these vectors gives you a normal to that surface. If we normalize it, we can already call it z'

```
z' = normalize( PQ x PR )

```

The missing vector is orthogonal to the other two, I am assuming that you want to define an orthogonal coordinate system. And because both of them are already of length 1, no need to normalize it:

```
y' = x' x z'

```

This will give you one of all the possible coordinate systems that match the criteria: orthogonality, unit-length, x' and y' contained in the plane and z' normal to that plane.

(Note: I am using "x" to denote the cross product of two vectors, and "x'" to name one of the vectors in this exercise. I hope it's not too confusing)
> 1 votes

---
Tags: java, 3d, geometry
---


# Question
Title: LibGDX Box2DLights shadow offset problem on bodies
Hello I just started to use LibGDX, and it's awesome. I looked at the Box2DLights library, and started to learn how the lighting work here.

I got something up:

<sub>(source: gyazo.com)</sub>

As you can see, it works, but the shadow of the sprite goes over itself, and doesn't start in the right place.

Why is it doing this? is it possible to set offsets?

This is how I initialize them:

```
    this.texture = new Texture("sprites/water.png");
    this.camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    this.camera.setToOrtho(false);
    this.renderer = new SpriteBatch();

    this.map = new TileMap(20, 20);
    this.map.generateAllSame(new Texture("sprites/sprite.png"));

    this.world = new World(new Vector2(), true);

    this.createBodies();

    RayHandler.setGammaCorrection(true);
    RayHandler.useDiffuseLight(true);
    this.ray = new RayHandler(this.world);
    this.ray.setAmbientLight(0.2f, 0.2f, 0.2f, 0.1f);
    this.ray.setCulling(true);
    this.ray.pointAtLight(50, 0);
    this.ray.setBlurNum(1);
    camera.update(true);
    this.spriteLight = new PointLight(ray, 128);
    this.spriteLight.setDistance(500f);
    this.spriteLight.setPosition(150, 150);

    this.spriteLight.setColor(new Color(0.5f, 0.8f, 0.7f, 1f));
    this.spriteLight.setSoftnessLength(0);
    this.spriteLight.setSoft(true);

public void createBodies() {
    CircleShape chain = new CircleShape();
    chain.setRadius(10);

    FixtureDef def = new FixtureDef();
    def.restitution = 0.8f;
    def.friction = 0.01f;
    def.shape = chain;
    def.density = 1f;

    BodyDef body = new BodyDef();
    body.type = BodyType.DynamicBody;

    for (int i = 0; i < 3; i++) {
        body.position.x = 40 + MathUtils.random(500);
        body.position.y = 40 + MathUtils.random(500);

        Body box = this.world.createBody(body);
        box.createFixture(def);
        this.bodies.add(box);
    }
    chain.dispose();
}

```

And my rendering:

```
public void render() {
    handleInput();
    camera.update();
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    renderer.setProjectionMatrix(camera.combined);

    renderer.disableBlending();
    renderer.begin();
    this.map.render(renderer);
    renderer.draw(texture, 50, 50);

    renderer.enableBlending();

    for (Body body : this.bodies) {
        Vector2 pos = body.getPosition();
        renderer.draw(texture, pos.x + amount, pos.y);
    }
    renderer.end();

    ray.setCombinedMatrix(camera.combined, camera.position.x, camera.position.y,
            camera.viewportWidth * camera.zoom, camera.viewportHeight * camera.zoom);

    ray.update();
    ray.render();

}

```

What did I do wrong?

# Answer
> 5 votes
This is less a problem with Box2dLights, and more a problem with setting up Box2d collision fixtures to match your sprites.

The Box2dLight rays are colliding with the CircleShape fixture you attached to the box2d body.

```
CircleShape chain = new CircleShape();
chain.setRadius(10);

```

Instead, this should be a Polygon shape with the same dimensions as your box, like this:

```
PolygonShape shape = new PolygonShape();
shape.setAsBox(width/2, height/2);

```

It also looks like your sprite has some transparent space surrounding it. The center point of your circle fixture is not matching up with the bottom left of your sprite. I would either modify the picture file or add an offset to the fixture so it matches.

You should also convert your pixel coordinates to something smaller for Box2d. Right now your circle shape has a radius of 10 meters. Box2d is not built to simulate very large or very small objects. 10 meters is within the tolerance, but if you go over 50 meters box2d can have undefined behavior. Check out the http://www.box2d.org/manual.html section 1.7 Units for more information.

---
Tags: opengl, java, libgdx, box2d
---


# Question
Title: Normals in my skinned model are not animated
I have a blender skinned mode with animation. Normals look like they are messed up. This is how it looks in Unity3D before and after animation.

As you can see, my model should be lit up just like the cube next to it. When I apply Armature modifier in blender, my model looses animation and its locked in particular position, but the light on that model works.

My question is: The normals are set as they would be for a static model, not for a animation. Why are normals not animated ?

# Answer
> 1 votes
I would suspect there is a way to setup the normals within your animation tool so that you don't have to mess with them in Unity, but it turns out there's a simple setting when you import the model. Go to the Inspector and look in the Model tab, and set the Normals property to Calculate (it defaults to Import).

(There is also a code command to calculate normals, but that's exactly the same as doing it through the import settings.)

# Answer
> 0 votes
Unity animations do not animate changes to mesh details. Animations are only pos-rot-scale of nodes. Unity's skinned mesh renderer uses animations of nodes to deform meshes. How Unity deforms your mesh can be slightly different than Blender's deformation. Unity is trying to do the right thing given the armature animation and the mesh weights for the nodes of the armature.

How are you animating the normals in Blender anyway? The armature in Blender isn't supposed to deform normals like the first screenshot you gave.

---
Tags: unity, animation, blender, normals
---


# Question
Title: GLM/OpenGL: How Can I Prevent Vector Magnitude From Increasing While Rotating Bones in Skeletal Rig?
***ANSWER AT THE BOTTOM OF THIS QUESTION***

I have been reading tutorials, articles, questions on StackExchange and books all with the subject of skeletal rigging. I have boiled my program down to just the essentials and I still experience the same situation.

Currently, I have a root joint, a child bone of the root, and a child of the child. Each child's rotation is relative to its parent. The first one rotates to the proper angle (the second overshoots the goal), but as they rotate, the vectors (vertices) they affect seem to increase in magnitude. They have translated and then rotated it seems.

There are 3 dots. Red is the root joint. Green should represent the end of the first bone. Blue should represent the end of the second bone. The basic pose is to have all bones at an angle of 0 radians, so will lie upon the positive x axis starting from the origin:

As I rotate the first bone, the vertex veers away from the origin, but is at the correct angle of PI/2 Radians (90 Degrees) and the second bone follows:

Now I rotate the last bone, and the corresponding vertex veers even further than the first. However, this one has rotated more than the intended PI/4 Radians (45 Degrees) relative to the parent:

The code I used to calculate the transformation follows.

**OpenGL 3.2 Core, Main.cpp:**

```
GLfloat meshVertices[] = // Vertex (X, Y, Z), Color (R, G, B), Joint/Bone Index
{
    0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
    0.2f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
    0.4f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 2.0f
};

GLuint meshElements[] =
{
    0, 1, 2
};

glm::mat4 _matRoot = glm::mat4(); // Load Identity
_matRoot = glm::translate(_matRoot, glm::vec3(0.0f, 0.0f, 0.0f)); // Translate to Local Origin (In Relation to MODEL)
_matRoot = glm::rotate(_matRoot, 0.0f, glm::vec3(0.0f, 0.0f, 1.0f)); // Root does not need rotation
_matRoot = glm::translate(_matRoot, glm::vec3(0.0f, 0.0f, 0.0f)); // Translate to Length of Bone (ZERO for root)

glm::mat4 _matBase = _matRoot; // Inherit Parent Transform
_matBase = glm::translate(_matBase, glm::vec3(0.0f, 0.0f, 0.0f)); // Translate to Local Origin (In Relation to PARENT)
_matBase = glm::rotate(_matBase, PI / 2, glm::vec3(0.0f, 0.0f, 1.0f)); // Rotate 90 Degrees About Z Axis
_matBase = glm::translate(_matBase, glm::vec3(0.2f, 0.0f, 0.0f)); // Translate to Length of Bone (x=0.2f is same as mesh vertex)

glm::mat4 _matEnd = _matBase; // Inherit Parent Transform
_matEnd = glm::translate(_matEnd, glm::vec3(0.0f, 0.0f, 0.0f)); // Translate to Local Origin (In Relation to PARENT)
_matEnd = glm::rotate(_matEnd, PI / 4, glm::vec3(0.0f, 0.0f, 1.0f)); // Rotate 45 Degrees About Z Axis
_matEnd = glm::translate(_matEnd, glm::vec3(0.2f, 0.0f, 0.0f)); // Translate to Length of Bone (x=0.2f is same as mesh vertex)

vector<glm::mat4> _matSkeleton(3); // Sent to Shader
_matSkeleton[0] = _matRoot;
_matSkeleton[1] = _matBase;
_matSkeleton[2] = _matEnd;

```

**GLSL 1.50 Core, Vertex Shader:**

```
in vec3 position;          // From Mesh - Vertex (XYZ)
in vec3 color;             // From Mesh - Color  (RGB)
in float bone;             // From Mesh - Bone Index
out vec3 Color;            // To Fragment Shader
uniform mat4[3] transform; // From glm::mat4 Vector (Bone transforms)

void main()
{
    gl_PointSize = 10.0f;
    Color = color;
    int Bone = int(bone);
    gl_Position = transform[Bone] * vec4(position, 1.0);
}

```

I have tried numerous changes to the translations, attempted different combinations of transforms, added and subtracted transforms. I have recompiled this code a couple of hundred times over the last couple days. This is as close as I have come to any success.

**BEGIN EDIT**

Here I have provided my method of sending data to the shaders:

```
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);

glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(meshVertices), &meshVertices, GL_STATIC_DRAW);

glGenBuffers(1, &ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(meshElements), &meshElements, GL_STATIC_DRAW);

GLuint shaderAttributePosition = glGetAttribLocation(shaderProgram, "positon");
GLuint shaderAttributeColor    = glGetAttribLocation(shaderProgram, "color");
GLuint shaderAttributeBone     = glGetAttribLocation(shaderProgram, "bone");

glEnableVertexAttribArray (shaderAttributePosition);
glBindBuffer              (GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer     (shaderAttributePosition, 3, GL_FLOAT, GL_FALSE,
                           7 * sizeof(GLfloat), (void*)(0 * sizeof(GLfloat)));

glEnableVertexAttribArray (shaderAttributeColor);
glBindBuffer              (GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer     (shaderAttributeColor, 3, GL_FLOAT, GL_FALSE,
                           7 * sizeof(GLfloat), (void*)(3 * sizeof(GLfloat)));

glEnableVertexAttribArray (shaderAttributeBone);
glBindBuffer              (GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer     (shaderAttributeBone, 1, GL_FLOAT, GL_FALSE,
                           7 * sizeof(GLfloat), (void*)(6 * sizeof(GLfloat)));

```

And the Uniform:

```
GLint uniTrans = glGetUniformLocation(shaderProgram(), "transform");
glUniformMatrix4fv(uniTrans, _matSkeleton.size(), GL_FALSE, glm::value_ptr(_matSkeleton[0]));

```

**END EDIT**

**2nd EDIT (WITH ANSWER)** By mapping out the transformation on graph paper, traversing the steps in reverse from result to original point, I was able to figure out the exact steps needed to answer my question. Instead of just building on my matrices with functions, I created several different matrices, each with their own part of the transform (rotation, translation). I then multiplied the matrices together to get the final result.

I re-coded the mathematics in the test source with success. I also removed the root bone and rebased the bones origins. Point one is now at the center and is not transformed in the example. The second point (Green) is transformed by a bone with its origin at the global origin. Finally, the third point (Blue) is transformed by a bone with its origin set to its parent's origin, plus the parent's length along the x axis (x axis being 0 degrees in this example). All further children will follow the pattern as the second bone. I then implemented this back into my main engine and it works flawlessly! Below is the updated math calculations.

The line comments should help anyone else who happens to Google themselves onto this question. Should anyone wish for further explanation, feel free to comment and I will explain what this all means.

```
// PRECOMPUTED VALUES
float       PI  = 3.1415926535897932384626433832795f;
float       PI2 = PI / 2.0f; // 90 DEGREES
float       PI4 = PI / 4.0f; // 45 DEGREES
glm::vec3   RAx = glm::vec3(0.0f, 0.0f, 1.0f); // ROTATIONAL AXIS
glm::mat4   I   = glm::mat4(); // IDENTITY MATRIX

// BONE ONE
glm::mat4   R   = glm::rotate   (I, PI2, RAx); // ROTATION MATRIX (90 DEG AROUND Z)
glm::mat4   O   = glm::translate(I, glm::vec3(0.0f, 0.0f, 0.0f)); // MOVE TO LOCAL ORIGIN
glm::mat4   T   = glm::translate(I, glm::vec3(0.0f, 0.0f, 0.0f)); // MOVE BACK TO GLOBAL SPACE
glm::mat4   B1  = T * R * O; // LOCAL ORIGIN, ROTATE, GLOBAL SPACE, PARENT TRANSFORM (NON EXISTANT IN THIS CASE)

            R   = glm::rotate   (I, PI4, RAx); // ROTATION MATRIX (45 DEG AROUND Z)
            O   = glm::translate(I, glm::vec3(-0.2f, 0.0f, 0.0f)); // MOVE TO LOCAL ORIGIN
            T   = glm::translate(I, glm::vec3(0.2f, 0.0f, 0.0f)); // MOVE BACK TO GLOBAL SPACE
glm::mat4   B2  = B1 * T * R * O; // LOCAL ORIGIN, ROTATE, GLOBAL SPACE, PARENT TRANSFORM

boneOne = B1;
boneTwo = B2;

```

**END 2nd EDIT**

# Answer
By mapping out the transformation on graph paper, traversing the steps in reverse from result to original point, I was able to figure out the exact steps needed to answer my question. Instead of just building on my matrices with functions, I created several different matrices, each with their own part of the transform (rotation, translation). I then multiplied the matrices together to get the final result.

I re-coded the mathematics in the test source with success. I also removed the root bone and rebased the bones origins. Point one is now at the center and is not transformed in the example. The second point (Green) is transformed by a bone with its origin at the global origin. Finally, the third point (Blue) is transformed by a bone with its origin set to its parent's origin, plus the parent's length along the x axis (x axis being 0 degrees in this example). All further children will follow the pattern as the second bone. I then implemented this back into my main engine and it works flawlessly! Below is the updated math calculations.

The line comments should help anyone else who happens to Google themselves onto this question. I will also edit my question to include the answer. Should anyone wish for further explanation, feel free to comment and I will explain what this all means.

```
// PRECOMPUTED VALUES
float       PI  = 3.1415926535897932384626433832795f;
float       PI2 = PI / 2.0f; // 90 DEGREES
float       PI4 = PI / 4.0f; // 45 DEGREES
glm::vec3   RAx = glm::vec3(0.0f, 0.0f, 1.0f); // ROTATIONAL AXIS
glm::mat4   I   = glm::mat4(); // IDENTITY MATRIX

// BONE ONE
glm::mat4   R   = glm::rotate   (I, PI2, RAx); // ROTATION MATRIX (90 DEG AROUND Z)
glm::mat4   O   = glm::translate(I, glm::vec3(0.0f, 0.0f, 0.0f)); // MOVE TO LOCAL ORIGIN
glm::mat4   T   = glm::translate(I, glm::vec3(0.0f, 0.0f, 0.0f)); // MOVE BACK TO GLOBAL SPACE
glm::mat4   B1  = T * R * O; // LOCAL ORIGIN, ROTATE, GLOBAL SPACE, PARENT TRANSFORM (NON EXISTANT IN THIS CASE)

            R   = glm::rotate   (I, PI4, RAx); // ROTATION MATRIX (45 DEG AROUND Z)
            O   = glm::translate(I, glm::vec3(-0.2f, 0.0f, 0.0f)); // MOVE TO LOCAL ORIGIN
            T   = glm::translate(I, glm::vec3(0.2f, 0.0f, 0.0f)); // MOVE BACK TO GLOBAL SPACE
glm::mat4   B2  = B1 * T * R * O; // LOCAL ORIGIN, ROTATE, GLOBAL SPACE, PARENT TRANSFORM

boneOne = B1;
boneTwo = B2;

```
> 0 votes

# Answer
Depending on your compiler, when you divide PI in your calculations then the result could be interpreted as either a float or an int. From what I recall, the C++ standard demands that the result of an arithmetic operation on basic data types will always have the same signature as the left hand operand. However, not all compilers follow the standard. Because of this, the result could be rounded up in the case of an int, causing your scale to increase as well. Try writing "PI / 2.0f" and "PI / 4.0f" instead.
> -1 votes

---
Tags: opengl, matrix, skeletal-animation, glm, rigging
---


title: Line of Sight with Bresenham

text:
# Question
Title: Line of Sight with Bresenham
I have a simple function to determine whether an entity can see another, in a top-down tile-based game (this is actually a tiny bit more complex in my game, to determine whether to see the first block, but I simplified it for this example):

```
public static boolean canSee(int x, int y, int x2, int y2, Area area) {
    Array<Tile> blocks = new Array<>();
    Utils.Bresenham.Plotter plotter = (x1, y1) -> {
        Tile t = area.getTileAt(x1, y1);
        if (t.blocksView()) {
            blocks.add(t);
        }
    };

    Utils.Bresenham.line(x, y, x2, y2, plotter);

    return blocks.size == 0;
}

// Example below:

P = player, E = enemy, B = block

.....
.....
.....
P.B..
B...E

```

Now the problem I have is that in this position, the enemy can see the player, but the player cannot see the enemy (because the most top 'B' blocks the Bresenham).. and I'm not sure what's a good way to fix this.

# Answer
If you use an algorithm like Bresenham, where the two lines can be different, depending on their start- and end-position, you then have to either:

* Plot both lines and use the result of both plots for your LoS calculation.
* Plot only one line (for example always from Player to Enemy) and use this one LoS calculation for both entities.
> 5 votes

---
Tags: java, line-of-sight
---


title: Get position of Fixtures

text:
# Question
Title: Get position of Fixtures
I'm constructing a `Body` (a **box2d** body using **AndEngine**) using multiple `Fixture`s and later I need to get the world position of these `Fixture`s.

Currently I am trying something like this;

```
// Declarations
Body body;
Fixture centerFixture;
Fixture leftFixture;
Vector2 centerPos = new Vector2(0, 0);
Vector2 leftPos = new Vector2(-1.5f, -1.5f);

void setup() {
  BodyDef bodyDef = new BodyDef();
  bodyDef.type = BodyType.DynamicBody;
  bodyDef.position.set(new Vector2(10, 10));

  body = physicsWorld.createBody(bodyDef);

  PolygonShape centerShape = new PolygonShape();
  centerShape.setAsBox(1, 1, centerPos, 0);
  FixtureDef centerDef = new FixtureDef();
  centerDef.density=1;
  centerDef.shape=centerShape;
  centerFixture = body.createFixture(centerDef);

  PolygonShape leftShape = new PolygonShape();
  leftShape.setAsBox(0.5f, 0.5f, leftPos, 0);
  FixtureDef leftDef = new FixtureDef();
  leftDef.density=1;
  leftDef.shape=centerShape;
  leftFixture = body.createFixtureleftDef);
}

void someFunction() {

  Transform transform = body.getTransform();
  Vector2 temp = new Vector2(leftPos);

  // These two seems to not be the center of the fixture
  Vector2 worldPosition = transform.mul(temp);
  Vector2 pixelPosition = new Vector2(worldPosition.x * PhysicsConstants.PIXELS_PER_METER, worldPosition.y * PhysicsConstants.PIXELS_PER_METER);
}

```

But is seems that as the `body` rotates the `worldPosition` is off.

How do I get the world position of the `Fixture`?

# Answer
> 2 votes
As I understood your question, you want to get the coordinates of the points of your body relative to the world, in other words, following the transformations applied to the body.

I did this function not long ago, I hope this will help you and guide you towards an answer:

```
public Vec2[] getPoints() {
    Vec2[] v = new Vec2[shape.getVertexCount()];
    for (int i = 0; i < shape.getVertexCount(); i++) {
        v[i] = body.getWorldPoint(shape.getVertex(i));
        v[i].x *= world.getMeter();
        v[i].y *= world.getMeter();
    }
    return v;
}

```

Here I used a PolygonShape for my body, but you can replace this by the vertices of your ficture, I think. What's important is that function:

```
body.getWorldPoint(shape.getVertex(i));

```

This will return a point of the body (Ex: (0, 0)) and return the same point with the transformations applied (Ex: (1, 0) if you rotated 90° clock-wise).

---
Tags: java, box2d, andengine
---


# Question
Title: Unity Material constructor not applying Shader
I am proceedurally generating a generic game object and trying to make it transparent using the default diffuse transparency shader.

```
meshRenderer.materials[0]=new Material(Shader.Find("Transparent/Diffuse"));
meshRenderer.materials[0].color = new Color(0f,1f,0f,0.05f);

```

Just seems to make it Default-Diffuse, but if I do this

```
meshRenderer.materials[0]=new Material(Shader.Find("Transparent/Diffuse"));
meshRenderer.materials[0].shader = Shader.Find("Transparent/Diffuse");
meshRenderer.materials[0].color = new Color(0f,1f,0f,0.05f);

```

It works just fine and I get transparency. The Material constructor looks like it takes the exact same shader, but it doesnt seem to be applying. Why? I am already explicitly inluding the shader in the project settings.

# Answer
> 2 votes
You can change material of your gameObject using:

```
renderer.material = new Material(Shader.Find("Transparent/Diffuse"));
renderer.material.color = new Color(0f,1f,0f,0.05f);

```

which seems to work fine. I was searching unity3d forums and found this which also seems to work fine. Here's the code for the same:

```
var meshRenderer = GetComponent<MeshRenderer>();
var mat = new Material(Shader.Find("Transparent/Diffuse"));
mat.color = new Color(0f,1f,0f,0.05f);
var matArray = new Material[]{mat};
meshRenderer.materials = matArray;

```

---
Tags: unity
---


# Question
Title: Skybox: OpenGL texCUBE vs a textured cube
In OpenGL, the typical way that I've seen to set up a skybox using cubemapping is to create a cube in camera space, prepare a cubemap sampler with the appropriate six-sided texture, and then in the pixel shader use the camera space direction of the pixel as the input to texCUBE. What I'm wondering is, if instead of this, I set up the same cube, but then simply textured each face of the cube with the appropriate face of the cubemap texture, and then rendered the cube with a standard shader, would it achieve the same visual effect?

# Answer
> 0 votes
The only difference you would have is that you are doing texture lookup based on UV instead of direction.

This would mean that each cube vertex would need a uv or you would need a routine to calculate the appropriate uv based on the view direction ... which is basically us back at using texCUBE, with the exception that texCUBE is probably going to be more efficient that anything added as a function in the shader.

So, yes that would be the same in look, and probably about the same in actual performance, but texCUBE will likely always be slightly faster.

I did this once with a textured sphere - because I happened to have a textured sphere already, obviously drawing a sphere is slower than drawing a cube because there are more vertices.

---
Tags: opengl, shaders, cubemap, skybox
---


title: Dealing with multiple licenses

text:
# Question
Title: Dealing with multiple licenses
I came across an asset with 3 different licenses. The GPL 3.0 license appears to just be a newer version of the GPL 2.0. Can the GPL 2.0 be disregarded if the GPL 3.0 is complied with?

Must all conditions from all 3 licenses be met? For example, the GPL 2.0 mentions printing or displaying an appropriate copyright notice, but this seems to be absent from the CC BY-SA 3.0 license.

# Answer
> 18 votes
According to Open Game Art's FAQ:

> You must follow only one of the licenses. However, when you re-distribute/edit, you are encouraged to include/use all of the licenses, so the license spectrum (and thus sum of people/projects who can use the art) doesn't shrink.

\[Source\]

# Answer
> 6 votes
The asset is offered under different license conditions. It is your choice under which of these terms you would like to license it.

Regarding your question about the GPL 2.0 and 3.0 compatibility: No, the versions 2 and 3 of the GPL are generally not compatible. However, you need to pay close attention to the wording of the copyright message. If the work is licensed under *"GNU GPL Version 2.0"* it is nailed down to version 2.0 for all eternity. But when it reads *"GNU GPL version 2.0 **or any later version**"*, you are allowed to "upgrade" the work to GPL 3.0 (or a version 4.0 which might exist some day). Some projects trust the Free Software Foundation to still know what they are doing in the future and use the "or later version" wording, while other projects (like the Linux kernel, for example), don't want to risk giving the FSF a carte blanche to introduce a new license which can then automatically be applied to their software.

The Free Software Foundation also has a handy table regarding combining different GPL licenses. When reading that table, you might wonder if using an asset counts as use of a library or as copying code. That's a very good question. The GPL is designed for program code, not for artwork, which makes it quite hard to interprete in that context.

# Answer
> 0 votes
About the GNU Public License (GPL) version x.
It's clearly mentioned in GPLv2 and GPLv3 declarations that you must apply this version or, at your option, newer of the license.

> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

Source - How to use GNU licenses for your own software

So; the parts of your program using **only** GPLv2 submitted code could be redistributed under GPLv2 or under GPLv3, if you want. The parts using **only** GPLv3 under GPLv3.

And so, your program should be redistributed under GPLv3, since GPLv3 contains everything GPLv2 contains plus added content.

And since there is 3 licenses; I think you should apply the GPLv3 on your program, plus the other license, and, as long as the licenses do not interfere with each other; you probably should apply both (GPLv3 and CC).

If the license interfere with each other; you better should contact CC's admins, the GNU's admins (or the Free Software Foundation?) and Open Game Hearth admins.

I'd recommend to put all the sources and headers under GPLv3, the documentations as well. And all the arts (drawings and such) under the CC license.

---
Tags: assets
---


# Question
Title: Determine Mesh Vertex Index Given Another Mesh Index
Please bare with me as I explain what I am trying to accomplish :P

Each 'X' below represents a mesh vertex:

For my Unity3d GameObject (G1); the mesh vertices are stored in a C# List object in the following order. \*Note the mesh index 'A'. This is a value I know - in this case A=16 (mesh index 16).

I have another GameObject (G2) whose shape is the same (a simple rectangle) but the mesh vertices are ordered differently.\*Note the mesh index 'B'. This is a value I dont know and I want to find this value (mesh index) - in this case B=17 (mesh index 17).

As you can see the mesh arrangement is pretty much the same except rotated 90 degrees. If I know the 'mesh vertex index' of A how can I find the 'mesh vertex index' of B?

**Whats an algorithm that can calculate the mesh index of B?** My attempt is not working at all:

```
uint A     = 16;
uint nCols = 6;
uint nRows = 4;

// Technically both B and A sit on Row 3, Column 5 so if I can find A's row and column maybe I am there?
uint aCol = 16 / nCols;        // nup not right
uint aRow = (16 % nCols) - 1;  // gives 3

// Once I've calculated aCol and aRow its easy
uint B    = (aRow * nRows) + aCol;  // ie, (3 * 4) + 5 = 17

```

# Answer
I think that you got the most part right except by the fact of aCol and aRow is swapped.

```
// the mod operation will give a number ranging from 0 to nCols-1 so there's no need to
// subtract 1.
uint aCol = 16 % nCols;
uint aRow = 16 / nCols; // this value must be less than nRows

// The B get swapped as well because of the rotation of the matrix
// uint B    = (aCol * nRows) + aRow;
// but is not quite right yet, since the aRow counts ftom top to bottom therefore
uint B    = (aCol * nRows) + (nRows - aRow - 1);

```

Hope it helps. If the mesh arrangement is arbitrary you will need a more complex code than this one.
> 1 votes

---
Tags: unity, logic, mesh
---


# Question
Title: How are red dot/reflex/holographic sights implemented?
In first-person-shooters like Call of Duty, the hologram only appears when it is behind the glass portion of the sight.

In OpenGL, would it be implemented by rendering the glass to the stencil buffer and then rendering the hologram, but masked by the stencil buffer?

# Answer
i think you mean the 3 dimensional offset of the holographic sight that is positioned relative to the actual frame. i think the best way to simulate the reflected projection of the dot / cross is to offset a sprite from the glass a little bit to the front of the gun ( but still ceeping it inside the frame / housing of the sight ). Also render it from the viewers side only. that way the holograph appears to be projected and positioned depending on the view angle. I hope that makes sense.
> 1 votes

# Answer
Calculating UV in vertex shader:
uv.xy = mul(world2object, cameraWorldPos-mul(object2world, (0,0,0,1)))+(0.5,0.5)
> -3 votes

---
Tags: opengl, graphics, graphics-programming, first-person-shooter, masking
---


# Question
Title: how did coordinate-handling in old flightsimulators work?
Im currently working on a combat flight simulator pure for own fun. Using a floating-origin i thought the float inprecision was history, however this was the case untill i tried adding multiplayer to the game.

The server is authorative and i'm banging my head around positioning the players on the server and handling the gun hits and collisions.

Using sectors i reset the origin of the clients but the server keeps the original position. This will lead into float inprecisions on the server, thus physic and collision checking are terrible.

Now i'm just wondering how games like Airwarrior, Warbirds and aceshigh overcame these problems. What approach did they use? I'm assuming something else. If only i was able to use double precision, or even fixed point, but i'm tied to a physics model working with floats. I don't feel like changing that around, unless i have no other option.

Thanks for any pointers.

stephan

# Answer
Not sure how those games solved it. But I just read the write up of how Dungeon Siege solved this for multiplayer was to keep things in their local region space and for each frame, turn things to a local space based off one region.

Therefore you don't have a single numerical space for the whole game.

You should take to time to read the write up. Super interesting.
> 2 votes

---
Tags: multiplayer, floating-point
---


# Question
Title: Creating Direct2D PathGeometry from XAML format
Is it possible to create a Direct2D PathGeometry object from a XAML string (or from any other vector format) or do I have to create such a parser myself?

# Answer
Well I wasn't able to find if a straight conversion from a Xaml string to a Direct2D Geometry object exists. I used this SE answer to build my own version. It works by parsing the markup and converting the resulting instructions to GeometrySink commands.
> 0 votes

---
Tags: 2d, directx11, wpf, vector-art, direct2d
---


# Question
Title: How do I apply 2 rotations about different points to a single primitive using OpenGL
I'm working on a 2D top-down shooter game that has a rotation feature like Realm Of The Mad God such that if you press e the camera rotates around the character in a clockwise direction and q rotates the camera around the character in a counterclockwise direction. I have this working with my floors and walls by translating to the character, doing the screen rotation, and drawing everything with the character as the origin. The problem arises when I shoot projectiles which need to both rotate around the character and rotate around themselves (shooting uses the mouse cursor so I can shoot at any angle). For example, if the screen is not rotated and I'm shooting rectangular projectiles, I want them to face in the direction I'm shooting (rotation around themselves). However if I only do this rotation, when I then rotate the screen the projectiles will always shoot at the same position because my cursor position does not change. Therefore I need to also either rotate the projectiles around the character or rotate the mouse cursor position to get the correct position (which would then totally screw up all of the collision detection). Likewise if I only do the screen rotation on projectiles, the rectangles will always be facing the same way and they would only look correct if I were shooting straight up or straight down.

So my question is, how can I perform 2 rotations on a primitive around 2 different points? The only way I can think of is to translate to the character and do the screen rotation, then somehow calculate the translation required to move back to the middle of the projectile (seeing as how my axes are now rotated) and do its rotation. Or am I thinking about this in the wrong way and there is a different solution to accomplishing this effect?

# Answer
> 1 votes
Since your game is 2D, I will assume, as I read in your comments, that there is no "camera". I will assume that you have a view rotation around the player called viewRot.

Your player is the center of rotation as well as the center of the bullet. We will first rotate the bullet around itself because it seems logic to me to apply self transformations before others. To do so you will need the following (written in pseudo-code):

```
Translate to (0, 0), so apply translate(-x, -y)
Rotate by the bullet angle, rotate(bAngle)
Translate back to its position, translate(x, y)

```

Then we need to rotate around the player. To do so, we will translate not to (0, 0) but to the position of the player, here pX and pY:

```
translate(-pX, -pY)
rotate(viewRot)
translate(pX, pY)

```

At the end, you may need to translate the bullet's position relative to the view (if any).

It is in the end pretty simple, you only need to apply two rotation-around-point transformations. If you want more specific code, just leave a comment.

# Answer
> 0 votes
Lets say you have the character at (x,y) position with some theta rotation.

Similarly, you have the camera in the background at (x,y) + r\*(cos(phi),sin(phi)) (plus a z value where you want the camera to hang in) looking at the character direction (x,y)

This way, you shoot the projectile relative to your character

```
 (x,y) --> (x,y) + time*velocity*(cos(theta),sin(theta))

```

which is automatically "rotated a second time" from the camera perspective.

I think the problem is that you're not storing this original "theta" with respect to the character, but rather with respect to the camera.

Normally you apply a single rotation to get the coordinates in the "world coordinates" and the "second rotation" is automatically applied from choosing your camera location and its view direction.

A solution would be something like:

```
projectile bullet = projectile(hero.x, hero.y, hero.theta);
...
bullet.x += frameChangeInTime*bullet.velocity*cos(bullet.angle);
bullet.y += frameChangeInTime*bullet.velocity*sin(bullet.angle);

```

The camera will take care of the "second rotation" since we're placing the projectile in the world coordinates.

---
Tags: opengl, rotation
---


title: OpenGL - Buffer Usage

text:
# Question
Title: OpenGL - Buffer Usage
I am currently working on a little OpenGL project. At the moment I am trying to find a good solution for rendering multiple objects. I have set up a terrain with its own buffers, which works just fine. Now I am at a stages where I want to fill this terrain with game-objects (tree, rock, ...) I already programmed the .obj loader for 3D models. But now the question: Is it good to have for each game-object its own buffers(vertices-buffer, indices-buffer, ...) and enable these each draw-call ? For me it seems a bit weird having like 100+ buffers in the v-ram and enable these after each other. Is this the way buffer should be used? Or should I combine these (small) buffer to a few (big) ones ?

# Answer
The prevalent advise is fewer big buffers are better. Ideally one buffer big enough to hold everything. This also allows you to use 1 VAO per vertex layout. Along with persistently mapped buffers, it makes for a powerful GPU memory management in your application.

However, it does burden you with extra work to ensure your data is aligned correctly, that you don't overwrite data that's currently in use and that you calculate the correct offsets for things such as starting element and vertex.

However, using 1 or 2 buffers per object with a VAO to tie it all together is probably easier for small applications, which don't need the efficiency or out-right performance.
> 5 votes

---
Tags: opengl, performance, opentk
---


# Question
Title: Is game maker studio actually flexible enough to cater to an avid programmer?
After I got burned by RPGMaker which seemed fine what with the semi-open Ruby-like engine until you encountered some nasty surprises like the draconian resolution limitations etc., I've become more cautious.

I've heard a lot of good things about Game Maker and that it is now more flexible towards developers who actually want to get into the nitty gritty and push the limits, but I've also read that their scripting language GML isn't yet capable of things like object oriented design patterns.

I don't really want to get burned again by spending cash on something that may possibly not meet my expectations, and I feel I might be suckered in by the pretty wrapper.

That being said, while I'm feeling currently more comfortable in Java, the question about whether or not libraries such as libgdx and slick2d can offer me more freedom than game maker would be silly and rhetorical, instead what I ask is, **is Game Maker currently up to snuff to hold a candle to more-programming-oriented libraries such as libgdx or slick2d?**

Also, if I try out the free version of game maker would it accurately reflect the possibilities and perhaps even the limitations of the full priced product?

# Answer
**Short answer**: no.

**Long answer**: Game Maker's performance are really bad. If you are a good programmer, **you will find yourself hitting the performance wall more than once** or pay for the YYC (Yoyo COmpiler) which unlocks decent performances at a price. Libraries like libGDX, slick2D, LWJGL or any other will beat GameMaker by a lot.

**Object oriented patterns in GameMaker are not so bad**. You can create instances that derives from another and most of the basics of OOP are present. Still, it is not as flexible as the other options you stated and does not cover the whole OOP capabilities.

On the flexibility side, it is poor too, but performance and flexibility has never been the goal of Game Maker. It was **an engine made for beginners and for those who want to learn how to program**. Other libraries like libGDX, LWJGL or Slick2D are more complex to get working and to program but offer a lot more flexibility. On the other hand, GameMaker wins for the simplicity and by far.

The free version is nice and easy to use and, yes, you will have a good idea of the general product with it. They released a new free Game Maker Studio: Standard with all resources unlocked, which is nice.

In the end, GameMaker can compete with libGDX, LWJGL Slick2D or any other library, but only for beginners or people who want to simply make a game without complicating their lives with libraries. If you want performance and flexibility and can afford the complexity added by libraries, I would avoid GameMaker.

*Source: 10+ years of programming in GameMaker 5, 6, 7 and 8. When I tried Studio, it didn't look that different to me, sadly.*
> 5 votes

---
Tags: java, 2d, game-maker
---


title: LibGDX Z index for groups

text:
# Question
Title: LibGDX Z index for groups
Have three groups, `A`, `B` and `C`.

Let `B` and `C` be children of `A`.

Now set

```
B.setZIndex(3)
C.setZIndex(2)

```

Why is `C` drawn **over** `B`, if `B` has a greater Z index?

If you do this:

```
C.setZIndex(2)
B.setZIndex(3)

```

It works. However, I want to set `B`'s index before I set `C`'s. So, what's up?

(I know that `C` is drawn over `B` because each group contains an image)

# Answer
> 4 votes
**NEW ANSWER**

Found it. In the method setZIndex(), this line is the one that moves the children:

```
children.insert(index, this);

```

So the Z index is not a "true" z index which represents the depth, but the index of the children in the parent's children array. So if you try to put a child at position 3 in the array when there are only 2, it will be put at the end. Same when you try to put it at position 2.

If you want a correct ordering, you will then have to put them at positions 0 and 1, no more, no less, or else the results will be counter-intuitive.

**EDIT**: To apply this to your problem, then you put an actor at index 2, libGDX tries to put the actor at position 2 in the array. 2 being too big for the array, it puts it at the end. Same for 3. So that is why it is always the last one to call setZIndex that will be put last, and drawn in front. If you use 0 and 1, like I said, everything will work expectingly.

**EDIT 2**:

**Summary**: It is not a conventional Z-Index, it is the index in the ArrayList. If you try to place B or C in a cell that does not exist, like 2, 3, -1, etc., then the results will not be what you want.

To put it more simply, you have to understand how ArrayLists work. ArrayList are indexed just like arrays, starting at index 0 and incrementing by one each time a value is added. In your case, You have a group A that contains a ArrayList of children containing B and C. B is (probably) the first one in the list, placing it at index 0. C is at index 1.

If you call setZIndex(0) on C, then A will replace index 0 by C and push B at index 1. Simple as that. B will then be drawn on top of C.

But if you call setZIndex(3) on B, A cannot place B at index 3 because it is too far in the list, there is no cell 3. Instead, it places it at the end of the list, at index 1. Then you call setZIndex(2) on C and the same thing happens. A will, in the end, place C at index 1, pushing B at index 0. C will be drawn on top of B.

Source: https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/scenes/scene2d/Actor.java

**OLD ANSWER**

Simply because Z index is depth. The more depth, the further it is. An instance with less depth will be drawn on top of one with more depth.

EDIT: Look at it like this. Your screen is index 0. Past your screen, behind it, is positive depth. In front of it, it is negative. If you put your hand in front of your screen, it has a smaller depth, but it renders in front.

---
Tags: libgdx
---


# Question
Title: Generating transformation matrix for 2D camera with pan/zoom/rotate
# Question

How do you implement a camera with pan/zoom/rotation for a 2d game? Is it acceptable to multiply together a series of transformation matrixes to generate a final transformation matrix that is applied to the vectors/vertices in a scene, or is there a more efficient way?

# Overview

Working on a 2d game in löve2d I recently tried implementing a camera class that allows for panning/rotation/scrolling.

I tried finding a good resource for how to implement such a 2d camera, but was unable to find one that covered all three degrees of movement, and so I came up with my own solution.

I would like some feedback on if this is a good approach, and how it could be optimized/improved upon.

# My Attempt

My camera object stores the following values:

1. *position*: (`Vector2`)(World-Space position relative to the origin)
2. *angle*: (`float`)(how much the world is rotated, in radians)
3. *zoom*: (`float`)(the zoom factor, 1 = normal, 0.5 = 2x zoom, etc)
4. *offset\_center*: (`Vector2`)(center the camera on the point of rotation using `[screen_width/2,screen_height/2]`)
5. *offset*: (`Vector2`)(any additional offset away from the center of rotation, typically just `[0,0]`

Whenever a camera value changes (basically each frame) I run `camera:computeMatrix()` which calculates its transformation matrix:

```
Camera.computeMatrix = function (self)

    local m_pos = Matrix{ -- World-space Position
        {1, 0, self.position.x},
        {0, 1, self.position.y},
        {0, 0, 1}
    }

    local m_zoom = Matrix{ -- Zoom
        {self.zoom, 0, 0},
        {0, self.zoom, 0, 0},
        {0, 0, 1}
    }

    local m_rot = Matrix{ -- Rotation
        {math.cos(self.angle), math.sin(self.angle), 0},
        {-math.sin(self.angle), math.cos(self.angle), 0},
        {0, 0, 1}
    }

    local m_offset = Matrix{ -- Screen-space Offset
        {1, 0, self.offset_center.x + self.offset.x},
        {0, 1, self.offset_center.y + self.offset.y},
        {0, 0, 1}
    }

    self.matrix = nil
    -- reverse order than when applying them 1 by 1
    self.matrix =  m_offset * m_rot * m_zoom * m_pos
end

```

So once `Camera.matrix` is calculated as a 3x3 matrix, I apply that to a given vertex/vector:

```
Vector2.TransformM = function (v, m)
    -- m is a 3x3 matrix of format {{a,b,c},{d,e,f},{g,h,i}}
    return Vector2(v.x*m[1][1]+v.y*m[1][2]+m[1][2], v.x*m[2][2]+v.y*m[2][2]+m[2][3])
end

```

An example of this implementation:

Download (pan with WASD, rotate with Q/E, zoom with 1/2)

# Answer
> 1 votes
Sorry for late answer - I originally jumped on the love IRC where I was pointed towards love.graphics's Coordinate Functions which allows you to modify love's coordinate system to do exactly what I wanted. Credit also to NauticaMile for suggesting hump.camera, which uses this as the underlying implementation.

This example replaces my original hardcoded transformation matrices with the relevant love.graphics functions. Using this my original program ended up being 3-5 times faster, but it could certainly be more optimized:

```
-- CANVAS METHODS --
Camera.attach = function (self)
    local cx, cy = love.graphics.getWidth()/(2*self.scale), love.graphics.getHeight()/(2*self.scale)
    love.graphics.push()
    love.graphics.scale(self.scale)
    love.graphics.translate(cx, cy)
    love.graphics.rotate(self.rot)
    love.graphics.translate(-self.pos.x, -self.pos.y)
    return self
end
Camera.detatch = function (self)
    love.graphics.pop()
    return self
end
Camera.draw = function (self, func)
    self:attach()
    func()
    self:detach()
end

```

To use it you can do something like `Camera:draw(World:draw())` in your `love.draw` call, where `World:draw()` could be any function that draws something to the screen.

You can download an updated version of my original project here.

---
Tags: 2d, camera, lua, transformation, love2d
---


title: Update and render in separate threads

text:
# Question
Title: Update and render in separate threads
I'm creating a simple 2D game engine and I want to update and render the sprites in different threads, to learn how it is done.

I need to synchronise the update thread and the render one. Currently, I use two atomic flags. The workflow looks something like:

```
Thread 1 -------------------------- Thread 2
Update obj ------------------------ wait for swap
Create queue ---------------------- render the queue
Wait for render ------------------- notify render done
Swap render queues ---------------- notify swap done

```

In this setup I limit the render thread's FPS to the update thread's FPS. Besides I use `sleep()` to limit both render and update thread's FPS to 60, so the two wait functions won't wait much time.

The problem is:

The average CPU usage is around 0.1%. Sometimes it's go up to 25% (in a quad core PC). It means that a thread is waiting for the other because the wait function is a while loop with a test and set function, and a while loop will use all your CPU resources.

My first question is: is there another way to synchronise the two threads? I noticed that `std::mutex::lock` don't use the CPU while it is waiting to lock a resource so it isn't a while loop. How does it work? I can't use `std::mutex` because I will need to lock them in one thread and unlock in another thread.

The other question is; since the program runs always at 60 FPS why does sometimes its CPU usage jumps to 25%, meaning that one of the two wait is waiting a lot? (the two threads are both limited to 60fps so they ideally won't need a lot of synchronisation).

Edit: Thanks for all the replies. First I want to say I don't start a new thread each frame for render. I start both update and render loop at the beginning. I think multithreading can save some time : I have the following functions: FastAlg() and Alg(). Alg() is both my Update obj and render obj and Fastalg() is my "send render queue to" renderer" ". In a single thread :

```
Alg() //update
FastAgl()
Alg() //render

```

In two thread:

```
Alg() //update  while Alg() //render last frame
FastAlg()

```

So maybe multithreading can save same time. (actually in a simple math application it does, where alg is a long algorithm amd fastalg a faster one)

I know that sleep isn't a good idea, although I ve never have problems. Will this will better?

```
While(true)
{
   If(timer.gettimefromlastcall() >= 1/fps)
   Do_update()
}

```

But this will be a infinite while loop that will use all the CPU. Can I use sleep(a number \< 15) to limit the usage? In this way it will run at, for example, 100 fps, and the update function will be called just 60 times per second.

To synchronise the two threads I will use waitforsingleobject with createSemaphore so I will able to lock and unlock in different thread (whitout using a while loop), won't I?

# Answer
> 29 votes
For a simple 2D engine with sprites, a single-threaded approach is perfectly good. But since you want to learn how to do multithreading, you should learn to do it correctly.

## Do not

* Use 2 threads that run more or less lock-step, implementing a single-threaded behavior with several threads. This has the same level of parallelism (zero) but adds overhead for context switches and synchronization. Plus, the logic is harder to grok.
* Use `sleep` to control the frame rate. Never. If someone tells you to, hit them.
First, not all monitors run at 60Hz. Second, two timers ticking at the same rate running side by side will always eventually get out of sync (drop two pingpong balls on a table from the same height, and listen). Third, `sleep` is *by design* neither accurate nor reliable. Granularity may be as bad as 15.6ms (in fact, the default on Windows\[1\]), and a frame is only 16.6ms at 60fps, which leaves a mere 1ms for everything else. Plus, it's hard to get 16.6 to be a multiple of 15.6...
Also, `sleep` is allowed to (and will sometimes!) return only after 30 or 50 or 100 ms, or an even longer time.
* Use `std::mutex` to notify another thread. This is not what it's for.
* Assume that TaskManager is any good at telling you what's going on, especially judging from a number like "25% CPU", which could be spent in your code, or within the usermode driver, or somewhere else.
* Have one thread per high level component (there are of course some exceptions).
* Create threads at "random times", ad hoc, per task. Creating threads can be surprisingly expensive and they can take a surprisingly long time before they are acutally doing what you told them (especially if you have a lot of DLLs loaded!).

## Do

* Use multithreading to have things run *asynchronously* as much as you can. Speed is not the main idea of threading, but doing things in parallel (so even if they take longer alltogether, the sum of all is still less).
* Use vertical sync to limit the frame rate. That is the only correct (and non-failing) way to do it. If the user overrides you in the display driver's control panel ("force off"), then so be it. After all it's his computer, not yours.
* If you need to "tick" something at regular intervals, *use a timer*. Timers have the advantage of having a much better accuracy and reliability as compared to `sleep`\[2\]. Also, a recurring timer accounts for time correctly (including time that passes in between) whereas sleeping for 16.6ms (or 16.6ms minus measured\_time\_elapsed) doesn't.
* Run physics simulations that involve numeric integration at a fixed time step (or your equations will explode!), interpolate graphics between steps (this *may* be an excuse for a separate per-component-thread, but it can also be done without).
* Use `std::mutex` to have only one thread access a resource at a time ("mutually exclude"), and to comply with the weird semantics of `std::condition_variable`.
* Avoid having threads compete for resources. Lock as little as necessary (but none less!) and hold locks only as long as absolutely necessary.
* Do share read-only data between threads (no cache issues, and no locking necessary), but do not concurrently modify data (needs sync and kills the cache). That includes modifying data that is *nearby* a location someone else might read.
* Use `std::condition_variable` to block another thread until some condition is true. The semantics of `std::condition_variable` with that extra mutex are admittedly pretty weird and twisted (mostly for historic reasons inherited from POSIX threads), but a condition variable is the correct primitive to use for what you want.
In case you find `std::condition_variable` too weird to be comfortable with it, you can as well simply use a Windows event (slightly slower) instead or, if you are courageous, build your own simple event around NtKeyedEvents (involves scary low level stuff). As you use DirectX, you're already bound to Windows anyway, so loss of portability shouldn't a biggie.
* Break work into reasonably-sized tasks that are run by a fixed-size worker thread pool (no more than one per core, not counting hyperthreaded cores). Let finishing tasks enqueue dependent tasks (free, automatic synchronization). Make tasks that have at least a few hundred non-trivial operations each (or one lenghty blocking operation like a disk read). Prefer cache-contiguous access.
* Create all threads at program start.
* Take advantage of asynchronous functions that the OS or the graphics API offers for better/additional parallelism, not only on the program level but also on the hardware (think PCIe transfers, CPU-GPU parallelism, disk DMA, etc.).
* 10,000 other things that I've forgotten to mention.

---

\[1\] Yes, you can set the scheduler's rate down to 1ms, but this is frowned upon as it causes a lot more context switches, and consumes a lot more power (in a world where more and more devices are mobile devices). It also isn't a solution since it still does not make sleep any more reliable.
\[2\] A timer will boost the thread's priority, which will allow it to interrupt another equal-priority thread mid-quantum and be scheduled first, which is a quasi-RT behavior. It is of course not true RT, but it comes very close. Waking from sleep merely means that the thread becomes ready to be scheduled at some time, whenever that may be.

# Answer
> 3 votes
I am not sure what you want to achieve by limiting the FPS of the Update and Render both to 60. If you limit them to the same value, you could have just put them in the same thread.

The goal when separating Update and Render in different threads is to have both "almost" independent of one another, so that the GPU can render 500 FPS and the Update logic still goes at 60 FPS. You do not achieve a very high performance gain by doing so.

But you said you just wanted to know how it works, and it's fine. In C++, a mutex is a special object that is used to lock access to certain resources for other threads. In other words, you use a mutex to make sensible data accessible by only one thread at the time. To do so, it is quite simple:

```
std::mutex mutex;
mutex.lock();
// Do sensible stuff here...
mutex.unlock();

```

Source: http://en.cppreference.com/w/cpp/thread/mutex

**EDIT**: Make sure your mutex is class or file-wide, as in the link given, or else each thread will create its own mutex and you will not achieve anything.

The first thread to lock the mutex will have access to the code inside. If a second thread tries to call the lock() function, it will block until the first thread unlocks it. So a mutex is a blocing function, unlike a while loop. Blocking functions will not put stress on the CPU.

---
Tags: c++, directx, rendering, multithreading
---


title: GLSL to Cg fragment shader

text:
# Question
Title: GLSL to Cg fragment shader
I have found very useful resource on the Swiftless website on OpenGL.

Unfortunately, I cannot manage to adapt a GLSL fragment shader to my project, which uses Cg. Here it is:

```
uniform sampler2D color_texture;
uniform sampler2D normal_texture;

void main() {

// Extract the normal from the normal map
vec3 normal = normalize(texture2D(normal_texture, gl_TexCoord[0].st).rgb * 2.0 - 1.0);

// Determine where the light is positioned (this can be set however you like)
vec3 light_pos = normalize(vec3(1.0, 1.0, 1.5));

// Calculate the lighting diffuse value
float diffuse = max(dot(normal, light_pos), 0.0);

vec3 color = diffuse * texture2D(color_texture, gl_TexCoord[0].st).rgb;

// Set the output color of our current pixel
gl_FragColor = vec4(color, 1.0);
}

```

I have tried something:

```
struct fsOutput {
    vec4 color : COLOR;
};

uniform sampler2D detailTexture : TEXUNIT0;
uniform sampler2D bumpTexture : TEXUNIT1;

fsOutput FS_Main(float2 detailCoords : TEXCOORD0,
            float2 bumpCoords: TEXCOORD1)
{

    fsOutput fragm;

    float4 anorm = tex2D(bumpTexture, bumpCoords);
    vec3 normal = normalize(anorm.rgb * 2.0f - 1.0f);
    vec3 light_pos = normalize(vec3(1.0f, 1.0f, 1.5f));
    float diffuse = max(dot(normal, light_pos), 0.0);
    vec3 color = diffuse * texture2D(detailTexture, detailCoords).rgb;
    fragm.color = vec4(color, 1.0f);
    return fragm;
}

```

But it doesn't work. To debug, I have a function that catches Cg errors, and my program breaks at this point. I have identified the two texture IDs in the main program. Can you suggest any improvement for this Cg shader?

# Answer
I tried compiling it from the command-line as follows:

```
cgc -profile glslf -entry FS_Main test.cg

```

This gave the following error output:

```
test.cg
test.cg(18) : error C1066: invalid type in type constructor
test.cg(18) : error C1010: expression left of ."rgb" is not a struct

```

This immediately highlights the fact that you used `texture2D` on line 18 instead of the correct Cg function `tex2D`. Fixing this error makes it compile correctly.

In the future, you should probably use the `cgGetLastListing` function when `cgGetError` returns `CG_COMPILER_ERROR`. This will allow you to print out the error listing in your application, which makes your shaders easier to debug.

On another note, you use `vec3` and `vec4` on various occasions. While the Cg compiler seems to accept this, the correct types are `float3` and `float4`, I believe.
> 1 votes

---
Tags: opengl, glsl, cg, bump-map
---