# Question
Title: Most common format & good practice for 3D models for a placeholder in a PC game
I'm soon starting programming my first 3D game in OpenGL, C++, for PC. It's going to be a top-down space-based game.

Early on I want to create basic placeholder 3D models for my objects, and then in later stages (if I prove able to write C++ game mechanics successfully...) I'll collaborate with / employ a 3D model artist for the full textured models.

What's the best format to create these placeholders in for optimum integration later on?

Any particular advice for how to program it from the start to make it easier to work with the artist later on?

# Answer
I would say that wavefront is the best one to start with. The .obj layout can be exported from almost every editor out there and is really easy to use(Read/write/modify).

The wavefront format is also easy to build upon and to get into a even better suited for your own needing later on, but when you start doing custom adds to it, you are going to need a special exporter from the artists editor.

There is also an awesome library called Assimp that will handle most of the different format loading for you, so you can focus on just hooking it with vertexs instead. Both links are worth a good dig-in-to.
> 1 votes

---
Tags: opengl, 3d, models, format
---


# Question
Title: How do you create 2D skeletal animations without extra software?
I'm working on a Cocos2d-x game and I'm developing on Windows. What I want is to make some skeletal animations, *without* using a tool or extra software to do so?

# Answer
> 1 votes
Well, the way to go about that is to take a hard look at your linear algebra and go to work. A bone in skeletal animation is just a vector that has another vector as origin and is dependent on its parents scale and rotation. Example skeletal structure:

If you think of all these bones as a relative vector, you can arrange them in a hierarchy, one being dependent on its parent bone.

At the point of every vector, you add an image that is relative to it's position, rotation and scales with the scale of each bone.

Once you've gone through the grueling process of making your hierarchy work correctly with scaling, rotation, etc., you can just keep adding nodes and move them / rotate them over time as you please.

The part of merely rotating, moving and scaling them as you please of course is much harder to get looking good then doing in-editor but hey, here we are. It's a lot harder than doing it with additional software however and I highly recommend an application like Spriter or the like for any skeletal animation.

---
Tags: cocos2d-x, skeletal-animation
---


# Question
Title: Lerp problem object teleporting not moving
Hi i just wanna move my object smoothly from one position to another but object disappear and immediately teleport to position where i clicking anyone know whats happen ?

```
    if (Input.GetKeyDown(KeyCode.Mouse0))
    {

        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hit, 1000.0f))
            {

                Vector3 newpos = new Vector3(hit.point.x, 0, hit.point.z);
                Cube40.transform.position = Vector3.Lerp (Cube40.transform.position, newpos, 1f);

            }
    }

```

---

Thank you Vishnu i already fix it with code below your code was better anyway but there is another problem with Lerp method itself because no matter where i click object always transform his position with the same time and it can't be use in RTS game rather i need something like transform.Translate with from:Vector3, to:Vector3 parameters.

```
GameObject Cube40;
RaycastHit hit;
Vector3 newPosition;

void Start()
{

    Cube40 = GameObject.Find("Cube1");
    newPosition = Cube40.transform.position;

}

void Update()
{

    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

    if (Physics.Raycast(ray, out hit, 1000.0f))
    {

        Vector3 newpos = new Vector3(hit.point.x, 0, hit.point.z);
        if(Input.GetKeyDown (KeyCode.Mouse0))
        newPosition = newpos;
        Cube40.transform.position = Vector3.Lerp (Cube40.transform.position, newPosition, 0.1f);

    }
}
}

```

# Answer
Change these lines:

```
Vector3 newpos = new Vector3(hit.point.x, 0, hit.point.z);
Cube40.transform.position = Vector3.Lerp (Cube40.transform.position, newpos, 1f);

```

to something more akin to this

```
//initialize outside of the loop
float newPos = 0;

float rate = 1.0f; //change to what you want, Percent-covered/sec
Vector3 endpos = new Vector3(hit.point.x, 0, hit.point.z);
newPos += Time.deltaTime * rate;
Cube40.transform.position = Vector3.Lerp (Cube40.transform.position, endPos, newPos);

```

The rate of change in *rate* will cause the cube40 object to move toward the Mouse's raycast point. However, the quick and dirty way I have it now will cause it to accelerate (my thought experiment suggest it will decelerate) since the start point changes. You will want to make the start point constant as well if you want to avoid that.

\*changed answer so percentage accumulates
> 2 votes

# Answer
If you want your game to run smoothly independently of the platform it runs on, make sure you multiply your last value with Time.deltaTime. In slower platforms (e.g. mobile), the Time.deltaTime will be higher and the frames drawn will be lower so the lerp speed will remain exactly the same.

For example:

> Cube40.transform.position = Vector3.Lerp (Cube40.transform.position, newpos, Time.deltaTime\*0.5f);
> 1 votes

# Answer
I think your problem would be solved if you place your teleporting code outside of the Input segment if `(Input.GetKeyDown(KeyCode.Mouse0))`

Set a boolean variable keyFired to true when input is detected and place lerping code inside update and turn it false when the lerp completes. Try this, it worked for me.(assign your cube via game inspector to the gameobject variable *Cube40* before running)

```
using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour
{

    public GameObject Cube40;
    bool fireKey = false;
    Vector3 newpos;
    float tParam ;
    // Use this for initialization
    void Start ()
    {
        tParam = 0.0f;
    }

    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit, 1000.0f))
            {
                fireKey = true;
                newpos = new Vector3(hit.point.x, 0, hit.point.z);

            }
        }
        if(fireKey)
        {
            if(tParam < 1.0)
            {
                float speed = 1.0f;//if you want , vary this
                tParam += Time.deltaTime * speed;
                Cube40.transform.position = Vector3.Lerp (Cube40.transform.position, newpos, tParam);
            }
            else if(tParam >= 1.0)
            {
                tParam = 0.0f;
                fireKey = false;
            }
        }
    }
}

```
> 0 votes

---
Tags: c#, unity, lerp
---


# Question
Title: how to implement A Star path finding on 2D map with large tiles
The map tiles I have im my game are 64x64 pixels, and the characters are 16x16 pixels. I was reading about A Star path finding and I was wondering if I need my tiles closer to the size of my characters so that the movement given by the path finding seems more natural, or should I set up a different node map of where the characters can move, and use that in the A Star algorithm.

Or if you have a better solution let me know

Thanks!

EDIT: this is the Map class I am using

```
public class Map extends JComponent{
MapTile[][] map;
Random random;

public Map(char[][] mapKey){
    map = createMap(mapKey);
}

public void update(){

}

@Override
public void paintComponent(Graphics g){
    for(int i = 0; i < map.length; i++){
        for(int j = 0; j < map[0].length; j++){
            drawTile(g, map[i][j].getType(), i * 64, j * 64);
        }
    }
}

private MapTile[][] createMap(char[][] mapKey){
    MapTile[][] temp = new MapTile[mapKey.length][mapKey[0].length];

    for(int i = 0; i < mapKey.length; i++){
        for(int j = 0; j < mapKey[i].length; j++){
            temp[i][j] = new MapTile(mapKey[i][j]);
        }
    }
    return temp;
}
}

```

really the only thing that the MapTiles hold at this point is a key to the Image they paint on the screen

# Answer
> 0 votes
**Think of your character as moving from the centre of one tile to the next.** You have to remember that A\* works off a grid, and your grid determines the resolution of your movement.

If you have a 64x64 tile size, then you're going to be able to move at most in 64x64 increments. If visually this behavior isn't what you want, then consider resizing your grid for the A\* purposes.

Remember that A\* is an algorithm, a way to sort your data. Your data and your graphics *CAN* be different. If you take a 64x64 graphics tile, and separate it into 16 16x16 "path" tiles. That would allow you a single image for graphics, while having a higher pathfinding resolution.

---
Tags: java, path-finding
---


title: Perspective projection computation

text:
# Question
Title: Perspective projection computation
I'm learning OpenGL from arcsynthesis and I don't understand something about perspective projection (http://www.arcsynthesis.org/gltut/Positioning/Tut04%20Perspective%20Projection.html).

When the author gives the example "2D to 1D Perspective Projection Diagram", is R a 2D point or a scalar? When I saw the figure I thought it was a scalar because of the title and I thought that P is projected in a line (the Projection Plan). But later, when I saw the perspective computation, I realized that R has the same number of coordinates of P, because, from that equation, R is a product of the vector P with a scalar, so basically, I don't understand how many coordinates has R.

I don't know where that equation (the perspective computation) comes from, if someone could just give me some information about it I would appreciate it.

# Answer
The mark over the R suggests it is a vector. So does your reasoning.

As for where the equation comes from, that is the whole point of that section of the book. The purpose of the 2D to 1D diagrams is to simplify the explanation of converting 3D to a 2D screen. If the material didn't sink in, read it again. Research other sources for different perspectives on the subject. Or perhaps, ask one of the contributors to the book.
> 1 votes

---
Tags: mathematics, projection
---


# Question
Title: How to set shader global variable in sharpdx without using Effect class
I am working with SharpDX, i thinking to try using (uniform) global variables for HLSL constants instead of constant buffers.

But, in my code SharpDX's **Effect** class is not used: i use PixelShader and VertexShader classes instead - constructed directly from bytecode blobs (i just don't use techniques/passes, i compile shaders separately).

With Effect class, i can assign new value to any constant in HLSL program by its name, as DirectX allows that, in any time. Example (i haven't tested this; yes, its ugly here):

```
SharpDX.Direct3D11.Effect fx = //
fx.GetVariableByName("someOption").AsVector().Set<Vector3>(newVectorValue);//nice

```

But i don't use Effect class. How can i set global HLSL variable using Vertex/PixelShader class instance? If it is not possible, shame on SharpDX dev then, in native DirectX it is much easier.

# Answer
> 1 votes
In D3D11, there is no such thing as a global variable that's not in a constant buffer. Even if you declare variables outside of a constant buffer, the HLSL compiler will put them in a default constant buffer for you.

In C++, I usually just create a struct that matches the layout of a constant buffer in the shader. That might be harder to get working in C# (not sure); but you can also query for the location of individual variables in constant buffers of a compile shader using the ShaderReflection interface, and assemble constant buffers in a data-driven form.

To use a constant buffer outside the effect framework, you have to:

1. Create a Buffer object to hold the contents of the constant buffer. It should be created with dynamic usage, the constant buffer bind flag, write access from the CPU, and its size has to be a multiple of 16 bytes. If your constant buffer isn't a multiple of 16 bytes, just round up to the next one.
2. To update the constant buffer, map it (using one of the `DeviceContext.MapSubresource` methods) using the `WriteDiscard` map mode, copy your data into it and then unmap it. This can be done as many times per frame as you need (constant buffers are designed to be updated many times per frame).
3. To provide it to the shader, use the `DeviceContext.VertexShader.SetConstantBuffer` and `DeviceContext.PixelShader.SetConstantBuffer` methods. You have to know which slot the constant buffer is assigned to in the shader, which can also be retrieved through the reflection interface, or assigned explicitly in the shader using `register(b0)` syntax.

---
Tags: hlsl, sharpdx
---


title: Save "Explored Area" to SQL Database

text:
# Question
Title: Save "Explored Area" to SQL Database
For a strategy game, the area "already explored" has to be saved to a DB, so that the player can (upon resuming his game) see where he has already been.

The game will be a mmo-game, so i have to handle lots of users - each with perhaps 100x100 fields or more that are already explored.

I thought about client sided creating of a bitmap (each field with value 0 = unexplored or 1 = explored), then sending it to the server database to save it as a blob.

Has somebody already tried that solution or has choosen another (better) one?

# Answer
If you're really worried about the storage most of all, the maximum you'll have to store is half the map, plus one bit. The first half of the exploration, you keep track of where they've been. Once they reach halfway explored, you switch over to keeping track of where they *haven't* been and flip you bit. This will cost you a performance hit when you need to switch over to tracking where they haven't been. You'll have to iterate the tiles and see which ones haven't been visited and store those instead. If you were to make a graph of the storage for this technique, it would look like a tent or triangle. Near zero storage on both ends, and the most storage in the middle.

You can improve this by breaking the map up into regions. Do the same half-way technique for each region and you can further just store a single bit for "explored" once the entire region has been explored. Breaking it up into regions also breaks up the performance hit when switching at the halfway point.

How it's stored in the database really depends on how you have things organized already. I'd suggest doing a serialized bitmap stored in the database, per region, that's updated when the player exits the region.

Additional improvements:

* Make the resolution of your explored area overlay half or a quarter that of your tile map. This can drastically reduce the amount of data you need to store, without affecting the game mechanic too drastically.
* Use a lossless compression algorithm to store the data instead. (again trading performance for storage).
> 3 votes

# Answer
Many problems can always be solved with a bit of decomposition.

First off, if your target is the MMO space, then I suspect you either elected to create your maps in continous connected zones much like World of Warcraft's world maps are designed or they're separated into zone-based maps much like GuildWars2.

In either implementation, a map includes area triggers that signify sub-areas or sub-zones within that map (terminology is entirely up to you). So if you combine the characterId, mapId, and areaId; that can easily describe an entry in an exploration table on the server side.

When a player enters a particular map, it's the server's job to query this exploration table and send the client information about what the player has already explored so it can update it's world map state, etc. As the player navigates throughout the world, the area triggers fire and check whether the player has ever visited the area. If so, nothing happens. If not, the server updates the player's exploration state, sends a packet to the client so that it can do the same and perhaps inform the player they've discovered the new area. At some checkpoint on the server side, the exploration data held in memory will be committed back to the database.

Such a narrow table can easily hold millions of rows with little overhead. But it's important to note here that it's the server's job to detect when new areas are explored and to simply send visual information to the client. In no way does the client update any of this state on the server. It's all transparently done based on the player's current position in the map and the area trigger objects defined by the game map design team.
> 2 votes

# Answer
How about using `binary(length)` or `varbinary(maxlength)`? With binary you could store the data for the entire map as bits. Imagine a grid or matrix where the first bit is the position `(0,0)` and the next is `(0,1)`. Each bit's index N represents the position `(N % Width, N / Width)`. This means 1024 * 1024 bits in total which is one megabyte per player. If you divide the map to sectors and only store the bitmap for players who have visited ta specific sector, you can take it down to 10-100K per player.

With varbinary you could possibly save visited space by storing only the positions of the visited areas (for beginners) before players reach the point where it's worth storing the entire map. For instance the first 10 bits represent the `X` position of the first visited area and the next 10 bits it's `Y` position. The next 20 bits are the second visited area.
> 1 votes

# Answer
Beside using the trick of flipping from saving the discovered tiles to saving the undiscovered ones once the player has reached 50% of exploration, this comes down to a data organization and compression problem.

As per your question, I assume that the player usually explores the area by moving between adjacent tiles. This will lead to a pattern of "explored paths" in a mostly undiscovered area, and "patches" of undiscovered tiles in a mostly discovered area.

What that knowledge means is that the pattern of discovery will probably have a lot of contiguous tiles sharing the same state. This is interesting, because this kind of data usually compresses very well under most compression algorithms, like LZMA.

Another approach might be to see your data not as a set of tiles, but as a set of blocks sharing the same state. You could achieve such partition using data structures like BSP trees.

I would probably try the compression first, as it would be easy to implement and most likely yield sufficient results.
> 1 votes

---
Tags: tilemap, mmo, sql
---


# Question
Title: Alternatives to storing all my entities in an SQL database
I've been trying to build my entity system based on pure SQL data storage as explained in this post series. The idea is that every entity or component is stored in an SQL table. I created my framework to manage that, only to realize that many SQL queries took more than 10ms, which is unsuitable for use in a game loop.

I first thought the delay was I/O-bound, so I created an in-memory MySQL cluster. This was better, but still not real-time enough for a game loop.

Has anyone built an SQL-based entity system? If so, how did you manage to keep query times manageable?

---

If an SQL database isn't feasible for performance issues, what data structure could I use to retain the entity system idea and the possibilities of direct SQL requests on components?

I've heard of many MMOs running on SQL. Do they use it for only part of the data or a full entity system? How to separate database-stored and classical memory-stored structures in that case?

---

*Edit for clarification*: Yes, all game data is stored in the database. If say I run my physics system it will first get data from SQL, then do its stuff, then insert the updated data back to the database.

# Answer
> 6 votes
Database reads are usually via network and from hard-drive. That means database queries will always take a few ms, no matter how simple they are. Databases can get faster with in-memory techniques and smart database designs with good indexing concepts, but their speed is often still insufficient for real-time processing.

Blocking your process while a database-request takes place is a bad idea. Instead of that you should always try to:

1. Request data asynchronously. Start the database query in a separate thread of execution and proceed processing the rest of the world while you wait for the response. Many database frameworks support asynchronous queries with callbacks out-of-the-box.
2. Keep data in memory. There is no need to `SELECT attack FROM players WHERE id = 23876` whenever a player attacks. Just *parsing* that SQL string takes ages compared to directly reading `players[23876].attack`. Load all of their character-data with a single `SELECT * FROM players WHERE id = 23876` when the player logs in and store all the data in a data-structure on the game-server. Likewise, don't do an `UPDATE players SET hp=hp-21 WHERE id = 23876` whenever a player takes damage. Do the modification in the game-servers memory and save the whole data when the player disconnects (maybe do regular backup-saves so you don't lose data in case of a server-crash, but not more frequently than every few minutes.).
3. Think about what you really need to persist in the database. When you have objects which simply don't need persistence (like common mobs in mainstream MMORPGs - nobody will complain when their positions reset after a server restart), there is no reason to store these in the database at all.
4. To avoid hitting a speed-bump in the opposite direction (running out of RAM on the game-server) also consider when and what you can persist or discard. When you have an area which wasn't visited by players for a while, there is no reason to still keep its state in memory. Persist the state of anything that's worth persisting, discard the state of everything that isn't and re-boot the area when a player comes near.

# Answer
> 1 votes
Keep in mind that no MMO server is just a single process. In fact, they typically are composed a plethora of processes that each handle unique characteristics of the game world.

But specific to game object data, generally these are handled by zone servers that are often overseen by a master world server. These zone servers are separate processes with their own memory space that hold only the pertinent game object data necessary to simulate their portion of the virtual world. This minimizes the RAM requirements and aids in game state update since each zone server manages a subset of the full game world.

Game object data is still loaded from SQL during startup, data which isn't kept in memory can be queried but is done asynchronously as pointed out by others. But generally, component-data that you're talking about isn't persisted to the database each loop but perhaps every few minutes, during logout, or when specific transactions take place in the game world, such as trading items, etc.

---
Tags: mmo, entity-system, data-structure, databases, sql
---


title: Creating an array to manage terrain

text:
# Question
Title: Creating an array to manage terrain
I want to create random terrain for my game in XNA but i have a problem:

Lets say my game window size is 500X500, so potentially I want an 500 by 500 array right?

But here is the problem, my terrain texture is lets say 5X5, and my player is 20X20. So using the array isn't that good after all because I want to use collision detection on the player and the terrain so he wont fall through.

Maybe an array of ***\[500/terrainTexture.Width,500/terrainTexture.Height\]*** would be better?

Is there a way to fix my problem so i can use collision detection between the player and the terrain?

thanks!

(the terrain is like terraia or 2D minecraft)

# Answer
To help solve your problem, you need to first understand the concept of a camera (in terms of game dev).

The idea is to separate conceptual coordinates which is where your objects are in the game world from rendering coordinates which is where objects are drawn on the screen. In other words, you will need some logic that will transform world coordinates to rendering coordinates which is usually encapsulated in the form of some `Camera` object. For example, your game's character might at a corner of the map while you want to draw the character in the middle of the screen. The camera is essentially where you are viewing the game world from.

See a 2D Camera Tutorial and MSDN docs on the subject.
> 1 votes

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


# Question
Title: Proper Directional light on multiple models
I've been trying to implement a Directional light into an XNA game I'm working on, but for what ever reason, I cannot seem to get the directional light to be a true directional light. Instead, I am stuck with a directional point light. 'Directional Point Light', in this case, means 'each model has a proper directional light applied to it, but the light is coming from a fixed point, instead of an offset position to the model'. What I want is for the directional light to come from a offset of each model, so that each model, regardless of position, will be lit from the same angle.

Ex: If I have 2 cubes (separate models), c1 at (0,0,0) and c2 at (4,0,4), and my light direction as (0, 2, 2), and I am standing at (6, 0, -3) I want to see the top, left (and back, if I could see it) faces of my cubes lit, but instead I get the back, left and top faces of c1 lit, but the right, front, and top faces of c2 light, which isn't what I want.

Current shader code

```
// Global world variables
float4x4 World;
float4x4 View;
float4x4 Projection;

// Ambient Lighting variables
float3 AmbientColor;
float AmbientIntensity;

// Diffuse Lighting variables
float3 DiffuseColor;
float DiffuseIntensity;
float3 DiffuseLightDirection;

// Texturing variables
Texture ModelTexture;

// Texture sampler
sampler TextureSampler = sampler_state {
    texture = <ModelTexture> ;
    magfilter = LINEAR;
    minfilter = LINEAR;
    mipfilter= LINEAR;
    AddressU = WRAP;
    AddressV = WRAP;
};

struct StaticLightVSInput
{
    float4 Position : POSITION0;
    float3 Normal : NORMAL0;
    float2 TexCoords : TEXCOORD0;
};

struct StaticLightVSOutput
{
    float4 Position : POSITION0;
    float2 TexCoords : TEXCOORD0;
    float3 Normal : TEXCOORD1;
    float3 CameraView : TEXCOORD4;
};

StaticLightVSOutput StaticLightVertexShader( StaticLightVSInput input )
{
    StaticLightVSOutput output;

    // Set output position
    float4 worldPosition = mul( input.Position, World );
    float4 viewPosition = mul( worldPosition, View );
    output.Position = mul( viewPosition, Projection );

    output.TexCoords = input.TexCoords;

    return output;
}

float4 StaticLightPixelShader( StaticLightVSOutput input ) : COLOR0
{
    float4 texColor = tex2D( TextureSampler, input.TexCoords );
    // calculate diffuse light
    float diffuse = saturate(dot( -DiffuseLightDirection, input.Normal )) * DiffuseIntensity * DiffuseColor;
    // calculate specular light  - disabled for now
    float specular = 0; //SpecularIntensity * SpecularColor * max(pow(dotProduct, Shinniness), 0) * diffuse;

    float3 ambient = AmbientIntensity * AmbientColor;
    float3 color = texColor.rgb * saturate( diffuse + ambient + specular );

    return float4 (color.rgb, texColor.a);
}

technique StaticLighting
{
    pass Pass0
    {
        VertexShader = compile vs_2_0 StaticLightVertexShader();
        PixelShader = compile ps_2_0 StaticLightPixelShader();
    }
}

```

C# code for setting the shader

```
// set parameters for our shader
objectLightingEffect.Parameters["World"].SetValue(position);
objectLightingEffect.Parameters["View"].SetValue(view);
objectLightingEffect.Parameters["Projection"].SetValue(projection);
// Ambient light
objectLightingEffect.Parameters["AmbientColor"].SetValue(weather.AmbientColor.GetVector3());
objectLightingEffect.Parameters["AmbientIntensity"].SetValue(weather.AmbientIntensity);
// Diffuse light
objectLightingEffect.Parameters["DiffuseColor"].SetValue(weather.SunColor.GetVector3());
objectLightingEffect.Parameters["DiffuseIntensity"].SetValue(weather.SunIntensity);
Vector3 dir = new Vector3(16, 13, 0) + position.Translation;
objectLightingEffect.Parameters["DiffuseLightDirection"].SetValue(dir);
// Texture
objectLightingEffect.Parameters["ModelTexture"].SetValue(texture.Texture);

```

I've even tried offsetting the lights 'direction' (read: position) by the position matrix of each object, which does nothing

Can someone please tell me what I'm doing wrong/missing? I've spent the past 3 days trying just about every single directional light shader variation Google has managed to find for me, and I can't believe something so simple has to be nearly impossible. I can't find anything related to my problem at all here, on stackoverflow, or on any game development blog/tutorial.

Any help will be greatly appreciated.

# Answer
Just set `DiffuseLightDirection` to a constant unit vector. Don't try to add it to the object's position as you're doing now. This vector represents the direction the light is coming from, not the position of anything. So if it's constant, all the objects will be lit from the same direction.
> 1 votes

---
Tags: xna, c#, xna-4.0, hlsl
---


# Question
Title: How to make platforms spawn without touching other platforms
So I am making a doodle jump like game where there are platforms scrolling by but right now how I have platforms spawning is completely random. I would like the platforms to be spread apart so they weren't touching but don't have much of an idea to implement it. I was thinking of using the distance formula to check to make sure that they were apart but I was thinking that as I was creating those object I would have to check with all the previous objects before to see if they weren't colliding. Does anyone have any ideas on how to make this work efficiently?

# Answer
> 3 votes
You could keep it simple.

Methods:

1. Randomly generate platforms, if a newly generated platform's position is overlapping, simply don't use it and randomize another position. It will work unless the platforms are very dense which they should not be.
2. Another way to do it is to use slots across the Y-axis and never use the same Y slot. For instance if the height of the screen is 100 units and a platform's height is 5 units, divide the screen into 20 discrete logical slots and pick one at random and never pick the same one twice. This could be accomplished by storing the empty slots in a pool.

In general arrays are not very fast `O(N)` when you need to remove a random item. To be able to quickly remove items from an array, you may want to shuffle the array and only pick items from the end. In your specific case the size of the array should be `< 1000` so it will likely have no noticeable effect.

You may also simply want to shuffle the array and then iterate on the array in order, never reusing items your previously picked.

---
Tags: java, collision-detection, libgdx
---


title: Best collision shape for rooms

text:
# Question
Title: Best collision shape for rooms
I'm wondering what is the most efficient collision shape to use with APIs like Bullet or Havok for rooms/interiors. Rooms tend to be boxes but are concave since the normals point inward which means no to the box shape. Rooms also can have holes in the walls (doors, windows, etc) too. If I'm assigning shapes with a modeling tool like Blender it seems like my only option is a Triangle Mesh shape but it seems like I should be able to get away with a cheaper (performance-wise) shape for something like this.

# Answer
> 3 votes
Boxes are not what you want; they are solid. (That is, they have a filled interior. Anything inside a box will be thrown out of it.)

Assuming you wrap the triangle mesh in some sort of bounding hierarchy (such as Havok's MOPP or Bullet's BvhTriangleMesh) you should not see any performance problems unless you are running massive numbers of casts or simulating massive numbers of objects. AAA games regularly represent level geometry with mesh shapes consisting of tens of thousands of triangles; if you have shapes as simple as you describe you should be fine.

# Answer
> 0 votes
Not all rooms, halls and pathways are born alike. Some games have very plain level design. For instance in some Beat'em Ups VS fighting games, classic RPGs and some other games, the rooms are sometimes very square and planar. If the rooms lack any complex detail that the player is supposed to interact with physically (as in jump on or bump into), you may be able to easy define walls as boxes. In most (99.9%) FPS, Adventure and modern third person RPG games you will likely not get away with that. In these games the level is very detailed and there are lots strangely shaped corridors, platforms, terrain and also maze-like structures that you simply load into the physics engine knowing the player will likely physically interact with it. You may however often want to have a detailed (high-poly) mesh for rendering purposes and a very rough (low-poly) one for physics.

---
Tags: collision-detection, physics, blender, bullet-physics
---


# Question
Title: In platformer games, what are "hole in the ground" obstacles called?
In most jump and run games, holes in the ground are common obstacles: You need to jump over them, or you'll fall down and lose a life.

It would be helpful to know for documentation, variable naming and discussion: **What are those holes called?**

# Answer
> 21 votes
In various *Super Mario* games, it's called a *pit*, *abyss* or *bottomless pit*.

*Bottomless Pit* is also a TV trope.

---
Tags: 2d, platformer, side-scroller, terminology
---


title: How to mix pixel colors in Shader?

text:
# Question
Title: How to mix pixel colors in Shader?
I have a pixel that have a colour RGB. This color is calculated by the shader and can be anything.

How can I override this color by a colour I choose. If my pixel is white it's simple, I can do this:

```
half3 original = half3(1, 1, 1);
half3 mycolor = half3(1, 0, 0);
half3 result = original * mycolor;

```

But what can I do if:

```
half3 original = half3(0.36, 0.74, 0.18);
half3 mycolor = half3(1, 0, 0);
half3 result = ?;

```

What operation or function should I apply to my original pixel color to override it ?

# Answer
It was very easy finally. Here is the answer. I am using an external value.

```
half3 original = half3(0.36, 0.74, 0.18);
half3 mycolor = half3(1, 0, 0);
half value = 0.5;
half3 result = original * value + mycolor * (1 - value);

```

You could also use `mix();` or `lerp();` depending on your platform.
> 4 votes

# Answer
Just

```
half3 result = (original + mycolor) / 2;

```

does what you'd expect because the arithmetic operators are overridden for the `half3` type.
> 6 votes

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


# Question
Title: How do I send multiple matrices to a vertex shader?
I'm practising animations using bones/skinning. I am trying to send the shader one matrix per vertex. I can think of these two approaches.

## Method 1

I have one uniform handle for each bone matrix like this

```
u_Bone0 = GLES20.glGetUniformLocation(mProgram, "u_Bone[0]");
u_Bone1 = GLES20.glGetUniformLocation(mProgram, "u_Bone[1]");

```

and in the `onDraw` I send each of them to the shader: `GLES20.glUniformMatrix4fv(u_Bone0, 1, false, matrix0, 0);`

This obviously isn't a good approach if I have a large number of matrices. My second idea which I haven't tried yet since there is a lot of code to refactor

## Method 2

Is to use the `glUniformMatrix4fv` to send them all at once like (assume I have 20 matrices)

```
GLES20.glUniformMatrix4fv(u_Bones, 20, false, matrices, 0);

```

where `matrices` is `float[16 * 20]`. But then modifying the matrices for each bones becomes a bit tedious. For example, if I want to get the 3rd matrix, I need something along the lines of

```
float[] _3rd = Arrays.copy(matrices, 3*16, 4*16);

```

and saving back the values can become even more annoying.

---

I'm using Method 1 now, but it doesn't look very smart...

What is the best way to send multiple matrices to an OpenGL ES 2 shader?

LE: I'm using Android, so I'm looking for a Java solution.

# Answer
> 2 votes
Sending multiple matrices to shader is straightforward:

Shader:

```
uniform mat4 mBones[20]; //20 matrices
.. skipped code ..
vec4 vert = vec4(vPosition, 1.0) * mBones[int(vaBoneId)];

```

Program:

```
glUniformMatrix4fv(fShaderUnitSkeletal.uBones, 20, False, @bones20[0]); // Passing 20 matrices

```

Modifying the matrices for each bone is unrelated to how you pass them to the shader though. You can make modifications simpler if you work with structures instead of array of numbers.

```
bones20: array of TMatrix; // Declare array of matrices
bones20[2] := TMatrix.Identity; //Reset 3rd matrix

```

# Answer
> 2 votes
I would suggest using a VBO. Fill your VBO with the matrices, and pass them in using an attribute instead of a uniform. That way the VBO will distribute a new mat4 per vertex pass in the shader.

When you bind the VBO before drawing (or create a VAO for these states):

* Enable the vertex attributes (glEnableVertexAttribArray)
* Set the vertex attributes divisors to 0 (glVertexAttribDivisor)
* Set the vertex attributes pointer (glVertexAttribPointer)

Have a look at how to pass a mat4 as an attribute: https://stackoverflow.com/questions/17355051/using-a-matrix-as-vertex-attribute-in-opengl3-core-profile

Hope this helps

# Answer
> 0 votes
method 1 can be expanded to use arrays to abstract out the number of matrices in the code: (assuming java)

```
int[] u_Bone=new int[NUM_MATRICES];

for(int i=0;i<u_Bone.length;i++)
   u_Bone[i]=GLES20.glGetUniformLocation(mProgram, "u_Bone["+i+"]");

```

and then when you set the matrices you can do

```
for(int i=0;i<matrix.length;i++)
    GLES20.glUniformMatrix4fv(u_Bone[i], 1, false, matrix[i], 0);

```

---
Tags: opengl, java, shaders, opengl-es2, skinning
---


# Question
Title: How Extract Frustum Planes from Clip Coordinates?
I'm having some problems with my Frustum Culling and I want to debug it, so I'm trying to render it's planes, to see exatly the Frustum. But I'm using the Clip Coordinates to do the culling (like OpenGL pipeline do), but I dont know how to render a frustum, in another words, I dont know how to convert a frustum in Clip Coordinates to a "Frustum Mesh".

Actually to calculate the frustum I use this function:

```
glm::vec3 point = MVP * glm::vec4(-radius, -radius, -radius, 1.0f)) //leftTopPoint
return (point.x > -point.w) && //Inside left clipping pane
       (point.x < point.w) && //Inside right clipping pane
       (point.y > -point.w) && //Inside bottom clipping pane
       (point.y < point.w) && //Inside top clipping pane
       (point.z > -point.w) && //Inside near clipping pane
       (point.z < point.w); //Inside far clipping pane

```

Where MVP is a glm::mat4 of Projection * View * Model matrices.

This function is activated only when I press the left click of mouse, so I want to render the Frustum and see how it is.

Also I dont use a "`lookAt`" function to rotate the camera, I'm using `Quaternions` (dont know if that matters).

Sorry if it is a bit confusing, it's hard to explain. So I just need a tip or a orientation/example of how achive this.

Thanks for your attention.

# Answer
> 2 votes
I've done it by using a mix of Lighthouse3D tutorial, which I got by following the tip of @concept3d. My previous Frustum Culling routine was execute in about 12~16ms using Clip Space approach, but extracting planes from camera, I can execute it in 1~2ms....So, the peformance boost is awesome.

Here is my final code. Whenever my rotation/position changes, I update my frustum classe, like this:

```
localForward = glm::inverse(rotation) * -FORWARD; //Calculate the forward direction using the quaternion inverse and the inverse const direction (Always Z+).
relativeRight = glm::normalize(glm::cross(localForward, UP)); //This is relative because we use a const direction (Always Y+), so this isnt a local rotation.
localUp = glm::normalize(glm::cross(localForward, relativeRight)); //Now we calculate the local up based on local forward and relative right.

frustum->SetCameraInfo(position, localForward, relativeRight, localUp);

```

And to extract planes I just setup:

```
nearCenter = position + (forwardVector * nearDistance);
farCenter = position + (forwardVector * farDistance);

nearLeftTop     = nearCenter - rightVector * nearWidth + upVector * nearHeight;
nearLeftBottom  = nearCenter - rightVector * nearWidth - upVector * nearHeight;
nearRightTop    = nearCenter + rightVector * nearWidth + upVector * nearHeight;
nearRightBottom = nearCenter + rightVector * nearWidth - upVector * nearHeight;

farLeftTop      = farCenter - rightVector * farWidth + upVector * farHeight;
farLeftBottom   = farCenter - rightVector * farWidth - upVector * farHeight;
farRightTop     = farCenter + rightVector * farWidth + upVector * farHeight;
farRightBottom  = farCenter + rightVector * farWidth - upVector * farHeight;

/*

            +-----------+
            | \       / |
            |   +---+   |
            |   |   |   |
            |   +---+   |
            | /       \ |
            +-----------+
*/

planes[ePS_NEAR].SetPointAndNormal(nearCenter, forwardVector);
planes[ePS_FAR].SetPointAndNormal(farCenter, -forwardVector);

planes[ePS_TOP].CalcPointAndNormal(farLeftTop, (nearCenter + upVector * farWidth), farRightTop);
planes[ePS_BOTTOM].CalcPointAndNormal(farRightBottom, (nearCenter - upVector * nearWidth), farLeftBottom);

planes[ePS_LEFT].CalcPointAndNormal(farLeftBottom, (nearCenter - rightVector * nearWidth), farLeftTop);
planes[ePS_RIGHT].CalcPointAndNormal(farRightTop, (nearCenter + rightVector * nearWidth), farRightBottom);

```

Hope this help someone else. Thanks.

---
Tags: opengl, c++, glm, frustum
---


# Question
Title: How can I move the view in a DirectX game?
I'm making a game in C++ using Direct3D 9. How do I move the camera at constant rate?

I'm making a Flappy Bird type game and I'd like to move the camera forward through the level.

# Answer
If you have a camera eye position, move that in the forward direction (add to its xyz values the constant vector xyz values which you want to move it by). The camera up vector (which defines the up direction) should stay intact (unless you want to rotate the camera), the lookat vector (or forward vector in which your camera faces from the eye position) should be lookAt.xyz=lookAt.xyz+eye.xyz . Then recreate your view matrix with those values. The projection should not be changed.
> 0 votes

---
Tags: c++, 2d, directx, movement
---


title: How to draw non-triangulated mesh?

text:
# Question
Title: How to draw non-triangulated mesh?
I am working with DirectX (C#/C++). I am wondering is it possible to do not triangulate meshes and what the difference between cases (in loading and rendering code)? If so, how to do this? I know `DrawIndexed` requires `primitive_topology` to be set - which value should I use then? I always used triangulated mesh before with no problems but it is interesting..

# Answer
> 4 votes
Using directx you must draw triangle meshes. If your mesh data contains quads, then create an index buffer that indexes each quad as two triangles and draw by calling DrawIndexed. For example if you have vertex1,vertex2,vertex3,vertex4 which describes a quad then index them by 0,1,2,0,2,3 or according to the desired winding order.

# Answer
> 1 votes
Do you mean draw stuff like cubes, rectangles.. etc?

It´s easy!

Per example for a rectangle (square or something with 4 vertices) :

```
CUSTOMVERTEX Dirt[] =
    {
        { 0.0f, 600.0f, 0.0f,  1.0f, D3DCOLOR_XRGB(221, 216, 148), },
        { 700.0f, 600.0f, 0.0f, 1.0f, D3DCOLOR_XRGB(221, 216, 148), },
        { 0.0f, 700.0f, 0.0f, 1.0f, D3DCOLOR_XRGB(221, 216, 148), },
        { 700.0f, 700.0f, 0.0f, 1.0f, D3DCOLOR_XRGB(221, 216, 148), },
    };

```

instead of having only 3 vertices

then `d3ddev->CreateVertexBuffer(4 * sizeof(CUSTOMVERTEX), 0, CUSTOMFVF, D3DPOOL_MANAGED, &v_buffer, NULL);` instead of 3 * sizeof....

and atlast : `d3ddev->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);` instead of D3DPT\_TRIANGLELIST and change the uiPrimitiveCount to 2...

Source : http://www.directxtutorial.com/Lesson.aspx?lessonid=9-4-7

It also explains cubes and stuff...

Sorry if I didnt helped much

---
Tags: directx, 3d-meshes, vertex-buffer, index-buffer
---


# Question
Title: Box2dWeb: setting velocity of bodies using events
I would like to move a kinematic box by pressing the down arrow. As is noted by the console logs, the keydown actually does change the box's velocity... but for reasons beyond my grasp it still doesn't move.

Note that if you place the SetLinearVelocity() call in a spot where it runs immediately, the box will move, but if it is in a setTimeout, or as in my example, called from an event, the box stays frozen despite its y velocity property changing to 1.

I created the simplest example I could to show my problem.

Note: I am using the latest release of Box2dWeb

```
//std variables
     var   b2Vec2 = Box2D.Common.Math.b2Vec2
        ,   b2BodyDef = Box2D.Dynamics.b2BodyDef
        ,   b2Body = Box2D.Dynamics.b2Body
        ,   b2FixtureDef = Box2D.Dynamics.b2FixtureDef
        ,   b2Fixture = Box2D.Dynamics.b2Fixture
        ,   b2World = Box2D.Dynamics.b2World
        ,   b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape
        ,   b2DebugDraw = Box2D.Dynamics.b2DebugDraw;

//create world and gravity
     var world = new b2World(
           new b2Vec2(0, 10)
        ,  true
     );

//fixture defs
     var fixDef = new b2FixtureDef;
     fixDef.density = 1.0;
     fixDef.friction = 0.5;
     fixDef.restitution = .2;

//body defs
     var bodyDef = new b2BodyDef;
     fixDef.shape = new b2PolygonShape;
     fixDef.shape.SetAsBox(2,2);
     bodyDef.type = b2Body.b2_kinematicBody;
     bodyDef.position.x = 3;
     bodyDef.position.y = 0;

//body and fixture creation
     var body1 = world.CreateBody(bodyDef);
     body1.CreateFixture(fixDef);

//"Before" console log
     console.log("Claimed velocity before down is pressed: " + body1.GetLinearVelocity().y);

//Listener and keycode switch for intended velocity change
     window.addEventListener("keydown", onKeyDown, false);
     function onKeyDown(e) {
        switch(e.keyCode) {
            case 40://down
                body1.SetLinearVelocity(new b2Vec2(0,1));
                console.log("Claimed velocity after down is pressed: " + body1.GetLinearVelocity().y);
        }
     }

//debug drawing
     var debugDraw = new b2DebugDraw();
        debugDraw.SetSprite(document.getElementById("canvas").getContext("2d"));
        debugDraw.SetDrawScale(30.0);
        debugDraw.SetFillAlpha(0.5);
        debugDraw.SetLineThickness(1.0);
        debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
        world.SetDebugDraw(debugDraw);

     window.setInterval(update, 1000 / 60);

//loop
     function update() {
        world.Step(1 / 60, 10, 10);
        world.DrawDebugData();
        world.ClearForces();
     }

```

# Answer
The bodies are apparently asleep and therefore need to be woken up before they respond.

This is taken from this link:

http://www.box2d.org/manual.html

From the Box2d site:

> A sleeping body doesn't require any simulation.
>
> What does sleep mean? Well it is expensive to simulate bodies, so the less we have to simulate the better. When a body comes to rest we would like to stop simulating it.
>
> When Box2D determines that a body (or group of bodies) has come to rest, the body enters a sleep state which has very little CPU overhead. If a body is awake and collides with a sleeping body, then the sleeping body wakes up. Bodies will also wake up if a joint or contact attached to them is destroyed. You can also wake a body manually.
>
> The body definition lets you specify whether a body can sleep and whether a body is created sleeping.

```
 bodyDef.allowSleep = true;

 bodyDef.awake = true;

```
> 1 votes

# Answer
I think this may be a bug in box2dweb. If I add this to the body definition, it works:

```
 bodyDef.linearVelocity.x = 1;
 bodyDef.linearVelocity.y = 1;

```

But of course, if you want the body to start motionless, you would do:

```
 bodyDef.linearVelocity.x = 0;
 bodyDef.linearVelocity.y = 0;

```

... which does not work. Trying to trick it by using a very small value like 0.0001 caused the body to move for a very short while, after which the velocity became zero and setting it to anything else after that had no effect. But for values of about 0.01 and above, the velocity remained constant.

Changing the body type to dynamic also made everything work correctly.

Something seriously screwy is going on there. Hope this helps :D
> 1 votes

# Answer
Not sure if it's a bug or the intentional function of the programmer. Although I would argue that it does lack certain useful functionality if it is intentional.

As far as I can tell, the way it works is that kinematic bodies cannot change velocity after coming to a rest. They must begin with a significant velocity, and from there can change velocity based on events, but if they stop, or if they begin with no velocity, they will remain still.

Below I have included some code which allows my previous program to function somewhat how it's supposed to. However, it's not good enough for application in my opinion because of the small movements always taking place, despite them being nearly unnoticeable.

```
//std variables
     var   b2Vec2 = Box2D.Common.Math.b2Vec2
        ,  b2AABB = Box2D.Collision.b2AABB
        ,   b2BodyDef = Box2D.Dynamics.b2BodyDef
        ,   b2Body = Box2D.Dynamics.b2Body
        ,   b2FixtureDef = Box2D.Dynamics.b2FixtureDef
        ,   b2Fixture = Box2D.Dynamics.b2Fixture
        ,   b2World = Box2D.Dynamics.b2World
        ,   b2MassData = Box2D.Collision.Shapes.b2MassData
        ,   b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape
        ,   b2CircleShape = Box2D.Collision.Shapes.b2CircleShape
        ,   b2DebugDraw = Box2D.Dynamics.b2DebugDraw
        ,  b2MouseJointDef =  Box2D.Dynamics.Joints.b2MouseJointDef
        ;

//create world and gravity
     var world = new b2World(
           new b2Vec2(0, 0)
        ,  true
     );

//fixture defs
     var fixDef = new b2FixtureDef;
     fixDef.shape = new b2PolygonShape;
     fixDef.shape.SetAsBox(2,2);

//body defs
     var bodyDef = new b2BodyDef;
     bodyDef.type = b2Body.b2_kinematicBody;
     bodyDef.position.x = 3;
     bodyDef.position.y = 3;
     bodyDef.linearVelocity.y = .05;
//body and fixture creation
     var body1 = world.CreateBody(bodyDef);
     body1.CreateFixture2(fixDef.shape,1);

//Listener and keycode switch for intended velocity change
     window.addEventListener("keydown", onKeyDown, false);
     window.addEventListener("keyup", onKeyUp, false);
     function onKeyDown(e) {
        switch(e.keyCode) {
            case 37:
                body1.SetLinearVelocity(new b2Vec2(-1,0));
                break;
            case 38:
                body1.SetLinearVelocity(new b2Vec2(0,-1));
                break;
            case 39:
                body1.SetLinearVelocity(new b2Vec2(1,0));
                break;
            case 40:
                body1.SetLinearVelocity(new b2Vec2(0,1));
                break;
        }
     }
     function onKeyUp(e) {
        switch(e.keyCode) {
            case 37:
                body1.SetLinearVelocity(new b2Vec2(0.01,0.01));
                break;
            case 38:
                body1.SetLinearVelocity(new b2Vec2(0.01,0.01));
                break;
            case 39:
                body1.SetLinearVelocity(new b2Vec2(0.01,0.01));
                break;
            case 40://down
                body1.SetLinearVelocity(new b2Vec2(0.01,0.01));
                break;
        }
     }

//debug drawing
     var debugDraw = new b2DebugDraw();
        debugDraw.SetSprite(document.getElementById("canvas").getContext("2d"));
        debugDraw.SetDrawScale(30.0);
        debugDraw.SetFillAlpha(0.5);
        debugDraw.SetLineThickness(1.0);
        debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
        world.SetDebugDraw(debugDraw);

     window.setInterval(update, 1000 / 60);

//loop
     function update() {
        world.Step(1 / 60, 10, 10);
        world.DrawDebugData();
        world.ClearForces();
     }

```

My final note is that the direction I will be taking to move forward with my application is coding my own acceleration and velocity function for the kinematic bodies based on setting their positions.
> 0 votes

---
Tags: javascript, box2d
---


# Question
Title: How can I get the width and height of a picture?
I'm trying to make a script on RPG Maker XP that needs the width and height of an image to do some calculations. I tried `@picture.bitmap.width`and `@picture.bitmap.height` but it returned the width and height of the image that is being shown in the screen.

For instance, if the image is 800 pixels height, and the image takes 400 pixels in the screen, `@picture.bitmap.height` will only return 400. This is the code I'm using:

```
@picture = Sprite.new
@picture.bitmap = RPG::Cache.picture("picture")
@pictureWidth = @picture.bitmap.width
@pictureHeight = @picture.bitmap.height

```

# Answer
> 1 votes
I've realized what the problem was. I had made another picture, bigger than the screen size to test the script. But I forgot to import it to RMXP. Now that I've done that, it prints the correct value to the screen. Apologies for my lack of attention.

---
Tags: sprites, ruby, rpg-maker-xp
---


title: Libgdx Get Font Height with a Wrap

text:
# Question
Title: Libgdx Get Font Height with a Wrap
is possible to get the 'Height' of a font drawed with the drawWrapped methods (with a wrapWidth) ?

getMultiLineBounds only works when **\n** is used, but when drawing with drawWrapped it doesn't give the right Height.

**Text**

```
String text = "hello this is very lonnnnng text without new line";
float wrapWidth = 100;

```

**Display code** :

```
 font.drawWrapped(batch, text, x, y, wrapWidth, alignment);

```

My '**get the displayed height code**' :

```
 font.getMultiLineBounds(text).height;

```

**Output** :

```
 hello this is very
 lonnnnng text without
 new line

```

**Problem** :

How to have the total height of the displayed text by the methods : DrawWrapped

Can you help me please ? thanks you

# Answer
try getWrappedBounds instead of getMultiLineBounds
> 2 votes

---
Tags: java, libgdx, fonts
---


# Question
Title: Which code is faster to convert -1 to 0 and 1 to 1?
I'm writing a shader for rendering the sides of triangles with different colors. I have a value `mediump float back = dot(V, N)` which is positive if the normal faces away from the camera and negative if towards the camera.

To correctly select which diffuse color to shade a particular fragment, I need something like this:

```
lowp vec4 color = max(0.0, sign(-back)) * frontdiffuse + max(0.0, sign(back)) * back diffuse;

```

It's more or less an "unrolled conditional"...

Which code produces faster instructions?

* `x * 0.5 + 0.5`, or
* `max(0.0, x)` ?

The former may be better mathematically behaved than the latter, but maybe min/max/clamping is super efficient in hardware

# Answer
> 7 votes
As you say, the two formulas don't behave the same way mathematically. So if it makes a difference to the visuals, your first priority should be to pick the one that gives you the better-looking result.

Both formulas will be a single instruction on the vast majority of GPUs. `x * 0.5 + 0.5` can be done with a `mad` (multiply-add) instruction, and `max` is a single instruction as well. So I would expect no performance difference under ordinary circumstances.

However, the `sign` function isn't so efficient here, as it evaluates three cases (positive, negative, or zero) while you only need two cases (positive or negative). It should be faster to use an `if` statement or the `?` operator to explicitly check whether `back` is positive or negative and choose the correct color. The shader compiler *should* turn that into an efficient conditional move (as opposed to a more expensive dynamic branch).

All that being said, this is micro, micro-optimization, and quite possibly premature optimization. :) If your shaders aren't ALU-bound, this may produce no measurable difference in performance whatever. So it's probably not worth worrying about anyway.

# Answer
> 2 votes
`step` is what you are really looking for. `step(0.0, back): = 1.0` if `(0 < back)`, or `0.0` otherwise.

So the lines become:

```
lowp float aux = step(0.0,back);
lowp vec4 color = (1.0-aux) * frontdiffuse + aux * back_diffuse;

```

For a more elegant (and maybe optimized) version with `mix`:

```
lowp vec4 color = mix(frontdiffuse, back_diffuse, step(0.0,back));

```

---
Tags: opengl, shaders, opengl-es2, optimization
---


# Question
Title: Elemental damage/resistance rates that exceed 100%
In games there may be the idea of resistance/weakness to certain types of attacks. For example, some games have triangles where A beats B, B beats C, and C beats A. Others may implement this in the form of elemental affinities like fire/earth/water/wind that are popular in certain kinds of games.

Now, I can understand what it means to have 0% fire resistance. It means when you take damage from a fire-based attack, you take full damage.

Similarly, if you have 50% fire resistance, then it's like wearing some fire-resistant clothing and the amount of damage you receive is reduced.

At 100% fire resistance, you are fully fire-proof. No amount of fire will do any damage to you (disregarding of laws of physics and thermodynamics at this point)

On the flipside, you have an attack that deals 0% fire damage, or perhaps 50% fire damage and 50% something else. Or maybe 100% fire damage.

What I am having a hard time grasping is what happens when you have 200% fire resistance, or 200% fire damage rate.

Some games cap the rates at 100% using perhaps a call to a `min` function. Other games assume that you can absorb the excess amounts (eg: 120% means you absorb 20% of the damage).

But are there any solid arguments for why any rates beyond 100% make sense?

# Answer
> 2 votes
Ultimately, it's your game, and you decide how you want it to play out.

I like the explanation given by some games (like Epic Fantasy Battle) that "a resistance of more than 100% is absorption."

For example, a fire resistance of 100% means you take 0 damage; 200% means you absorb the full damage and are healed by that amount.

Or alternatively, you can choose to model your game without resistances over 100%.

# Answer
> 1 votes
In some games you cannot reach 100% due to the amounts equipment give you. In other games this gets just capped at a certain percentage like 75% or 100%. Then there are some that lets you heal since you have such an affinity with that particular element.

For solid arguments as to why any resistance above 100% makes sense would be a creature of fire itself that gets healed for 50% of the damage a offensive fire spell does. Of course when a meteor is involved the discussion starts again. You could make a meteor spell like this a 75% fire spell and 25% earth spell for instance.

Another example would be a healing spell. In some games this healing spell does damage to undead. If the resistance of this spell goes over 100% it could turn to damage.

In the end you decide what happens in your game, some things do not have to make complete sense as long as they add to the game experience. A guy that can shoot fireballs at ugly looking demons does not make much sense to me if i think really seriously about that.

---
Tags: game-mechanics
---


# Question
Title: GLSL/SFML - Only make portion of texture alpha
I'm trying to take a portion of the current texture and turn it to 50% transparent. I send in four values, signifying the rectangle I want to make transparent. It seems every time, however, that coord.x/coord.y are set to (0, 0), resulting in the entire image being transparent when I send in any rectangle that starts at (0, 0).

I'm still new to GLSL and and probably approaching this wrong. Any pointers on the correct approach would be greatly appreciated!

**Values being sent in**

```
sprite.Shader.SetParameter("texture", sprite.Texture);
sprite.Shader.SetParameter("x1", 0);
sprite.Shader.SetParameter("x2", 5);
sprite.Shader.SetParameter("y1", 0);
sprite.Shader.SetParameter("y2", sprite.Height - 1); // sprite.Height = 32

```

**transparency.frag**

```
uniform sampler2D texture;

uniform float x1;
uniform float x2;
uniform float y1;
uniform float y2;

void main() {
    vec2 coord = gl_TexCoord[0].xy;

    vec4 pixel_color = texture2D(texture, coord);

    if ((coord.x > x1) && (coord.x < x2) && (coord.y > y1) && (coord.y < y2))
    {
        pixel_color.a -= 0.5;
    }

    gl_FragColor = pixel_color;
}

```

# Answer
Texture coordinates are expressed as floating points values between the limits 0 and 1. What you are doing is sending 5 and 32 which get clamped to 1, resulting in the image becoming transparent between 0 and 1, which encompasses the whole thing. What you need to do is divide, either in the shader or outside (preferably outside, on the cpu) by the actual width and height of the texture.

For example, say you have a 32x64 texture, and you want it to be transparent in the rect x1=0, y1=0, x2=5, y2=10. You have to divide x1 and x2 by 32 and y1 and y2 by 64, and then do the comparisons.

Something like this:

```
sprite.Shader.SetParameter("texture", sprite.Texture);
sprite.Shader.SetParameter("x1", 0/(float)sprite.Width);
sprite.Shader.SetParameter("x2", 5/(float)sprite.Width);
sprite.Shader.SetParameter("y1", 0/(float)sprite.Height);
sprite.Shader.SetParameter("y2", sprite.Height/(float)sprite.Height); // sprite.Height = 32

```
> 0 votes

---
Tags: c#, glsl, sfml
---


# Question
Title: How should I implement a Game Over menu in Android?
By *Game Over menu*, I mean a menu displayed when you die, with an option to play again.

I have two approaches in mind:

1. **Use OpenGL**

Have some button textures ready. When the character dies, draw them. Listen for events on those textures.
2. **Use a view**

(This is what I'm doing now.) When the user opens the game, I have a basic activity, along with a basic view with a `FrameLayout`: The root is a `GlSurfaceView` and there's a menu on top of it (embedded in a `LinearLayout`). When the user hits "Play", this menu is translated away (using a translate animation) from the screen, leaving only the `GlSurfaceView` visible, with which the user can interact. I was thinking of implementing something similar when the game ends, but I'm not sure where to start.

I don't particularly like the first approach, since implementing button events in OpenGL seems hard.

How should I approach this?

# Answer
This is a pretty broad question since there are so many approaches so the only thing I can do is tell you what I choose to do in my own games.

I run game states, for example when I'm playing `gameState = GAMEPLAY` , then when my character dies I change my game state to `gameState=gameOverScreen`, and using if-statements in my rendering and update methods I check for all the game states, and `if (gameState==gameOverScreen)` I stop rendering and updating gameplay and bring up my game over menu and change my onTouch method (in `update()`) to fit the new screen.

This is just one way and Im not sure if its the best way, but there you go.
> 1 votes

---
Tags: java, android, opengl-es2
---


# Question
Title: Best method for selecting points from a point set - path distance
having a big set of points and a polygonal path what is the best way to select a set of points that are at a certain distance or smaller from the path? Or do I need to iterate thru all points on each segment?

More Info:

* Points are randomly distributed in 2D space as well as path coords.
* Path segments can vary from 10 to 100.
* There can be like 100 points that needs to be selected
* Incoming data is a vector of points for path, a vector of points to find the nearest one and a radius

# Answer
If the incoming points are indeed represented as a vector then you have to touch every single one of them, or else you wouldn't be able to tell if it is within radius distance. But, you might be able to speed up your computation if you have control over the data structure used to represent your point set.

For the sake of simplicity, let's assume the task was really to determine which points are are close to a single point `p`, i.e., the distance to `p` should be at most `r` (the radius). Then if your set of points was not represented as a vector but as, e.g., a quadtree then you would be able to narrow down your search space with logarithmic cost. Since you say that the points are randomly distributed in the 2D plane, you would expect this to speed up your search noticably.

The same argument could be applied if your actual task is not finding points that are close to a single point `p` but to all points on a path. Here, instead of having to iterate over all points of the path, you might be able to save on processing time if the path points come in a similar datastructure (quadtree) that allows you to basically to collapse a bunch of points to a single quad.
> 1 votes

---
Tags: 2d, mathematics, geometry
---


title: Is the "Match-3" mechanic unpatented?

text:
# Question
Title: Is the "Match-3" mechanic unpatented?
Can I use a match-3 mechanic in my commercial game without being sued by some company holding the patent? I will add some extra features to the mechanic.

# Answer
Our *Ask Patents* sister site have a more general question: *Can game mechanics be patented?* It seems most mechanics *are* patentable, but only very specifically. (This may be different for your country.)

I'm no lawyer, but based on those answers, I believe you'll be fine, provided your "some extra features" are significant enough extensions to make your game distinctly differ from the patent.

With English search terms, I found this US patent titled *Match three gaming system and method* through Google Patent Search. The idea seems unpatented in the UK. (You should check your own country's patent registry of course.)
> 2 votes

---
Tags: game-mechanics, patents
---


# Question
Title: Difference between texture arrays and multiple single textures?
I've just learnt that DirectX 10 and above have a feature called "texture arrays". Which, basically, is just a normal array of textures (shader resources) which in a shader is declared like:

```
Texture2D myTextures[2];

```

What I've been using so far is 2 multiple separate textures:

```
Texture2D myFirstTexture;
Texture2D mySecondTexture;

```

Is there any practical (performance, memory etc...) difference between the two?

# Answer
> 7 votes
Not exactly: texture arrays are declared in HLSL as `Texture2DArray` for Texture2D and not as an array of texture, so it is quite different. They are almost acting as a 3D texture, where the z is a slice of the 2D Texture (in terms of uv, it is the w dimension). The difference with 3D texture is that they are not supporting trilinear interpolation between the 2D slices but you can still select dynamically a Texture2D slice with a z/w component (unlike an array of texture), the z/w component is rounded to the nearest integer to select the z/w slice. Concerning the memory, I believe this is equivalent, for performance, not sure they give a huge boost even accessing a set of Texture2D compare to an array of texture (but they support dynamic indexing). Using `Texture2DArray` is also easier as you only need to bind it to a single slot.

---
Tags: textures, directx11, directx10
---


# Question
Title: Creating 3D objects from code and their normals
I'm trying to create my own 3D objects from scratch so I can generate my own terrain for a game I'm making.

So I created a cube and realized the lighting was strange, I looked up the cause and found that each face needed multiple vertices so they could hold their own individual normal because face x's normal will be different to face y's normal, even though the vertices are the same.

So I re-made my cube this way and went on with my terrain generating code. Now that I'm getting into creating more sophisticated meshes the number of vertices and indices are getting quite high (atleast compared to my cube) and a big reason for it is because I have to replicate a lot of the vertices just to have a different normal.

I just wanted to ask if this is **normal** (I know, I'm so funny) and that I'm doing everything right? Or is there a simple way for a single vertice to hold multiple normals?

# Answer
The best way to think about it is whether the surface needs to be smooth at a vertex or whether it needs to create a sharp edge.

To create a smooth surface, the normal at each vertex must be the average of the normals of the triangles bordering the vertex. If you want this, you can have one single vertex at a given position that has a single normal.

To create a sharp edge, you're almost "cutting" the smooth surface. Because of this, there must be more than one surface normal at a given position along the edge. Hence, you need more than one vertex.
> 2 votes

---
Tags: mesh
---


title: How do I flip upside down fonts in FTGL

text:
# Question
Title: How do I flip upside down fonts in FTGL
I just use FTGL to use it in my app. I want to use the version `FTBufferFont` to render font but it renders in the wrong way. The font(texture?buffer?) is flipped in the wrong axis.

I want to use this kind of orthographic settings:

```
void enable2D(int w, int h)
{
    winWidth = w;
    winHeight = h;

    glViewport(0, 0, w, h);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    //I don't even want to swap the 3rd and 4th param
    //because I like to retain the top-left as the origin
    glOrtho(0, w, h, 0, 0, +1);
    glMatrixMode(GL_MODELVIEW);
}

```

I render the font like this:

```
//No pushing and popping of matrices
//No translation

font.Render("Hello World!", -1, position, spacing, FTGL::RenderMode::RENDER_FRONT);

```

On the other forums, they said, just scaled it down to -1, but it wont work in mine. Example:

*font is above the screen*

I can't see relevant problem like in mine in google so I decide to ask this here again.

How can I invert texture's v-coordinate without modifying its source code ? *(assume its read only)*

# Answer
> 0 votes
I have no experience with FTGL, but after some Googling I found this: http://devcry.heiho.net/2012/01/opengl-font-rendering-with-ftgl.html?m=1

Basicaly when using `glOrtho` with the rendering, you should set the origin to the lower left corner. I hope this helps.

---
Tags: opengl, c++, textures, coordinates
---


# Question
Title: Why are there different ways of building projection matrices?
Matrix.PerspectiveFovLH documentation page says that this method uses the following formula to build a perspective projection matrix.

```
[w, 0, 0, 0]
[0, h, 0, 0]
[0, 0, zFar/(zFar - zNear), 1]
[0, 0, -zNear * zFar / (zFar - zNear), 0]

```

where

```
h = cot(fovY / 2)
w = h * aspectRatio

```

DirectXMath's **DirectX::XMMatrixPerspectiveFovLH** uses the same formula but with a difference. It calculates **w** as **w = h / aspectRatio** therefore creates a different matrix.

There is a difference between orthogonal projection matrix building too.

Why are there such differences or am i missing something?

# Answer
Simply because there are many ways to compute the projection of objects in a 3D scene onto a 2D plane. That's why you have perspective versus orthographic projections (and various flavors thereof, such as off-center projections), and that's why you can use slightly different formulae to compute the projection transformation.

Sometimes the differences are semantic in nature (such as in the case of perspective versus orthographic). Sometimes they are purely conventional in nature. Sometimes they are due to known quantities or characteristics of the inputs the system.

It's sort of similar to how you can represent your vectors as 4x1 or 1x4 matrices, and that consequently has a impact on whether you multiply your vectors on the right or the left of your transformation matrices.
> 4 votes

---
Tags: directx, projection, perspective
---


# Question
Title: Why do I see a lot of games using Unreal engine when there are much better alternatives?
I play games on my computer often and I see a lot of games using the **Unreal engine**. Can someone explain why do developers choose to use this engine? In my opinion there are much better alternatives. For example games running on the **cry engine** look way better and the engine itself is more optimized.

# Answer
> 9 votes
The unreal engine, or more specifically the Unreal Development Kit (UDK) is a very versatile and user friendly engine. There is a big community involved with it and it has great documentation and support for it. Furthermore, everyone can use the complete engine for free until a good amount of cash is earned with your product, i believe that is $50.000 I'm not familiar with the cry engine but i'm pretty sure it is not as versatile. Other then that, you say the cry engine looks way better, i doubt that. Since UDK is so versatile you can write your own shaders for it, i have seen very beautiful shots from the UDK engine, though i never compared it with cry engine.

That being said, a developer should pick a platform that will work for his game. If you need all the optimization you can get don't pick an engine at all but write one in C++. That goes for all needs.

---
Tags: unreal, cryengine
---


title: Each level is one scene?

text:
# Question
Title: Each level is one scene?
I'm planning to get into Unity 2D tools - so in order to start off I decided to create a little breakout clone. However, I'm not sure how to manage levels. When I wrote Breakout using MonoGame, I just had one class Level which read a XML-file for the level itself (kind of a simple tilemap).

Now that Unity has a graphical interface I could probably just create one scene for each level and put all the blocks in there. Is this a normal approach to handle levels in Unity - or would it be more appropriate to have one scene that also loads objects by using something like a XML file?

Thanks!

# Answer
Technically you could do a new scene for each level, but I highly recommend the other approach of one scene that simply places objects based on data in an XML file. Separate scenes in Unity are intended for loading/unloading graphics and code when each level is significantly different, but if each level is pretty much the same objects just with the objects in different positions (like, say, a level in Breakout) then using separate scenes is rather inefficient.
> 4 votes

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


title: Planet gravity?

text:
# Question
Title: Planet gravity?
I am trying to make a game with the Phaser game engine and would like to implement some sort of planetary gravity. Essentially I just want the player to be able to walk on a circle or orbit a point. I was wondering what would be the best way to do this in phaser. I know that you can set objects gravities but you can only do so in the x and y direction.

# Answer
> 4 votes
Phaser doesn't have built-in support for any fancier gravity, so you'll have to roll your own. Fortunately it's fairly easy to understand, so you just calculate your own gravity in the game's `update()` function, which is simply a (properly scaled) vector from your player to the planet's center of gravity, and set your player's `body.gravity` property, or you can manually add the gravity vector to the `body.velocity` property.

Here's an example of the first approach: http://jsfiddle.net/gJ4kA/

```
function create() {

    planet = game.add.sprite(200, 150, 'planet');

    ship = game.add.sprite(200, 32, 'ship');
    // Use our own gravity
    ship.body.allowGravity = false;
    // Set an initial motion
    ship.body.velocity.x = 100;

}

function update() {

    // Calculate gravity as the normalised vector from the ship to the planet
    ship.body.gravity = new Phaser.Point(planet.body.x - ship.body.x, planet.body.y - ship.body.y);
    // Normalize and multiply by actual strength of gravity desired
    ship.body.gravity = ship.body.gravity.normalize().multiply(300, 300);

}

```

This is probably not accurate enough if you're making a simulation, but for simple games it is fine.

---
Tags: phaser
---


# Question
Title: What is the process to start developing games for the PS Vita?
Let's assume a solo/indie developer using Unity and targetting the PS Vita. Let's also assume that the developer's region is Europe.

* What does the developer need to start developing (only developing, not publishing) on the PS Vita?
* Which Unity version/license?
* What needs to be done on the Playstation side? (registration etc)

As an extra point:

* What extra steps are needed for the said developer be able to distribute an alpha/beta version of the game? (for a gamejam and feedback)

# Answer
http://blogs.unity3d.com/2014/01/15/playstation-vita-deployment-is-here/

You need Unity 4.3. You must register with SCE as a developer to get the proper tools, keys, and so on to be able to publish to the Vita even in testing. Note that registering with SCE requires (for North American developers):

* Corporate entity (Strongly Recommended)
* A Legal Signatory
* Static IP
* Located in US, Mexico, Central America, South America or Canada

If you need more help on the technical aspects of using Unity to publish to Vita, you should consult Unity's documentation or ask on the Unity or SCE developer forums given how very specific to their technology stacks this question is.
> 5 votes

---
Tags: unity
---


# Question
Title: Efficient type checking in collision detection
Basically, what's the most efficient and professional means of checking an object's type when it collides with another object. For instance (ignoring the math for collision detection), suppose we have a gameObject class that game objects inherit from and assume that there is a separate physics system that detects collisions for us, and then proceeds to call the colliding objects collideWithOther method, passing the other object involved in the collision into the method.

```
abstract class GameObject
{

    void abstract collideWithOther(GameObject gameObject);
}

class Bullet : GameObject
{

    void override collideWithOther(GameObject gameObject)
    {

    //Check other object to see if it has game logic related to collision with this object
    if (gameObject is Enermy)   //this is sudo code, the "is" keyword is to expensive for this.
    {
        //do bullet hit enermy code here
    }

    }
}

class Enermy : GameObject
{
...
}

```

I am aware that there is the "is" keyword and the the .getType meathod. However I have read that they are expensive and sloppy for a real time system such as a game.

To address some of the answers that this question might receive. In the example above we can simply cast the game object to bullet since we know that it would be that class. But the purpose of this question is for a situation where we don't which class it would be. As there may be 10 different classes that can all collide with the bullet, but only 2 of them have game logic associated with it. Also I know we can give the bullet different damaged as an member based on what type of the bullet it is, but that misses the point of the question as this between any object. What would be the most professional and efficient way of dealing with this.

# Answer
> 3 votes
Generalize and simplify.

There's no reason for the collision system to know or care about specific game object types. The collision system needs only know about shapes (*how* to check collision) and collision groups/masks (*what* to check for collisions).

Game objects are responsible for defining which groups they collide with. The collision system then checks collisions and feed responses back to the game logic system.

The collision type is just an enum.

The collision group is just an int, possibly a bitfield (some systems use both groups *and* masks, possibly with subgroups; depends on your needs).

# Answer
> 0 votes
One way I deal with such stuff is I put a member in the base class that describes the type of the derived object. For instance, GameObject can have a member called type which is an enum or w/e. Then, you could do

```
 if (gameObject.type == GAME_OBJECT_TYPE_ENEMY)
 {
        Enemy e = (Enemy)gameObject;
        //do bullet hit enermy code here
 }

```

Also, virtual methods tend to be slow as well.

It may not be the most *professional* way of dealing with this, but I think it's the fastest.

---
Tags: collision-detection
---


title: Entity Component System, weapon

text:
# Question
Title: Entity Component System, weapon
I'm new to game programming and currently trying to understand Entity Component System design by implementing simple 2d game. By ECS I mean design, described here for example

In my game I have different kind of weapons: automatic, gun, grenade, etc... Each type of weapon has it's own affect area (gun shots along the straight line and grenade explodes and covers some spherical area) , damage impact, visual effect and bullet amount, delay between shots. So I don't completely understand how to implement weapons. Should weapon be an Entity or it should be a component? And how the player should pick up a weapon, switch between different types of weapons and etc.

# Answer
> 9 votes
In ECS everything is broken down to components that describe functions.

1. A weapon is a physical item so one component will be a physical position. If it is on the ground or thrown at an enemy (sword / throwing knife) then you need the physical position component to decide if it was picked up or hit something (e.g. wall or monster). When a weapon is held you can use the physical positional component of the owner. A physical component is important because it helps us keep in mind that a weapon does not have to be held to be useful (mines for instance and gun towers are an example).
2. A weapon is sometimes a container. It contains an Ammo entity. Some weapons could contain different types of ammo for different effects. Some weapons can be enhanced or enchanted so you may or may not need another container for such buffs.
3. A Weapon is a factory. It creates moving projectiles or AoE zones that collide and affect mobs.
4. A weapon can sometimes deteriorate (as in Diablo) so it may have a health component.

So this is how I would define a weapon:

Factory component, Container component, Physical (position & velocity) component and health component.

# Answer
> 1 votes
In my book, an entity is something that takes part in the simulation of the world. In that category belong all visible game objects, but also logical entities such as trigger areas.

A weapon does not take part in the simulation of the world by itself. Unless of course the weapon is dropped in the world and thus becomes a pickup item. But a weapon held and used by an entity is not an entity itself, it is an entity attachment. Think of the weapon as being part of the entity's inventory, with effects - ie it changes the entity's visuals, the type and amount of damage it can do, and so on.

So a weapon clearly changes the behavior of an entity and can be replaced, too. That makes it a component of the entity rather than an entity by itself.

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


# Question
Title: Change game from portrait to landscape dynamically
I have multiple classes that implement `Screen`.

I want to, say, have the **Main Menu** screen `portrait`, then the **Play Screen** `landscape`. Is there anyway of changing the `orientation` dynamically?

I thought I could just start another `Activity` and have the **Play Screen** extend `Game`. And the new `Activity` would `intialize` the **Play Screen**. But it appears that you can't call `startActivity` or the like, obviously, as `LibGDX` is platform independent.

I use `Gdx.graphics.getWidth()` and `Gdx.graphics.getHeight()` to align `Sprites` and `Actors` so it looks "right" on different devices.

I've also tried swapping the `Gdx.graphics.getWidth()` and `Gdx.graphics.getHeight()`, respectively, but can't seem to get the position of sprites and actors correct.

# Answer
I figured out how to do it.

I used an interface as shown at this link

Basically, I created an interface in the core project, then for each back-end project I `implements` my interface.

To change the `orientation` in Android is simple as shown here

That is, `setRequestedOrientation(ActivityInfo.<THE_ORIENTATION>)`
> 1 votes

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


# Question
Title: Is multitexturing really just "using more than one texture"?
This might seem stupid, but it bugs me. From what I understand, *multitexturing* is just using more than 1 texture per shader (usually to blend them somehow). So instead of creating 1 texture, I create 2 or more which is... pretty obvious!

Why is there a special term for that? Is there more to it than just "using more than 1 texture"? Am I missing something?

# Answer
> 16 votes
The special term has to do with the evolution of graphics cards and real time graphics APIs rather than being so special. For instance image processing and offline graphics rendering had this feature long before it was available in real time graphics APIs and consumer level hardware.

Since OpenGL 1.1 (fixed functionality) multitexturing was introduced as a new state to the API. Instead of only binding one texture, it gave you the ability to bind multiple textures; one for each texture units and then blend between them using one of the texture environment parameters, blend, modulate..etc1

Then texture combiners were introduced, it gave the ability combine a set of textures using more flexible operations, by giving you a way to pass parameters to a fixed set of operations (think of it as shaders but with fixed set of params), this was more flexible than the original "combiners".

With the introduction of shaders, the previous combiners became redundant until officially deprecated. Finally It became trivial (as hardware and accordingly APIs evolved) to pass a texture sampler to the shader and let the GPU execute *arbitrary* operations (your shader) on your textures as much more flexiblel to what was before.

The point here; even if it became trivial, the term survived as a generic term for any operation that describes sampling and convolution of multiple textures.

 I am using my memory to recall OpenGL fixed functionality correct me if I missed sth.

# Answer
> 5 votes
The historical reason is that "multitexturing" was a marketing buzzword like "hardware TnL" once upon a time. Since it was a distinguishing feature of new cards, there needed to be a word for it to sell them.

The technical reason is that multitexturing is **not** just creating and using two textures instead of one. If you simply used two textures (or three, or any number), you could just as well only use one texture, since there is only one output fragment. That would make no difference (whatever the input is, the output can only be one or the other), so it wouldn't be anything special.

The difference is not that you can create several textures, but that you **combine** two or more textures. For example, you might blend them based on alpha or on some per-vertex interpolated blend factors, or you might add them, or something different.
The amount of configurability/programmability has greatly evolved over the last decade, but the one great difference remains that you can *somehow* combine two or more inputs into one output.

# Answer
> 2 votes
**In the beginning there was light**

OpenGL lighting, to be specific, which specified certain mathematical operations to be applied to a fragment, which were then combined with textures to derive a final colour.

**And then there was Quake**

Quake *didn't* use this kind of lighting for many of it's objects. Instead it used a second texture to represent lighting, which was multipled by (or "modulated with) the object texture to derive a final colour.

However, hardware of the time didn't support this in a single operation. So Quake needed to draw it's scene objects twice:

* Draw everything once to lay down the base textures.
* Set a modulate blend mode.
* Draw everything a second time to apply the lighting textures.

This of course was slow; not only did all geometry need to be transformed and clipped twice (which in those days was a CPU operation), but every pixel on-screen ended up being touched twice during rendering.

**Enter multitexture**

Multitexture was the solution to this, and was originally exposed via the GL\_SGIS\_multitexture extension, which only existed on certain consumer 3DFX cards. Originally it only allowed blending two textures (and with a limited set of blend modes).

To quote from the original GLQuake readme:

> GL\_SGIS\_multitexture
> Multitextures support allows certain hardware to render the world in one pass instead of two. GLQuake uses two passes, one for the world textures and the second for the lightmaps that are blended on the textures. On some hardware, with a GL\_SIGS\_multitexture supported OpenGL implementation, this can be done in one pass. On hardware that supports this, you will get a 60% to 100% increase in frame rate. Currently, only 3DFX dual TMU cards (such as the Obsidian 2220) support this extension, but other hardware will soon follow.

It's important to remember that at this time effects such as normal mapping, any other kind of per-pixel lighting, even shaders, and so on just *didn't exist* (well they did, but primarily just in academic papers and research projects, and weren't considered viable for use in real-time rendering).

**And so to the present**

From here it's pretty much as described in the other answers. Multitexturing became a standard feature over time, with more blend modes becoming available, eventually giving way to arbitrary shader code.

But what's important for the purposes of your question is this: in the beginning the standard functionality was just being able to use **one** texture at a time when rendering. Being able to use more than one was additional functionality that only high-end hardware supported, and so it needed a name. That name could have been "dual-texturing" (as the first implementations just supported two textures) but with one eye on the future the name "multitexture" was chosen.

Further reading on the history of all this is available here, and a good historical writeup (of the broader context, and the part multitexturing played in it) at this Programmers.SE answer.

---
Tags: shaders, terminology, multitexturing
---


# Question
Title: Is padding brackets objectively the best way to write C programs?
void Function( int, char )

versus:

void Function (int,char)

My friend keeps saying otherwise. What is objectively the best way to write brackets?

# Answer
There is not a *best* way. There is just a *preferred* way, and that changes from person to person. There are many different semantics that various programmers with bicker on about style. I have personally seen the following 3 ways in commercial code:

`void DoSomething(int,float,string);`

`void DoSomething(int, float, string);`

`void DoSomething( int, float , string );`

Although I have a preference for one of these, I can't tell someone that *my* way is best. Therefore the best advice is to write *what works best for you*, or the chosen style for a given collaborated project.
> 1 votes

# Answer
There is no best way, but there are some cases where one way is better than another.

* If you're working as part of a team, that team will have it's own coding style, and you should conform to that.
* If you've inherited a bunch of legacy code you may prefer to conform to the coding style already used by that legacy code.
* If you're coding something on your own you can sometimes just use whichever style you find most readable.
* If you're writing something where a pre-defined style already exists and is expected to be used (e.g a GNU utility) you'd better use that pre-defined style.

However, in a world where source code formatters exist and are common (and free) discussions or arguments over coding style seem silly.
> 1 votes

---
Tags: c
---


title: Smooth Camera Offsets

text:
# Question
Title: Smooth Camera Offsets
I am attempting to implement a sort of, smooth camera that has angle offsets from the player as they turn, creating a cinematic effect as well as visual feedback for when the player turns.

Here is an example of the desired functionality. (Starts at 1:06) http://youtu.be/uJ6tD-k\_RuA?t=1m6s

One idea I was thinking of (if even feasible) is to store a "desired quaternion" of orientation of where the camera wants to look (preferably the player's quaternion of orientation) and a "current quaternion" of the cameras orientation and SLERP to the desired quaternion. Then possibly set a max angle between the two rotations to cap how large the angle offset could be.

What are the ways of doing that?

# Answer
Quite old thread I see... :) Maybe somebody else will need that.

When I needed similar solution I tried hard with camera parented with the player object and quaternion tricks as you said, etc. and nothing seemed to work as I wanted. Then, I detached my camera from the player and everything became easier.

Just detach your camera and compute some point at the back of your player - this will be the point that you camera wants to get into. For every frame just move your camera by some percent of the distance to the target - this way you get nice, smooth movement.

The same applies to rotation - make some "target" orientation, it may point to the player, or in the same direction the player looks, and for each frame compute some percent of rotation difference to get closer to your target value.

In fact, what you want is some kind of chasing camera. It's not physically connected to the player but it tries to follow him smoothly. When you put your camera as a players child, then it inherits all player transformations, so it starts looking as if it was connected. You get the situation like on some GoPro movies, with camera attached to your helmet and pointing at your face. Then, you try to find some clever math to avoid the effect of your own hierarchy :).

BTW: Remember about your frame rate and numerical integration errors - i.e don't compute like: `val = dist * 0.1f`, but `val = dist * log(speed,time)`
> 2 votes

---
Tags: camera, quaternion
---


# Question
Title: Android Jump&Run - Random map generation
I'm pretty new to game development but I work on an android app. It's a 2D Jump and Run game.

I do it in Eclipse and the map is readed out of a txt file right now. But I want to do a Jump and run game, where the player must jump over holes in the ground. Theses holes should be created randomly. So I want an infinite map, which is created randomly. Can somebody give me tips how to begin with this? How can I do a randomly generated map? I don't want the full code or something else, just a little tip how to start because I don't know how I can do this randomly generating.

Thanks in advance! Hope u know, what I mean!

# Answer
> 1 votes
I'd define a minimal interval between two holes (I assume your map is tiled so let's say this interval is 2 tiles), then every time a new tile enters the screen, if there wasn't a hole for the previously defined interval, generate a random number to know if the new tile will be a hole.

---
Tags: android, maps, random
---