# Question
Title: Is it possible to update constant buffers/textures/variables by name?
When I was learning `OpenGL` (some old version), the way to update variables in shader was to find their index or whatever by name (string) and then use that index to actually update them. And I've seen it's also possible to update variables by name using `ID3D10Effect` interface (I don't know if there's any `ID3D11Effect`). But since I'm not using effect files, I'm wondering if it's still possible. Or should I just stick to manually indexing constant buffers/variables (`register(b0)`) in shader and then using these indices (slots) in `C++` code?

# Answer
Yes, you can look up resources and variables from a compiled shader using the ID3D11ShaderReflection interface. This can be used to find the bind points for constant buffers, textures, etc. which you can pass to calls like `PSSetConstantBuffers`, `PSSetShaderResources` and so forth. You can also look up the offsets of individual variables in a constant buffer.

FYI, there is also an Effects11 library that provides effect files for D3D11. It is no longer part of the DirectX SDK, though; it's been open-sourced as a standalone library, and Microsoft warns that the HLSL compiler support that it depends on is deprecated and could be removed in a future version of the compiler.
> 2 votes

# Answer
As pointed out here, if you have the DirectX SDK you have the Effects11 framework source code available. Personally I would recommend not relying on it and implementing your own assignment system. I find using cbuffer registers cleaner.

What I did is to have each material implementation (provided you have some sort of Material class) define and assemble all variables, cbuffers, etc. that it needs. For example I create cbuffer proxy objects by adding all the data they might need (matrices, vectors, and so on).

This ConstantBuffer class (C# code) defines what kind of cbuffer it represents, depending on the update frequency (i.e.: PerScene, PerFrame, PerInstance...), to what kind of shader it is associated and the slot:

```
public CBType Type { get; private set; }
public ShaderType ShaderType { get; private set; }
public int Slot { get; set; }

```

So before rendering, I have access to all this information. Thus cbuffers, textures, samplers (which have a similar organization), etc. can all be set automatically. If you want to go even further, you can also serialize shader parameters via XML so that when loading a material, it also fetches the necessary data to fill your cbuffers from your engine without hardcoding it.
> 2 votes

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


title: Light Map Generation using DirectX

text:
# Question
Title: Light Map Generation using DirectX
I'm trying to build lightmaps for an engine I'm working on. I'm using DirectX 9 w/c++ but my questions are related to the methodology behing the generation of light maps.

I have a scene built from collections of mesh objects. The scene is divided into an octree. I want to generate a light map for each of the octree nodes or possibly 1 light map for a subdivision( 8 nodes ).

I've read the tutorial on flipcode.com( here ). For the explanation on "calculating/retrieving light map texture coordinates the tutorial refers the reader to a broken link.

I'd appreciate a list of instructions on 'what' to do in order to complete this process...I've found bits and pieces from different sites that have different implementations and its hard to piece it together. How do I assign a polygon to a specific area of the light map?

# Answer
> 0 votes
You could try using Microsoft's UVAtlas tool, which is built into D3DX, so you already have it available. I've never tried it myself, but I've heard from others that it works pretty well.

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


title: Creating your own vertex element in XNA

text:
# Question
Title: Creating your own vertex element in XNA
I needed to create my own VertexElement with the follow - Position, Color & Normal. I found a tutorial explaining how to do this here (http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series1/Terrain\_lighting.php).

I created a struct similar to the tutorial and then replaced all the declarations with the new one, but I get this error:

> There is no boxing conversion from 'VertexPositionColorNormal' to 'Microsoft.Xna.Framework.Graphics.IVertexType'.

and I get it under the rendering line here:

```
graphicsDevice.DrawUserIndexedPrimitives<VertexPositionColorNormal>
(PrimitiveType.LineList, currentPlayer.LLObject.Vertices, 0,
    currentPlayer.LLObject.TotalVertices, currentPlayer.LLObject.LinelistIndexes, 0,
    currentPlayer.LLObject.TotalLinelistIndexes / 2);

```

I had a look on Google to see if there was any obvious answers but it's hard to search for. Could someone spread some light on what is going wrong?

# Answer
That error indicates that XNA expect your custom vertex type to implement `IVertexType` as shown here. Otherwise you need to use the overload that accepts an explicit `VertexDeclaration` object.
> 2 votes

---
Tags: xna
---


# Question
Title: How good can the graphics get on a game made only with Python?
Aside from the game being fun, which is the most important, is it possible to make a "good looking" game with it? The graphics I mean. Like Angry Birds. Could that be made in python, looking like it does (you know, good).

http://www.youtube.com/watch?feature=player\_embedded&v=7oZC6DpIUhQ

No, it's not mine. I don't know anything about it. But, I like the way it looks. It, however, is written in Java (I saw it on the java-gaming forum).

Also, I don't mean using Panda3d or another C++ engine with Python as the game logic. All in Python and based on some Python library (I don't have to totally reinvent the wheel.)

Thanks.

# Answer
> 1 votes
First off, your comment "based on some Python library" could very well be a "C++ engine with Python as the game logic".

Second, the quality of your graphics is almost never related to the programming language you choose. In part because of, well, the first point.

---
Tags: graphics, python
---


# Question
Title: OpenGL: How to map textures to geometry without using filter parameters
following my another question I have studied in the documentations that I should use this procedure :

Define the texture filter parameters. This will control what happens when a texture is scaled up or down.

```
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,filter);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,filter);

```

where filter is:

* `GL_NEAREST` specifies that point sampling is to be used when the texture map needs to be magnified or minified.
* `GL_LINEAR` specifies that bilinear interpolation among the four nearest neighbors is to be used when the texture map needs to be magnified or minified.

but since my program is all about image processing and applying different filters on an image, I don't want to apply extra filters to the image. Is there any way to apply the textures without filtering?

# Answer
GL\_NEAREST is nearest neighbor, this is effectively no filtering.
> 3 votes

---
Tags: c++, opengl, textures, performance, filtering
---


title: One or multiple quadtrees?

text:
# Question
Title: One or multiple quadtrees?
Let's say we have 100 objects of each of few types, that may have an effect if they collide with one other type, or they may not.

Is it better to have quadtrees for each object type, and check collisions directly between the object types we want; or is it better to have a single quadtree holding all objects, then generate collision pairs and check if the collision has effect or not?

Is having a single quadtree slower? Why not having multiple quadtrees, one for each object type?

# Answer
> 5 votes
Usually you'll just have a single quad tree. Often times this would be better as the different layers of collisions can be quite complex and numerous. Also I don't think a bottleneck has ever been that too many potential pairs are culled by layering instead of being implicitly culled by separating data structures.

It's hard to make something faster and simpler than a bitwise and as far as layer overlap checking goes.

# Answer
> 2 votes
If you make separate binary trees for different objects, you will destroy the whole purpose of the tree: logarithmic complexity.

Say you sort your objects into different trees. Each tree's contents and ordering will have no bearing on collisions with items in other trees. You will be back to testing each item from one tree against each item from another. That puts you right back at O² complexity.

On top of that, creating sparse or imbalanced trees also wipes out their efficiency. The point is that each branch of the tree reduces the required checks by half. You gain no benefit if all items reside in a single branch. So having trees with fewer items does not make them faster; it makes them slower.

Make a single tree for all item types. This is important enough to edit your code architecture to make it possible.

---
Tags: quadtree
---


# Question
Title: Architechture problem of implementation of a tutorial for a game
I'm creating one for my game and I'm confused a bit. I made special `TutorialManager` class and a number of steps to pass for player first time entered the game.

The problem is that tutorial steps are N separated classes, and each has some logic to lead the player. The problem is that I had to open (make public) a lot of private methods of UI and field to give `TutorialStep` classes ability to operate with objects I need, and it's an awful solution as far as I can see. But I have no idea how to organize it in other way.

I'm not sure I've described the problem clear enough, so any questions will be answered.

# Answer
> 2 votes
You need to more clearly separate how your individual modules work. Tutorial code should not need to reach into UI code, but the UI code interfaces should expose all the data necessary for an external source (like game logic or a tutorial) to drive it.

For instance, every UI element might have a way to enable/disable it, hide/show it, or highlight it. The code that decides which elements are visible or such is *not* in the UI itself, it's in a separate game logic system. This system can then query a ruleset about which actions should be available and what to do in response to a UI event. These rules can describe different game modes or tutorial states.

The nuts and bolts of game play should also include an abstraction to allow game events to flow from these rules. You'd have a submodule for moving units, attacking, whatever concrete actions you can perform or the AI can do. In typical game flow you might want an AI module driving decisions of non-player characters and attacks which request random damage amounts. In tutorial mode you probably want purely scripted "AI" with pre-determined attack values.

It's all just a matter of layering. Make each module responsible for *only one thing* and then have "glue modules" for logic that can either simply be different implementations for different game modes or the tutorial or which is completely data-driven if you have the time to build that.

---
Tags: architecture, actionscript-3, tutorials
---


title: Stick 2 btRigidBodies together

text:
# Question
Title: Stick 2 btRigidBodies together
I have a platform with btBoxShape as shape, and I want to rotate it every certain amount of time to simulate a rotating platform.

Right now I rotate it with Ogre (my rendering engine) and use a custom btMotionState to synchronize it with bullet. The thing is that when a player goes on top of it (a player is a btRigidBody with mass 1) the body should stay in the same coordinate relative to the platform and rotate with it. Right now it is kinda bugged and it doesn't rotate properly, and I don't know the exact cause.

What should I do to achieve this effect?

Here is a video with an example of what I want to do: http://youtu.be/z60jiGldX48?t=1m2s

# Answer
> 1 votes
Add a boolean "on\_ground" variable to keep track of if your player is standing, or in midair. Ray cast underneath the player just like you would to see if it is OK to jump.

If your player-\>on\_ground is false, and the ray hits something to stand on, make this object your new "platform" and set player-\>on\_ground to true. Save the *local* (not world) coordinate where the ray hit as your "platform\_offset". You can get this by taking the world space position where the ray hit, and transforming it by the *inverse* of the platform's model matrix.

Otherwise, if player-\>on\_ground is true, then you just transform the platform\_offset by the platform's model matrix. Move the player with it artificially if the platform has moved.

---
Tags: ogre, platformer, bullet-physics
---


# Question
Title: How do I represent projectiles in a video game?
I'm making a simple fixed shooter game, similar to *"Galaga"*,) as part of a presentation I'm doing. I'm wondering what strategies and data structures would people use for tracking projectiles, like lasers fired from the spaceship. A super simple implementation that I've used, before, is to just represent each projectile as a point, and check for collisions with all objects in the scene.

However, this seems costly, in large scenes with many projectiles; I'm wondering what other types of strategies or implementations are used for this type of use case. What do games like FPS use for tracking projectiles (bullets, tank shells, etc)?

# Answer
For *very fast* projectiles (such as lasers or bullets), you could use, a **Ray**.

A ray has a start point and an end point. A (very minimal) data structure for a ray is:

```
struct Ray
{
  Vector3f start, end ;
} ;

```

Looks like this:

(You could also cache the direction vector and length, but I used a very simple defn above).

If the ray is a laser beam that travels at the speed of light, you would just persist the ray (as starting at the gun nozzle and ending on a wall somewhere) for a couple of frames. Anything intersecting the ray each frame takes damage.

If the ray is a slower projectile (like a bullet, for example), the distance the bullet travelled over a timestep is modelled by the ray. The start point is where the ray is at the beginning of the frame, and the end point is where the ray will be after the frame is done. Anything in the bullet's ray's way is damaged by the bullet.

Rays can be efficiently collided with spheres, aabbs, convex hulls etc. Check out my Hullinator project for an actual running program (CTRL+Click to fire rays)
> 8 votes

# Answer
Using a ray works well for instantaneously travelling projectiles such as bullets. For projectiles which have slower speed such as the type you'll make use of for your space game it makes sense to simply track their position in the game world like you would any other entity. What I often do is have a base class called Entity which contains properties of any lasting game object — position, rotation, collision box, etc. My player driven and projectiles then inherit off this and my game world only needs to know how to deal with the super class Entity, not each individual type of entity.

To increase performance it's very common to keep a pool around for any objects you'll be creating and destroying often. When you need a new projectile you'd pull from this pool, modify the new projectile as needed and return it back to the pool when it's expired.
> 3 votes

# Answer
When you want to optimize for collision detection, you could store all game objects in a two- or three-dimensional tree. This data structure makes it very efficient to retrieve all objects in a certain area.

Binary trees do however have the disadvantage that they degenerate easily when objects are added, removed and change their positions, so you will need to auto-balance it.

A compromise which would be easier to implement but not be quite as efficient would be to use a chunk-based approach. Divide the playing field into cubes and keep track of which objects are touching each cube. When you check for collisions with an object, you only need to check it against the object lists of the cubes it is touching (replace "cube" with "rectangle" for a 2d-game).
> 2 votes

---
Tags: game-design, design-patterns
---


title: Open World Object Management

text:
# Question
Title: Open World Object Management
I'm currently creating a system that essentially creates a world at run-time based on a seed I choose. In this system, I made it so that there are certain "chunks" that divide up different sections of the world, and in these sections, I have different meshes that are completely unique to that chunk. Each chunk is also divided into 4 subchunks, which are exactly half the width and height of it's chunk.

The purpose of the chunks and subchunks is so as the player, you could walk around the level, with the current chunk, as well as the adjacent chunks stored into memory with their meshes, and those adjacent chunks, which cannot be seem from where the player is, are loaded, however their meshes are not currently loaded, and as the player moves, the system will load and unload these chunks meshes into memory, that way only the meshes needed to render are loaded in at this time.

The problem that I'm having is when I move from one chunk to another, and load the new chunks meshes, and unload the unnecessary chunks meshes, there's a lag spike that only lasts for about half a second. (But it quite noticable) The spike IS NOT coming from the loading and unloading of the mesh, (my memory manager is fast with allocation and deallocation and the loading and unloading are handled on a separate thread) the problem is when I go to change the memory inside the vertex and index buffers. (Which whenever there is a swap, adds AND removes 4 times each during one game loop.

Does anyone have any idea on how I should handle my open world objects? A good reference would be something along the lines of Skyrim or World of Warcraft; They have the large terrain in these worlds and they are most definitely not 100% loaded in the game at once, so how would I go about making it that so as you progress through the world, objects are handled with little to no skip?

Thanks a lot for the help in advance, and if there is clarification needed, simply ask.

Edit: Added code showing my AddVerts function, which is used to pass vertex data to the GPU.

```
// unsigned int* AddVerts(const VertexFormat *pVerts, const unsigned int nNumVerts)
// returns  :   unsigned int*           offset in buffer to where the mesh is located
// ins      :   const VertexFormat*     vertices to pass on to the GPU
//              const unsigned int      number of vertices allocated for the const VertexFormat*
void *buffer = nullptr;
unsigned int nSize = nNumVerts*sizeof(VertexFormat);

if( ( m_unBufferFlags & D3DUSAGE_DYNAMIC ) != 0 )
    m_pVertexBuffer->Lock(nVertLocation*sizeof(VertexFormat), nSize, &buffer, D3DLOCK_NOOVERWRITE);
else
    m_pVertexBuffer->Lock(nVertLocation*sizeof(VertexFormat), nSize, &buffer, 0);

// copy data to buffer
memcpy(buffer, pVerts, nNumVerts*sizeof(VertexFormat));
m_pVertexBuffer->Unlock();

m_dllOffsets.addTail(nVertLocation);

return &(m_dllOffsets.GetTail()->element);

```

# Answer
What you can do is use multiple vertex buffers for the chunks. When you call the map function, you deny gpu access to that resource, so the gpu must wait for you to be done with the buffer before it can use it again (see link). If you have multiple vertex buffers, say one for filling and one for rendering, the gpu does not have to wait and this might reduce your lag. Think it as the front- and back buffer approach most render systems use to render the result to the screen. One buffer is used for drawing and one is used for displaying, so you don't see the frame being drawn. I think the same approach could help you reduce or even remove the lag spike.

EDIT: my bad, I see now that you use the lock method instead.. You can still give it a try though...
> 2 votes

# Answer
One approach to reduce the lag is to divide the buffer change costs to multiple frames, that way the lag of a half second gets divided to e.g. 3 seconds, so it gets not that noticable.
> 1 votes

---
Tags: directx, gameobject
---


title: First person shooter camera movement

text:
# Question
Title: First person shooter camera movement
I am making an FPS in XNA. I cannot seem to make a FPS camera that I can move Forward, Back, Side to Side using the keyboard. How do I do that?

# Answer
> 2 votes
here is some basic code that will work for you.

```
//class scope fields
Vector3 camPosition, camTarget;

//in the camera Update method
Matrix ViewToWorld = Matrix.Invert(view);

if(/* W key is down */)
{
   camPositon += viewToWorld.Forward * speed;//speed should include a factor of frame delta time
   camTarget += viewToWorld.Forward * speed;
}

// same code as above for S key but use viewToWorld.Backward instead

if(/* D key is down */)
{
   camPositon += viewToWorld.Right * speed;
   camTarget += viewToWorld.Right * speed;
}

//same code as above for A key but use viewToWorld.Left instead

view = Matrix.CreateLookAt(camPosition, camTarget, Vector3.Up);

```

---
Tags: xna-4.0, camera, first-person-shooter
---


title: Java: Basic Movement AI not working

text:
# Question
Title: Java: Basic Movement AI not working
I am working on a basic AI system to get an entity to follow a player. I created both the `player` and the `ghost` entity, but it seems as if the ghost only wants to increment both `x` and `y`, it never wants to do the opposite, or choose only `x` or `y` to use. Here is where I implemented the `ghost` and `player` in my constructor:

```
public MansionAzazel() {
    ...
    TileCoordinate ghostSpawn = new TileCoordinate(52, 50);
    TileCoordinate playerSpawn = new TileCoordinate(54, 52);
    player = new Player(playerSpawn.x(), playerSpawn.y(), key);
    player.init(level);
    ghost = new Ghost(ghostSpawn.x(), ghostSpawn.y(), player);
    ghost.init(level);
    ...
}

```

Here is the update() function for the ghost:

```
public void update() {
    int xa = 0, ya = 0;
    if (anim < 1000000)
        anim++;
    else
        anim = 0;

    if (player.getX() > xa)
        xa++;
    if (player.getX() < xa)
        xa--;
    if (player.getY() > ya)
        ya++;
    if (player.getY() < ya)
        ya--;

    if (xa != 0 || ya != 0) {
        move(xa, ya);
        walking = true;
    } else
        walking = false;
}

```

In which to sum it all up, the `ghost` entity will only and always move in one direction because the coordinates are 0 and I don't know why.

# Answer
> 1 votes
If the intent is the move the ghost toward the player and if the move() method moves the ghost (you haven't given us enough info to be sure), then perhaps the update() method should initialize xa and ya to ghost.getX() and ghost.getY(). It seems to reset xa and ya to 0 every time update() is called.

---
Tags: java, ai, movement
---


# Question
Title: Can I make a flash file I developed to run on Androis / IOS?
I've created a simple game using ActionScript 3.0 and Adobe Flash CS5. Is there any way to run this creation on Android / Apple IOS ? (Even if so, I still have no Idea how to work with "touch" interfaces, just want to know if such thing is possible first.)

# Answer
Yes! You can use Adobe AIR to package and export the Flash file.

http://help.adobe.com/en\_US/air/build/WSfffb011ac560372f-5d0f4f25128cc9cd0cb-7ff6.html
> 4 votes

# Answer
You could port the code to Haxe, which is really easy since the languages (AS3 and Haxe) are almost identical, and just compile it natively for both android and IOS. I think that's better than adobe air... I feel like air is slow.
> 0 votes

---
Tags: android, ios, flash, actionscript
---


# Question
Title: Libgdx , how to get mouse position relative to a Tiled Map
I'm porting a game that i did for Ludum Dare 26, this year, i made it using Contruct2, i decided to port it to Libgdx, for learning reasons,

http://www.ludumdare.com/compo/ludum-dare-26/?action=preview&uid=15150 (check the web version)

My problem is that the Player moves base on the Angle, where the mouse is pointing at, in Contruct2, they have a really nice function called

```
setAngleToward(Mouse.X,Mouse.Y)

```

in libGdx i made this function

```
@Override
public boolean mouseMoved(int screenX, int screenY) {

    Vector2 centerPosition = new Vector2((float)Gdx.graphics.getWidth() / 2, (float)Gdx.graphics.getHeight() / 2);
//  Vector2 centerPosition = new Vector2(getX(), getY());

    screenY = Gdx.graphics.getHeight() - screenY ; //Inverse the Y

        Vector2 mouseLoc = new Vector2(screenX, screenY);

        Vector2 direction = mouseLoc.sub(centerPosition);
        float mouseAngle  = direction.angle();/*(float)(Math. atan2(direction.y, direction.x)); */
        setRotation(mouseAngle);

        return true;
}

```

which works nice, but when i reach the corners on the maps, it give me the wrong angles, because the Player is not centered anymore,

I know the solution is just use "centerPosition" with the player coords, and use "mouseLoc" with the mouse coords but needs to be relative to the tiled map, and that's my problem i don't know how to get those paramenters , screenX and screenY, are the mouse location but base on screen position

im using **OrthographicCamera** and **OrthogonalTiledMapRenderer**

i hope can understand my problem, this is the jar i have right now

https://dl.dropboxusercontent.com/u/2553973/Others/zombiesblocksattack.jar

# Answer
> 6 votes
I was able to find a solution, in order to convert the mouse coords to the coords relative to the tile map, i used:

```
@Override
public boolean mouseMoved(int screenX, int screenY) {

    //screenX, screenY - Mouse Coords

    Vector2 centerPosition = new Vector2(player.getX(), player.getY());

    Vector3 worldCoordinates = new Vector3(screenX, y, screenY,0);
    camera.unproject(worldCoordinates);

    Vector2 mouseLoc = new Vector2(worldCoordinates.x, worldCoordinates.y);

    Vector2 direction = mouseLoc.sub(centerPosition);
    float mouseAngle  = direction.angle();
    setRotation(mouseAngle);

    return true;
}

```

hope this can be useful to other with similiar issue

---
Tags: java, libgdx
---


# Question
Title: How to move around a player in a curved tunnel?
In a scenario where the player moves freely along the walls of a tunnel (like this), what is the best way to move the player along the walls of the tunnel?

I'm using Unity3d game engine. I've tried to remove all gravity and apply relative downward force on the object on every tick. Pressing right or left key applies relative force on the x-axis. But the player object will not rotate along with the walls of the tunnel and hence wont climb. I can calculate tangent to the center of the circle inside the tunnel and rotate the player myself but that wont work with curved tunnels.

# Answer
> 1 votes
You could do a `Physics.Raycast`in the down direction of the player. The normal of the `RaycastHit` this gives you, can then be used to determine the new orientation of the player. Then to "stick" the player to the surface, the new position can be calculated from the hit point, the surface normal and the desired distance from the surface.

For smoother results, do this twice, once a bit left of the player and once a bit to the right, then average.

This should work even when the tunnel cross section is not circular, should you choose so at some point.

# Answer
> 2 votes
The cross section of the part of the tunnel the player is in is always a circle. Simply use the center point of the tunnel as a position and the direction the tunnel is going as a rotation axis for rotating your player. Essentially, if the camera is exactly following the centerline of the tunnel, you'll rotate the player around the Z axis of the camera.

You may be able to achieve this by setting the origin of the player above the player by the radius of the tunnel. Then simply move the player along the center of the tunnel, and rotate about the player Z axis. Or make a parent object called "tunnelfollower" and put the player as a child object, offset with the tunnel radius.

That'll take care of curves in the tunnel and you won't be dealing with gravity. This rotation doesn't change the rotation of the player relative to the center of the tunnel. This means relative to the tunnel walls, the player up is aligned to the normal.

# Answer
> 1 votes
I think the best solution is to turn off physics. Make it work in not curved tunnels, then use a vertex shader to create the curves. If you use the same transformation both in tunnels and the player, you achieve the effect you desire.

---
Tags: unity, physics
---


# Question
Title: How can I check the shader model capabilities of an adapter?
I'm writing an application that targets Direct3D11 (through SlimDX) and shader model 5.

When I'm running it on a system that doesn't have SM5 capable hardware, I will get a NullReferenceException when trying to access the techniques in the compiled effect instance.

How can I check if the adapter is capable of this before I even attempt to use any of these features?

# Answer
> 1 votes
You can check the `FeatureLevel` property of the Device object. If it returns `Level_11_0` then it means that the hardware supports SM5.

---
Tags: directx11, slimdx
---


# Question
Title: Handle game flow in turn-based game on server or client side?
Im building a turn-based game using websockets and nodejs. At the end of each turn I want to show some scores before starting the next turn. Should that be controlled by the server using a timer? Or should the client start a timer and tell the server when it's ready for next turn? Just to keep the load of the server. What is the pros/cons?

# Answer
You don't necessarily need a timer on the server but you do need the server to be checking time(1) That is, that game should keep track of when the turn started, so that it can compare against this timestamp when it receives moves from the client.

(1) Assuming the time limit for turns has any effect on the game results. The rule of thumb with these things is that anything that affects the game results must be handled by or verified on the server, or else players will cheat. Anything that doesn't affect the game results should be handled on the client in order to reduce load on the server and the game's bandwidth usage.
> 3 votes

---
Tags: turn-based, websocket
---


# Question
Title: Can someone explain this occurrence with a fbx model in xna?
Because this is kind of weird to explain, let's show you what I mean. This is in my game. When I import this base ship model, it should be at (1000,1000,1000), but the model acts like it's at (1000,1000, 0). Note it is positioned correctly when I use a .x model. So it has to be the model. I need to know what's wrong with it.

Here is the model file, tell me if anything is wrong with it: https://dl.dropbox.com/u/92848165/station2.FBX

https://i.stack.imgur.com/CVUed.jpg

EDIT: The model works if you import it into Google Sketchup...but you lose the textures, not very nice.

# Answer
I realize that this is really really late....

The only solution to this that crosses the mind is that the model isn't centered in the origin....

Try making the model in a different software (importing / exporting again).... Use blender as it is free and is pretty easy to use:

http://www.blender.org/
> 1 votes

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


# Question
Title: Why do loot drops contain (mostly) useless items?
I was thinking about this and couldn't figure this out. In Diablo you kill enemies and they drop random things. But usually the drops are worthless to you relative to what you already have equipped. Why bother building a drop system that gives you crappy drops? Maybe I'm not communicating my question well so I'll provide an alternative implementation:

Instead of frequently dropping crappy items and rarely dropping good items, why not *only* rarely drop good items?

I guess that crappy items adds to the addictive-ness somehow, but I don't understand why. Why is dropping crappy items part of the design? What does that add?

Edit: FWIW, I have been referring to Diablo 2 as my reference, not D3. But it's still interesting to see answers explaining why D2 was more addictive.

# Answer
> 112 votes
Usually, they're not totally worthless. While they're not better than what you have equipped, the items you can' wear can usually be sold or broken down and used in crafting. However, the psychology behind it is interesting.

These small, mostly worthless items are called reinforcers(more). They strengthen desired activity. In this case, playing the game and killing baddies.

Mindless, repetitive tasks are more enjoyable with small frequent rewards, instead of rare large rewards. Giving players a "physical" reward works well, even if it's not worth much. The "physical" part is important. XP or money are really just numbers, not an actual object (in game object) that the player can see. The psychological effect very similar to grinding XP or gold however, it's a reward schedule that keeps the player coming back for more.

Getting these small frequent low interest items, increases the desire to continue playing, since the good reward is right around the corner right? This likely takes advantage of the Gambler's Fallacy.

(source)

This is a big reason people continue to buy scratch off tickets, or continue to pour money into a slot machine. Since they haven't won yet, they believe the probability of winning big is getting larger and larger.

Further, it's expected, and it should be. If players are continuously opening up the loot window, only to find no loot, they're going to stop looking and they're going to stop feeling rewarded. Even something little, not worth much, will show the player that they got *something* for their effort.

# Answer
> 17 votes
Because there has to be a heirarchy of stuff. Common, uncommon, rare and ultra rare. It hooks into that primal part of people that likes getting stuff, and gets frustrated if it doesn't.

Slot machines are built this way. They pay out often, but only occasionally give the big prizes. The big prizes could be bigger if they only ever paid about big prizes. But then people wouldn't play, because losing 100 times in a row makes them quit. But if they win a buck here and 10 bucks there, they keep playing.

So you do the same with your loot drops. The player gets used to the hope every time something drops that it's something good.

# Answer
> 6 votes
Besides the obvious psychological aspect in Byte56's answer, I wanted to add something. There are a few interesting things regarding your example, Diablo 3.

Blizzard made quite and experiment with their auction house, which effects the way they made items and item stat rolls behave. I don't want to insinuate anything, but it is in Blizzard's interest that the chances a player finds an upgrade to their gear gets smaller, the better their gear gets. It makes players depend on the auction house, and of course animates them to use the real money auction house.

Since the announcement of the release of the console version, it was clear that they went a complete different way. There will be no auction house included at all, instead players are more likely to find items with stats they actually need. If they would have just removed the auction house and implemented the same loot system, players would become very frustrated at some point.

So it might not be just a loot system, but a business model.

# Answer
> 4 votes
Most drops will be crap because you are comparing them the best drop you've gotten so far.

Roll a die 50 times. Most rolls will be lower than the best roll so far, simply because you're going to roll maximum pretty soon; then all other possible rolls will be "bad".

The only way to get away from that is to constantly increase the maximum and minimum roll. You could for instance add the number of rolls you've made so far to the die roll. But even then, unless the increase per roll is high compared to the variance, most rolls will still be low as it takes many increases for one good roll to be negated. (I won't do the math now, but I suspect +1 per roll is still in the "most rolls are lower"-category.)

In Diablo et cetera you will of course continuously get better loot, as it scales to your level, but it doesn't improve fast enough to cancel this effect.

It is possible to design a "loot-curve" such that new items are better than old ones, but there are issues with that. You have to ramp up the power level of items quickly, or have very little randomness in how good each item is or give out loot only rarely.

As to why such loot-curves are rare: they don't suit a majority of games.

First of all, it's hard to rate different abilities against each other, even a two stat weapon, speed and damage, is *hard* to rate, given preferences of players, interaction with armour et cetera.

Secondly, most games expect a long playtime, so power gain must be spread out over a long time. Nethack, in my opinion, has *mostly* useful loot; but has short playtime and your powerlevel goes from worthless tourist to demigod capable of killing Death.

Third: such a loot system isn't very interesting. http://progressquest.com/ is a good example of such a system. There are no choices to make: anything you pick up is better than what you had before.

# Answer
> 4 votes
On topic of Diablo III's Auction House:

Low drop rates encouraged players to use the auction house at first, but in the end AH was the main reason for people quitting the game. I didn't really understand the reason behind this (my personal opinion was "just don't use AH if you don't like it"), but after reading the answers here I think I can finally see the problem.

AH had too great of an an impact on what the players considered a "good gear" to be. Let's say there's a new player who played about 10 hours without touching the auction house. Assuming the drop rates are set to low, the player's gear is most likely pretty bad at this point. But the player doesn't know that. He is happy for every new, ever so slightly stronger item that drops. However, this all changes after visiting the AH. The player suddenly realizes that most of his gear is very bad, and buys some new stuff from the auction house. He goes back to playing... but now an item which would be previously considered an improvement can't compare to the shiny gear bought on auction house. And this is the point where the whole "psychological addiction magic" disappears because the game rewards just don't feel good enough, all the drops start to feel "annoyingly worthless".

The scale of the game probably escalated this problem even further. Lets say a "rare good item" is something that drops averagely once per 20 hours of gameplay. When the playerbase is high enough those items turn out to be quite common and cheap on the auction house. They are easy to buy so a player might think they are easy to find... But they aren't. A single player still needs to play those 20 hours. Well, now that's discouraging...

# Answer
> 3 votes
I just wanted to mention this study which provides a scientific basis for Byte56's answer and everyone else talking abut the link with gambling.

> The game was simple: when an icon on the left-hand reel lined up with the same icon on a right-hand one, the volunteer won a cash prize of 50 pence (75 cents). \[...\] A near miss came \[when\] the right-hand reel \[...\] eventually stopped within a space or two of lining up with a matching icon on the left.
>
> The researchers found that those who scored highest in gambling severity also showed the most activity in the midbrain area in response to near misses. (They did not differ in their response to real wins, however.)

Note that near-misses gave no reward at all.

Almost winning in the context of loot drops means finding a neat sword that *could* be really good, casting identify on it, but finding it's not magic or anything. You're just going to sell it at the next shop (or if you're already rich in the game you might just trash it to make room for more loot), but if you'd received a drop of equivalent gold it wouldn't have that "near-miss" feeling.

# Answer
> 1 votes
Worthless items in my opinion can be categorized as vendor trash, and a means to actually make the player feel more accomplished when they actually get a good item.

There are a series of reasons why a lot of popular ARPGs spawn a lot of items rather than a select few. First of all, it makes the good items feel more valuable than they actually are. Second of all, randomly spawned items are a lot like gambling where players feel like the more they grind the better their chances are at getting a good item. Although, I honestly would not suggest spawning a lot of vendor trash to them, because games like Diablo III really messed up on this. You also should not have item affixes that are worthless and just there to promote vendor trash. Look at games more like Torchlight and Path of Exile in terms of item generation, because they did a lot better job at it. Good luck!

# Answer
> 0 votes
The simplest answer? To get you to keep playing. If everything had an equal weight in terms of rarity or probability or usefulness, you wouldn't have to play very long to collect everything in the game. This is doubly so when the amount of time you play is directly related to how much money you are willing to spend per month.

---
Tags: game-design, psychology
---


# Question
Title: declaring variables in a render/game loop: good idea or bad?
I was just wondering how most of you like to declare your variables: for a variable you know will be used and changed frequently (i.e. every frame), do you declare those outside of the loop and simply change them? Or do you declare new variables every time around and count on the GC and function scope to clean up 60 little variables every second? Which is more efficient and reliable? Flash has a decent garbage collector, but I've had problems with leaks before.

Here's some example AS3 code with collision checking in Flashpunk:

```
public function update():void
{
    var bullet:Bullet = collide("bullet", this.x, this.y) as Bullet;

    if (bullet)
    {
        FP.world.recycle(this);
        bullet.destroy();
    }
}

```

vs.

```
var bullet:Bullet;

public function update():void
{
    bullet = collide("bullet", this.x, this.y) as Bullet;

    if (bullet)
    {
        FP.world.recycle(this);
        bullet.destroy();
    }
}

```

# Answer
There's no heap memory allocation taking place here and that's the only type of memory allocation you should worry about.

```
var bullet:Bullet = collide("bullet", this.x, this.y) as Bullet;

```

This line checks if the entity collided with another entity of type "bullet" and returns the first entity of that type. And since the method is `Entity`, there's a cast to `Bullet` (although I fail to see why this is even necessary). The important thing here is that `var xy` is **not** allocating memory with each iteration (except for memory on the stack, but that's a non issue), nor does it trigger garbage collection. It's basically the same as writing `var bullet` outside of the function scope.

```
if (bullet)
{
    FP.world.recycle(this);
    bullet.destroy();
}

```

The rest of the code recylces the current entity by feeding it back into an object-pool. The `destroy` method on the bullet is not part of the FlashPunk engine (AFAIK), but it might also feed it back to an object-pool or maybe also free references, so that the bullet can be garbage-collected. This is actually a point where your two code examples might behave differently. If you have the `bullet` variable as a class-member (eg. outside of the function scope), then you'll keep a reference to the bullet which will *prevent* garbage-collection of the bullet as long as the `bullet` variable still points to the bullet. FlashPunk even seems to enforce/encourage good practice by providing object-pools etc.

**TL, DR**: Unless you need the `bullet` variable *outside* of your update loop, you should always use the local scoped variables.
> 3 votes

# Answer
There isn't much difference between the two approaches IMO. I'm guessing the collide function creates and returns a new object in every tick anyway. It's okay to use any approach in most cases.
> -1 votes

---
Tags: flash, actionscript-3, game-loop
---


# Question
Title: Creating a fragment shader to darken a white texture over time - OpenGL GLSL
So as a part of learning OpenGL, I've now decided to try and be a bit more creative with shaders, as part of a practice game I'm making using C/OpenGL.

I'm completely new when it comes to working with shaders, so I'm still trying to get used to the thought process behind creating something with it. To this extend, here's what I want to attempt.

As a part of the gameplay, the entire background of the game consists of a white, plain, 2D texture. The white texture should slowly animate black circles into it over time, until finally the entire texture is completely black.

I've considered some different approaches to the problem, and would like to know which one will be the most practical when it comes to shaders.

**Using framebuffers**: As I've understood from looking around the internet, you can't really, say, apply certain colors to a specific area of fragments in your fragment shader (like creating a black circle), and then save the state of those fragments for the next frame. Instead, I would have to apply the effect, and render the texture to a framebuffer and then re-use it again the next frame. I could then continuously do this slowly add black circles to the texture. The problem is, is this really too much work to do for something simple as this? Or would it be fast enough? As far as I've seen, framebuffers are usually used to post-process effects for entire scene frames. This would not be for the entire scene, only for the background. The advantage of this approach would be that it's relatively simply to work with as you're only working on one texture.

**Creating individual circle objects with own fragment shaders**: This was another approach I thought about doing. Basically, instead of having one shader work on the entire background texture, I would simply spawn textured quads that each individually run a fragment shader that just turns their texture black over time using a simple percentage value input as a uniform. The disadvantage of this solution is that you make it a bit more complex by having to handle more objects at runtime, instead of simply working with one texture. More vertices would also have to be handled when rendering.

Of these two approaches, I don't know really what would be a good solution to run with. I would like to use the framebuffers approach but I don't know if I would "abuse" the technique with this kind of problem or not.

Or perhaps there's another way of doing this that I've completely missed because I'm new to shaders, in that case other suggestions would be welcome!

Thank you all for your help :)

# Answer
> 1 votes
It sounds like what you called the framebuffer approach would work fine. You'd just have an framebuffer that would be modified a little each frame, gradually accumulating the summed result of all the circles. That's a bit different from how framebuffers are often used - clearing them and re-rendering them from scratch each frame - but that's no big deal.

The second approach is similar to how a particle system would work. It would also work fine as long as you don't have millions of circles, but you're right that it does require more code infrastructure and has more moving parts, so to speak. (For learning purposes, it might be a good exercise to implement the second approach at some point, as it could serve as an introduction to dynamic vertex buffers and instancing.)

---
Tags: opengl, shaders, glsl, c, fragment-shader
---


# Question
Title: Monogame/SharpDX Texture2D doesn't hold value
The problem I have discovered is most likely between classes, so I dont really have much option but to post the whole code here: https://www.dropbox.com/sh/smyw9t1ap3by2vd/pBX-aJJ-Qx

I have been having some trouble with spritebatches rendering textures recently using monogame for windows 8 with xaml where it throws an error after a few seconds of running. The error only occurs after a few seconds, though the less efficient or more textures i render, the quicker it crashes. After doing a git submodule update, the error message is entirely gone, but the textures still dissappear from the screen leaving just the cornflower blue.

The folks on GitHub have decided that this is a problem with my code and not theirs, which means I am definitely doing something wrong. For reference, here is the issue thread: https://github.com/mono/MonoGame/issues/1927. Thanks for any help!

UPDATE: I have identified the source of the problem. It has to do with declaring and holding the texture.

```
    protected override void LoadContent()
    {
        _spriteBatch = new SpriteBatch(GraphicsDevice);
        ContentManager myManager = new ContentManager(Content.ServiceProvider, Content.RootDirectory);
        terrainEngine.Load(myManager);
    }

    ContentManager content;
    public void Load(ContentManager content)
    {
        this.content = content;
        blockTextures = content.Load<Texture2D>("Graphics\\Blocks");
        spriteFont = content.Load<SpriteFont>("Graphics\\SpriteFont1");
    }

```

Now, if I call Load(content) from inside the terrainEngine class Update method, then the program works, otherwise, the textures disappear after a second.

# Answer
I'm thinking you're declaring something that's inside a scope that's getting cleaned up with the garbage collector (which explains why using more memory made it happen faster and explains the delay between declaring the textures and them disappearing).

Specifically, I think it's your `ContentManager`, declared inside your `LoadContent()` function:

```
protected override void LoadContent()
{
    _spriteBatch = new SpriteBatch(GraphicsDevice);
    ContentManager myManager = new ContentManager(Content.ServiceProvider, Content.RootDirectory);
    terrainEngine.Load(myManager);
}

```

Even though you're setting assigning it to a global variable later:

```
ContentManager content;
public void Load(ContentManager content)
{
    this.content = content;
    blockTextures = content.Load<Texture2D>("Graphics\\Blocks");
    spriteFont = content.Load<SpriteFont>("Graphics\\SpriteFont1");
}

```

Now that global variable is just assigned to something that's going to get cleaned up when it leaves scope.

Try assigning directly to your global variable:

```
protected override void LoadContent()
{
    _spriteBatch = new SpriteBatch(GraphicsDevice);
    content = new ContentManager(Content.ServiceProvider, Content.RootDirectory);
    terrainEngine.Load();
}

public void Load()
{
    blockTextures = content.Load<Texture2D>("Graphics\\Blocks");
    spriteFont = content.Load<SpriteFont>("Graphics\\SpriteFont1");
}

```
> 1 votes

---
Tags: c#, textures, monogame, spritebatch, sharpdx
---


title: Is Ada suitable for game development?

text:
# Question
Title: Is Ada suitable for game development?
Would Ada be a practical language for game development (at least for the PC--I understand there aren't compilers for PlayStation and other consoles)?

It has bindings to OpenGL, it has decent performance, and it's less error-prone than C++. Please feel encouraged to support your point with relevant example projects you know about.

# Answer
Yes. But it depends entirely on the game you want to make, and how much time you want to spend making it.

Clearly, Ada is not a well known language in the world of game development. That comes with it a few complications:

* You'll have to create most of your own tools/libraries (pathfinding, texture/model parsers, animation libraries, etc.)
* I don't think any game engines exist using Ada, so you'll first be making an engine (not a game) (graphics engines for Ada *do* exist, so at least you'll have a start...)

**These tasks will take you a long time. Likely longer than any theoretical gains from Ada being "less error-prone" to develop in.** Given the limitations, I'd say it's viable for game development, but not practical. At this point, I think the only reason to develop a game in Ada is for the novelty of developing a game in Ada.
> 7 votes

# Answer
The commercial game 'Strategic Command' was written in Eiffel. You can write a the game logic in just about any language, the challenge lies in the GUI and IO parts. Your ADA environment should have capable libraries.

Btw there is an Ada version for .net but with serious limitations due to the constraints of the platform.
> 1 votes

---
Tags: opengl
---


title: Sprite with alpha Blending in 3D world

text:
# Question
Title: Sprite with alpha Blending in 3D world
I'm working on a game in a 3D world with elements 2D only (Like Don't starve game) for Android and IOS.

Currently, I've managed "Sprite" without alpha blending, I've just put a condition in the pixel shader to test if pixel alpha channel is null:

```
if ( texture.a < 0.5 ) discard;

```

Everything working here. (On old devies like an HTC desire mobile, this condition destroy framerate but it's another problem :/)

But recently, I've tried to had another Sprite with AlphaBlending activated:

```
glCheck( glEnable(GL_BLEND) );
glCheck( glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) );
glCheck( glDisable(GL_DEPTH_TEST) );

```

My sprite transparency is ok but it is now in front of everything in the scene. (Probably due to glDisable(GL\_DEPTH\_TEST)).

How can I handle depth with alpha blending activated?

EDIT: A video to show the problem: http://www.youtube.com/watch?v=W0gpBekEwW8&feature=youtu.be

# Answer
> 5 votes
Alpha blending in 3D is tricky, simply due to the fact that you're (usually) still rendering the quad (or polygon) to the depth buffer using the depth buffer, even if your visible texture is just a tiny part of that.

To achieve proper rendering you'll have to render everything in the correct order, essentially from back to front. If you don't use the correct order you'll get weird things like objects disappearing behind otherwise transparent surfaces (e.g. water or something like the thing you experienced).

For example, assume you'd like to render a scene with a sphere sitting in shallow water:

* Without transparency you're able to render these in any order and it will look good.
* But if you're making the water transparent, you'll have to render the sphere first (as it's partially "behind" the water surface).
* Otherwise the sphere won't be drawn underwater (simply due to the depth test failing there).

The problem is the same if you're drawing something with varying levels of transparency (like a texture with 100% transparent parts).

I don't know your actual scene, but I'd say you've got a 3D world with 2D sprites?

That case I'd say render your 3D world first, then all your sprites from back to front (far to close). If you've got transparent surfaces (like windows or water), you'll have to render that together with your sprites and in correct order rather than with your 3D world.

---
Tags: opengl, opengl-es2, transparency, alpha-blending
---


title: 3d Wall sliding collision

text:
# Question
Title: 3d Wall sliding collision
I'm working on collision for walls in my game and the way I currently have it I get stuck walking into a wall. I'm trying to make my character slide on the walls but still collide.

My character moves off of a vector I create using the angle he is facing.

this is my collision function:

```
    private static bool CheckForCollisions(ref Crate c1, ref Player c2,bool direction)
    {
        for (int i = 0; i < c1.model.Meshes.Count; i++)
        {
            // Check whether the bounding boxes of the two cubes intersect.
            BoundingSphere c1BoundingSphere = c1.model.Meshes[i].BoundingSphere;
            c1BoundingSphere.Center += c1.position + new Vector3(2, 0, 2);
            c1BoundingSphere.Radius = c1BoundingSphere.Radius / 1.5f;

            for (int j = 0; j < c2.model.Meshes.Count; j++)
            {
                BoundingSphere c2BoundingSphere = c2.model.Meshes[j].BoundingSphere;
                if (direction)
                    c2BoundingSphere.Center += c2.position + new Vector3(c2.getPlannedDirection().X, 0, 0);
                else if (!direction)
                    c2BoundingSphere.Center += c2.position + new Vector3(0, 0, c2.getPlannedDirection().Y);
                //c2BoundingSphere.Center += c2.position;

                if (c1BoundingSphere.Intersects(c2BoundingSphere))
                {
                    return true;
                }
            }
        }
        return false;
    }

```

This is my update:

```
for (int x = 0; x <= 29; x++)
        {
            for (int y = 0; y <= 29; y++)
            {
                if (crate[x, y].getType() == 11 && collisionEnabled)
                {
                    if (CheckForCollisions(ref crate[x, y], ref player,true))
                    {
                        player.clearPlannedDirectionX();
                        //Console.Write(player.getPosition().X + "," + player.getPosition().Y + "," + player.getPosition().Z);
                        //movePlayer = false;
                    }
                    if (CheckForCollisions(ref crate[x, y], ref player,false))
                    {
                        player.clearPlannedDirectionZ();
                        //Console.Write(player.getPosition().X + "," + player.getPosition().Y + "," + player.getPosition().Z);
                        //movePlayer = false;
                    }
                }
            }
        }

```

# Answer
This can happen because the position increment may take the character inside the bounding sphere where you have cleared the planned direction. So unless your player has a velocity component in y direction, it might not come out.

BTW, shouldn't this

```
else if (!direction)
                c2BoundingSphere.Center += c2.position + new Vector3(0, 0, c2.getPlannedDirection().Y);

```

be (last Y --\> Z)

```
else if (!direction)
                c2BoundingSphere.Center += c2.position + new Vector3(0, 0, c2.getPlannedDirection().Z);

```
> 1 votes

---
Tags: xna, c#, 3d, collision-detection
---


title: Local shape color blending

text:
# Question
Title: Local shape color blending
I am trying to implement this in Unity 4 Pro.

But I am stuck in the blending part. I don't understand how you could blend multiples textures/colors using multiples volumes on an object. How could you access those volumes in the shader and check for "collision"?

It's seems to be very similar to vertex/pixel lighting. But maybe I am wrong.

Here is the simple effect I am trying to create.

# Answer
> 2 votes
Essentially this looks like something where you'd need a custom blending function where the result will depend on the distance to the outlines of the actual shape.

* For each shapve covering a pixel determine how close that point is to the outline of the shape.
* For a circle this could be something as simple as `1 - (distance_to_center / radius)`.
* For a rectangle it would be similar, determining judging the shortest distance to any border.
* Then compare these values of all shapes involved - the ratio will tell you how to mix colors:
    + If both have the same value, you mix the colors 50:50.
    + If one value is 1, the other 0.5 you'd mix the colors 67:33.

# Answer
> 2 votes
I can't tell you how to do that in a shader, but I can at least explain the math.

Basically, all your objects have two textures: an RGB color texture (which in your example is just a solid color for each object) and a weight texture (which in your example is just a radial gradient). In practice, you could conveniently store the weight as the alpha component of a 4-component RGBA texture (although you *won't* be using it for normal alpha blending). Alternatively, for simple shapes and gradients like these, you can just calculate the weight for each object procedurally in your shader.

Now, to calculate the color of each pixel, you take the weighted average of the colors of the objects that overlap that pixel. That is, if object *k* has weight *Wk* and color *Ck* = (*Rk*, *Gk*, *Bk*), then you'd calculate:

*C*sum = (*W*1 * *C*1) + (*W*2 * *C*2) + (*W*3 * *C*3) + ...

and:

*W*sum = *W*1 \+ *W*2 \+ *W*3 \+ ...

and let the color of the pixel be *C*avg = *C*sum / *W*sum.

Note that you can avoid the multiplications in calculating *C*sum if you store the color channels premultiplied by the weight. Also note that it's possible for both *C*sum and *W*sum to be zero, e.g. if no objects overlap a given pixel. In that case, you need to decide what color to use; your example picture appears to be using black for that case.

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


title: XNA changing color alpha

text:
# Question
Title: XNA changing color alpha
I know I can take a color and multiply it by a float to reduce its alpha like that:

```
Color color = Color.Green * 0.15f;

```

But how do I return the color's alpha to it's original value?

I tried doing this:

```
color.A = 255;

```

But it seems like I get a different color. (The RGB are different then those of the original color).

Also, just changing the alpha of the original color (directly, not by multiplying) doesn't make it transparent..

# Answer
You are multiplying all color components, not only the alpha channel (`Color.Green * 0.15f;`) To only change the alpha:

```
Color color = Color.Green;
color.A *= 0.15f;

```
> -2 votes

---
Tags: xna, color, alpha
---


# Question
Title: Box2D: Efficient method to create b2Chainshapes for a tile-based map?
I'm working on a platforming game with tile based levels. I store the collision model for my tileset in an array.

This is how the collision model for a 4x4 tilesheet would look like (I can't post pictures yet so this link will have to suffice: Tileset example). The red dots are the vertices of the b2ChainShape.

When I load a level, I look up the collision model for each tile and create a b2Body at the corresponding place. The problem is that between the tiles, my character can experience a "bump" because it gets stuck on the edge of the shape of the next tile's body.

Is there an existing algorithm to connect the bodies of neighbouring tiles to a single b2ChainShape? Or should I ditch the idea of tile-based collision models all together and simply create the collision model for the whole map with the Tiled map editor? I don't create the the collision map with the Tiled map editor at the moment, because it is very time consuming for slopes and hills.

# Answer
You could just walk through your tiles in a top-left-bottom-right way, then create an outline for each of the connected tiles programmatically, similar to the marching squares algorithm: http://en.wikipedia.org/wiki/Marching\_squares

Each time a piece of the "countour line" changes direction, you create an edgeshape for it. You can now set so called ghost vertices for these edge shapes; vertex0 for the current edgeshape to vertex2 of the previous edgeshape and vertex3 of the previous edgeshape to vertex1 of your current edgeshape, this process is explained here: http://www.iforce2d.net/b2dtut/ghost-vertices

This would basically give a hint to box2d how to resolve the collision response to contact points between the different edgeshapes.
> 0 votes

---
Tags: collision-detection, box2d, tiles
---


# Question
Title: HLSL grayscale pixel shader: How to get the original colors of the model?
The following code gives me a completely black colored model, while it should be a model shaded in greyscale:

```
float4 SimplePixelShader(VertexShaderOutput input) : COLOR0
{
    //some lambertian shading done in the code I left out here

    return color;
}

sampler TextureSampler = sampler_state
{
    Texture = <ScreenTexture>;
};

float4 GrayscalePixelShader(float2 TextureCoordinate : TEXCOORD0) : COLOR0
{
    // Get the color.
    float4 color = tex2D(TextureSampler, TextureCoordinate);

    // Turn pixel to grayscale.
    float grayscale = dot(color.rgb, float3(0.3, 0.59, 0.11));
    color.r = grayscale;
    color.g = grayscale;
    color.b = grayscale;
    color.a = 1.0f;

    // Return the result.
    return color;
}

technique Simple
{

    pass Pass0
    {
        VertexShader = compile vs_2_0 SimpleVertexShader();
        PixelShader  = compile ps_2_0 SimplePixelShader();
    }

    pass Pass1
    {
        PixelShader  = compile ps_2_0 GrayscalePixelShader();
    }
}

```

As far as I could find out the problem lies here:

```
// Get the color.
float4 color = tex2D(TextureSampler, TextureCoordinate);

```

The whole lambertian coloring works, the grayscale seems to work properly by itself after some testing, but what doesnt seem to work is getting the red lambertian shaded model colors. Anybody any clue what I'm doing wrong?

Edit: Thanks to a lot of help in the chat from LuisW I now have a working greyscale shader, I didnt have to change anything about my GreyscalePixelShader but I did have to remove the second pass of the simple techique and put it into a seperate technique, as such:

```
technique Greyscale
{
    pass Pass0
    {
        PixelShader = compile ps_2_0 GrayscalePixelShader();
    }
}

```

I also had to update my XNA/C# Draw method to create a fullscreen quad that I rendered my scene with the first technique to so I could use my greyscale technique on that quad as an input. Mind you, the method Im using, with spritebatch, is known to be slow (for me that didnt matter, but if you need fast, then drawing the quad directly is supposably faster) My updated draw method:

```
protected override void Draw(GameTime gameTime)
{
    this.device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DeepSkyBlue, 1.0f, 0);

    PresentationParameters pp = this.device.PresentationParameters;
    RenderTarget2D renderTarget;
    renderTarget = new RenderTarget2D(this.device, pp.BackBufferWidth, pp.BackBufferHeight, true, pp.BackBufferFormat, pp.DepthStencilFormat);
    this.device.SetRenderTarget(renderTarget);
    this.device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DeepSkyBlue, 1.0f, 0);
    Rectangle screenRectangle = new Rectangle(0, 0, screenWidth, screenHeight);

    // Get the model's only mesh
    ModelMesh mesh = this.model.Meshes[0];
    Effect effect = mesh.Effects[0];

    effect.CurrentTechnique = effect.Techniques["Simple"];

    //<left out some noninteresting worldmatrix calculations here not relevent for this question/answer>

    device.DepthStencilState = DepthStencilState.Default;
    device.BlendState = BlendState.Opaque;

    mesh.Draw();

    this.device.SetRenderTarget(null);

    effect.CurrentTechnique = effect.Techniques["Greyscale"];

    spriteBatch.Begin(0, BlendState.Opaque, null, null, null, effect);
    spriteBatch.Draw((Texture2D)renderTarget, screenRectangle, Color.White);
    spriteBatch.End();

    base.Draw(gameTime);
}

```

# Answer
We had a chat conversation about it because it turned out out that there was a bigger problem than just an issue with the shader.

Heres my summary:

Multipass rendering using a single technique is very limited and it´s impossible to access the result of the first pass in the second. Inorder to get the first passes results you have to:

* render the first pass into a texture
* apply the second passes effect
* render a fullscreen quad textured with the texture from the first pass

that way you can read the current pixels result of the first pass throught a texture lookup in the second pass and apply the effect on it.

Implementation details got edited into the question text, so i wont post them again.
> 1 votes

---
Tags: hlsl, post-processing
---


# Question
Title: Can I simplify the inequality "distance(p1, p2) < distance(p1, p3)?"
I am working on some vector logic, so am asking: can I save processor time by simplifying this inequality:

```
distance(vector1, vector2) < distance(vector1, vector3)

```

I see that `vector1` is repeated in both cases.

# Answer
> 24 votes
**Yes**, you can simplify this. First, stop calling them vectors. They are points. Let’s call them `A`, `B` and `C`.

So, you want this:

```
dist(A, B) < dist(A, C)

```

Replace distances with distances squared, then with dot products (from the definition of the Euclidean length. Replace `AC` with `AB + BC` (now these are real vectors). Expand, simplify, factor:

```
dist(A, B)² < dist(A, C)²
dot(AB, AB) < dot(AC, AC)
dot(AB, AB) < dot(AB + BC, AB + BC)
dot(AB, AB) < dot(AB, AB) + dot(BC, BC) + 2 dot(AB, BC)
0 < dot(BC, BC) + 2 dot(AB, BC)
0 < dot(BC + 2 AB, BC)

```

There you are:

```
dot(AB + AC, BC) > 0

```

With your vector notation:

```
dot(v2 - v1 + v3 - v1, v3 - v2) > 0

```

That’s a few additions and one dot product instead of the previous two dot products.

# Answer
> 16 votes
**Yes.** Assuming your `distance` function uses a square root, you can simplify this by removing the square root.

When trying to find the larger (or smaller) of a distance, `x^2 > y^2` still holds true for `x > y`.

However, further attempts to simplify the equation mathematically are likely pointless. The distance between `vector1` and `vector2` is not the same as the distance between `vector1` and `vector3`. While the equation can be simplified mathematically as Sam's answer shows, the form it's currently in is likely as simple as you'll get from the processor usage perspective.

# Answer
> 0 votes
Some maths could help.

What you are trying to do is:

```
<v1, v2> < <v1, v3> =>
sqrt((y2-y1)^2+(x2-x1)^2) < sqrt((y3-y1)^2+(x3-x1)^2) =>
y2^2 - 2*y2y1 + y1^2 + x2^2 - 2*x2x1 + x1^2 < y3^2 - 2*y3y1 + y1^2 + x3^2 - 2*x3x1 + x1^2

```

From what you can remove repeated variables and group some others. The operation that you have to check is:

```
y3^2 - y2^2 - 2*y1(y3-y2) + x3^2 - x2^2 - 2*x1(x3-x2) > 0

```

Hope it helps.

# Answer
> -1 votes
*The real question* seems to be how to reduce computation for determining the nearest object?

*Optimising* this is often done in games, although with all optimisations it should be profile-guided and, often, doesn't *simplify* things.

The way to avoid unnecessary distance computations to determine the nearest thing - or all things within a certain range - is to use a *spatial index* e.g. an octree.

This only pays off if there are a large number of objects. For just three objects, it is unlikely to pay off and certainly doesn't *simplify* the code.

# Answer
> -3 votes
it depends on what the output of distance(v1,v2) is

if it is a decimal (float or double) over a vector it is likely that distancesquared would be a lot quicker

---
Tags: vector
---


# Question
Title: HLSL Gaussian blur pixelshader: blur is not occurring
I am trying to use postprocessing to create a gaussian blur, however, no blur is to be seen, what am I doing wrong?

I have included the full code at the bottom of this post in a google docs link, but here are the most important bits and pieces.

Part of the xna draw method:

```
RenderTarget2D renderTarget;
renderTarget = new RenderTarget2D(this.device, screenWidth, screenHeight, true, pp.BackBufferFormat, pp.DepthStencilFormat);
this.device.SetRenderTarget(renderTarget);
this.device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DeepSkyBlue, 1.0f, 0);
Rectangle screenRectangle = new Rectangle(0, 0, screenWidth, screenHeight);

// Set the effect parameters (the 'simple' technique creates a red lambertian shaded model, like is shown on the image below)
effect.CurrentTechnique = effect.Techniques["Simple"];
effect.Parameters["TextureWidth"].SetValue(screenWidth);
device.DepthStencilState = DepthStencilState.Default;
device.BlendState = BlendState.Opaque;

// Draw the model
mesh.Draw();

// Render our scene
this.device.SetRenderTarget(null);

effect.CurrentTechnique = effect.Techniques["GaussianBlur"];

spriteBatch.Begin(0, BlendState.Opaque, null, null, null, effect);
spriteBatch.Draw((Texture2D)renderTarget, screenRectangle, Color.White);
spriteBatch.End();

```

The pixelshader:

```
float Pixels[13] =
{
   -6,
   -5,
   -4,
   -3,
   -2,
   -1,
    0,
    1,
    2,
    3,
    4,
    5,
    6,
};

float BlurWeights[13] =
{
   0.002216,
   0.008764,
   0.026995,
   0.064759,
   0.120985,
   0.176033,
   0.199471,
   0.176033,
   0.120985,
   0.064759,
   0.026995,
   0.008764,
   0.002216,
};

float4 GaussianPixelShader(float2 TextureCoordinate : TEXCOORD0) : COLOR
{
    // Pixel width
    float pixelWidth = 1/TextureWidth;

    float4 color = {0, 0, 0, 1};

    float2 blur;
    blur.y = TextureCoordinate.y;

    for (int i = 0; i < 13; i++)
    {
        blur.x = TextureCoordinate.x + Pixels[i] * pixelWidth;
        color += tex2D(TextureSampler, blur.xy) * BlurWeights[i];
    }

    return color;
}

```

**What I have further found out by testing**

The code in the GaussianPixelShader does get executed (if I set it to just return a black color it gives an entire solid black screen) but just doesn't seem to work/do the blurring.

**Images**

This is how currently my model looks (I cant see any blurring but maybe the blurring is just too light): image.

**Full Code**

Link to the shader code and the link to the xna/c# code.

# Answer
> 3 votes
It looks like `TextureWidth` is an integer. The line:

```
    float pixelWidth = 1/TextureWidth;

```

will be calculated using integer arithmetic, and so long as TextureWidth \> 1, the result will be zero. This means the line:

```
    blur.x = TextureCoordinate.x + Pixels[i] * pixelWidth;

```

will be equivalent to:

```
    blur.x = TextureCoordinate.x;

```

and you will end up with a weighted sum of the same pixel.

You can fix this by making sure that pixelWidth is calculated using floating point arithmetic:

```
    float pixelWidth = 1.0/(float)TextureWidth;

```

---
Tags: xna, hlsl, post-processing
---


# Question
Title: What are the best resources on multi-threaded game or game engine design and development?
What are the best resources on multi-threaded game or game engine design and development? As this is obviously where computers are headed, I intend to study this topic and I'd like to know what resources and examples are out there.

# Answer
> 20 votes
Some intel resources.

http://software.intel.com/en-us/articles/designing-the-framework-of-a-parallel-game-engine/

http://software.intel.com/en-us/videos/dont-dread-threads-part-1/

# Answer
> 25 votes
The Don't Dread Threads presentation by Intel, is quite good.

Summary of what was covered in first half of the presentation:

# Avoid Functional Decomposition

First of all, they discourage using Functional Decomposition. Functional decomposition is just "put the AI on one thread, put the audio on another thread, put the graphics on the 3rd thread"

So that kind of looks like this

So that's \__bad\__™. Instead you want to use *Data Decomposition*.

# Use Data Decomposition

Data decomposition means you cut up *every thing* in your game into small achievable tasks. You spawn x threads, say 4, and then for each of those 4 threads they continually grab a task from the task pile and work on it until they're done.

It's kind of like a bunch of people eating a pizza. Everyone takes a slice until the pizza's done.

Of course, now I'm hungry.

# Answer
> 11 votes
A brief overview of Multi-threaded engine approaches. Gamasutra to the rescue.

# Answer
> 5 votes
Here's a blog post that provides a practical example in task management. It assumes some knowledge about parallel engine design on your part but you might still find it useful as 'advanced reading'.

# Answer
> 1 votes
I think you should look into a task- or job-basedd approach.

Game Engine Gems has 2 or 3 articles on the subject.

There have been a couple of presentations on the subject at different conference etc.

For example "Parallel Futures of a Game Engine" by Johan Andersson

Also take a look at the GDC Vault there are a number of presentations and full videos on the subject in the free section. http://www.gdcvault.com/

ps. Couldn't post any more direct links due to being a new user. ds.

# Answer
> 0 votes
The book Game Engine Architecture does also have some informations on how to design a game engine with multi threading support.

---
Tags: software-engineering, assets, multithreading
---


# Question
Title: is a good practice to orgnize MVC classes in diferent packages?
Im,working on a project where the classes are organized by subject like gameplay, menus, utilities etc... Basically this 3 packages.

is a good practice to organize classes in controller, view and module packages ?

games are typically visual applications. This question is regarding the viability of a particular organization and pattern in a game application, which are mostly visually oriented.

# Answer
> 0 votes
It depends on what programming language are you using. In Java for example I would strongly recommend separating coherent classes by their use.

At the very least you should put Game Logic and Display to different packages.

# Answer
> 0 votes
Yes, because you may then define your game resources as subclasses of Model, View, and Controller. Alternatively, you could feature Model, View, or Controller instance properties within your game classes.

For example: You could have an overall GameActor class, with separate instance properties of Model (for the data), View (for the visual representation of that data), and Controller (for game mechanics, etc.)...

Then, all actors within your game could be sent to Model, View, or Controller processing methods, just by passing-in the appropriate MVC actor property to that method.

---
Tags: mvc
---


title: GPGPU physics & game logic

text:
# Question
Title: GPGPU physics & game logic
I'm wondering about gpu accelarated physics after reading about Erwin Coumans presentation on GPU accelerated physics: http://www.gdcvault.com/play/1018185/GPU-Rigid-Body-Rigid-Body (demo video here: http://www.youtube.com/watch?v=ZkF4yMmP0R8)

While it certainly looks like a massive performance boost, I don't have any expirience with gpgpu programming, so I'm wondering how practical this is for games. You'd have to manage communication between the different parts of the game engine. I know there are facilities to have opencl & opengl share memory, that covers the rendering part.. but what about the other parts of a typical game engine? Let's say we have a fixed timestep physics simulation (lets say 60hz) and corresponding game logic (which also runs at 60hz) that needs to act on certain events triggered by the physics engine. Game logic is not necesarily suited for execution on the gpu, it may for example be very branching intensive. This would mean a readback from the gpu to the cpu, wouldn't this create too much latency to have our game logic proceed at 60hz?

# Answer
> You'd have to manage communication between the different parts of the game engine.

You have to do this anyway though.

> I know there are facilities to have opencl & opengl share memory, that covers the rendering part.. but what about the other parts of a typical game engine?

GPGPU and the Rendering Pipeline are independent. The Rendering Pipeline is a special-purpose operation. You can run GPGPU instructions by themselves without submitting anything to be rendered.

> Let's say we have a fixed timestep physics simulation (lets say 60hz) and corresponding game logic (which also runs at 60hz)

Is this a realistic scenario at this point? Will you actually have physics and game logic executing the entirety of their updates that often?

A renderer being able to draw at 60 frames per second is one thing. But processing physics, game logic (including AI?) at that rate is something else entirely.

> Game logic is not necesarily suited for execution on the gpu, it may for example be very branching intensive.

Pre-emptively remove branches where and when it makes sense to do so. Use threads with mark and sweep and rework your data so it doesn't need to branch.

> This would mean a readback from the gpu to the cpu, wouldn't this create too much latency to have our game logic proceed at 60hz?

So this is the major question. It's also somewhat loaded.

GPU can execute a lot more code in parallel than your CPU can, which means that if you have a lot of data to process - enough to dwarf the latency of transferring data between CPU and GPU - then you might benefit from this.

The presentation you linked deals with A LOT of data, performing an SIMD operation. They are bound to see a performance increase. As teodron also commented, they use tasks that naturally lend themselves to parallel execution and SIMD operations.
> 4 votes

---
Tags: opengl, physics, gpu, gpgpu, cuda
---


# Question
Title: How do you construct a node map for pathfinding in a non-tiled 2D environment?
A\* and Dijkstra's pathfinding algorithms work by navigating a node map. In a tile-based 2D environment, these nodes could easily be inferred to be the literal `x,y` positions of the map.

For example, the agent is at `(0,0)`, an obstacle is at `(0,1)`, and the agent wants to go to `(0,2)`.

However, in a 2D environment where locations are represented using floating point variables `float x, float y`, agents and obstacles can exist between the traditional style nodes `(0,0)` and `(0,1)`.

How do you create a node map from such an environment?

# Answer
The two most common answers are to use waypoints or navigations meshes (navmeshes).

In the former case, you pick various points on your map, precompute which are "neighbors" (have a clear path between them), and explicitly link them together.

In the latter case, you generate a triangle mesh covering all walkable regions. Your nodes can be triangles with graph-edges being the shared triangle-edges. Or nodes could be midpoints of triangle-edges with the graph-edges being computed from the triangles.
> 3 votes

---
Tags: 2d, algorithm, ai, path-finding
---


# Question
Title: VBO GL_STREAM_DRAW double buffer or new buffer?
There is some conflicting information on the STREAM usage specifier.

Apple's documentation states you should use double buffering and update the stream buffer that is not being read by the GPU.

OpenGL's reference documentation states you should only modify the contents of the buffer once. Which implies you should create a new buffer to write data instead of reusing the existing buffer.

Is there a reason to use the more complicated double buffering technique?

# Answer
This is what I've experienced:

GL\_STATIC\_DRAW - for static content, which never changing (examples: terrain, buildings)

GL\_DYNAMIC\_DRAW - for spontaneously changing data (examples: skybox, units, characters, anything that relies on actual input)

GL\_STREAM\_DRAW - for constantly updating data (examples: some 2D text like FPS counter, particles)

You can have a tiny FPS drop if you choose the wrong usage.
> -2 votes

---
Tags: opengl, vbo
---


# Question
Title: HLSL Textured Light: outputs only a specific part of the texture (new problem)
**Problem 1**

I am trying to create a spotlight that instead of giving the circle within the spotlight a simple color, applies a texture to it. However, where the texture is supposed to be is only a black circle: image.

Solution: the position I used for my texture wasnt correct.

old and faulty code:

```
float4 TexturedSpotlightPixelShader(VertexShaderOutput input, float2 TextureCoordinate : TEXCOORD0) : COLOR0
{
    //I left out all the other code in the shader, full code is at the bottom of the thread
    color = tex2D(SpotlightTextureSampler, TextureCoordinate);
}

```

better code that solved my 'black problem (but created a new one):

```
float4 TexturedSpotlightPixelShader(VertexShaderOutput input) : COLOR0
{
    //I left out all the other code in the shader, full code is at the bottom of the thread
    color = tex2D(SpotlightTextureSampler, input.Position);
}

```

where at that point input.Position was set to the worldPosition in the vertexshader (which turned out was the reason for problem 2)

**Problem 2**

My spotlight now applies the texture, however the texture is repeated multiple times in miniature, as such: image

Solution: I added these lines in the vertex shader:

```
input.Position3D.w = 1.0f;
output.Position = mul(viewPosition, Projection);

```

and by adding/changing these lines in the pixelshader:

```
float2 TextureCoordinates;
TextureCoordinates.x =  input.Position.x / input.Position.w / 2.0f + 0.5f;
TextureCoordinates.y = -input.Position.y / input.Position.w / 2.0f + 0.5f;
color += tex2D(SpotlightTextureSampler, TextureCoordinates);

```

however, there was still a third problem.

**Problem 3**

The third and probably (I hope :P) the last problem, my spotlight now only shows a part of my texture and manually resizing the image (in the image file, not in my code) doesnt change what part of the texture is shown, as such: image

Solution: In my vertexshader I used the 2D positions (viewmatrix multiplied with the projection matrix) where I should have used a viewmatrix not based from my camera but from my spotlights point of view (and a projection matrix also for my spotlight's point of view)

My new code:

```
float4x4 View2, Projection2;

VertexShaderOutput SimpleVertexShader(VertexShaderInput input)
{
//left out a lot of code here
output.Position = mul(mul(worldPosition, View2), Projection2);
}

```

**Full Code**

Link to the shader code and the link to the xna/c# code.

# Answer
You're using the world position as the texture coordinates. Texture coordinates range from 0 to 1 and then the texture repeats itself, so the result of this is that you'll get a copy of the texture squeezed into every 1 unit along the XY axes in world space. If your world units are centimeters then you'll get a copy of the texture in each square centimeter, for instance.

For a spotlight with a texture, you probably want projective texturing. The code in that tutorial is for D3D11, so it won't directly work in XNA, but you should be able to adapt it. The short version is that you have to transform the world position to a coordinate system aligned with the light and divide by z. This will make the texture scale larger as it gets farther from the light, like the image from a projector.
> 1 votes

---
Tags: xna, textures, hlsl
---


# Question
Title: OpenGL GL_LINE_STRIP produces arcs with visible line edges
Another member mentioned an issue while drawing arcs with `GL_LINE_STRIP`. He has `GL_LINE_SMOOTH` enabled.

The question is, how could he avoid the tiny gaps between vertices without increasing their number?

***Edit:*** The original discussion was on SO. Click here for more info.

# Answer
A quick google search shows this to be a common problem with line strips. I strongly suspect the correct answer is: don't use line strips. Use triangles instead, and build your own geometry so that it doesn't have gaps.

Moreover, according to this answer on StackOverflow, it sounds like line rendering is not rigidly specified by the OpenGL spec the way triangle rendering is, so results might vary between GPU vendors, chipsets, and driver versions.
> 4 votes

# Answer
This isn't a problem with line strips. OpenGL is doing exactly what you have asked it to do: draw a bunch of rectangles oriented to match the 'lines' you've provided, each with a particular width which you've also provided.

The problem is that you're imagining that OpenGL is going to magically join up the corners of those rectangles into a single swooping shape. That simply isn't going to happen -- OpenGL has no way to determine where those merged vertices ought to be placed, whether you want them at an averaged position or maintaining a particular orientation or distance apart or what. It just draws a rectangle for each line segment, with those rectangles oriented along the direction of the line. A "line strip" isn't a compound line from OpenGL's point of view; it's just a list of discrete lines which is expressed using less data. Because that's all it *can* be, because OpenGL can't guess what you want it to do.

If you want to draw a wide smoothly curving shape like this, you need to build the geometry for it yourself, and render it using triangles.
> 3 votes

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


# Question
Title: How should I architect my GUI for my HTML5 canvas cell phone game?
I'm making a game on the HTML5 canvas and my intent is to run or port this code to work on cell phones. Right now it only runs on my desktop computer. I'm trying to write my GUI code but I'm not confident in any of the architectures I come up with so I'm getting stuck in a refactoring loop.

So far I've got a `Dialog` and a `Clickable` (basically a button) type. The Dialog is initialized with a hardcoded list of Clickables . Whenever the user clicks on a dialog, a function iterates the current Dialog's Clickables to see if any of them were clicked and if so, runs that Clickable's action. This action can be basically anything.

This all worked for my needs until I needed to make the number of Clickables on a Dialog dynamic depending on the game state. For example, the inventory dialog. This is a grid and each cell *may* contain an item. Is every cell a Clickable, or only cells with an item? When are these dynamic Clickables created? Who creates them and where?

Also consider the level chooser dialog. It should contain a list of levels you can play. The more levels you beat the more Clickables on this screen. This screen will probably be scrollable. Keeping track of where the user clicked when the window may be scrolled is blowing my mind.

I feel like any decision I make will paint me into a corner later. I've never done this before so I'm looking for some advice from seasoned veterans. Thanks

BTW, I've looked around the site for other similar questions. They seem to be asking, "How do I do this in C++ w/ a library". Here I'm asking how to design it by hand.

# Answer
> 1 votes
I found your question hard to answer as it seems quite broad. "The GUI" can more or less be considered your whole game. Answering that question accurately would be designing the game, which I believe is out of scope for this forum.

There are numerous frameworks (Sencha, qooxdoo, Kendo, ...) that can make things easier, however if you want to learn and explore I'm all for it.

I've tried to answer the 3 questions I found in your post and provide some examples. I hope you find it useful.

Maybe you should divide this question into one or more concrete questions. Some code examples usually helps too.

"Clickable" sounds like an interface. The name only describes a single aspect of the required object (I assume you want to represent a square of custom graphics which might also be clickable).

I think I would represent the buttons as simply a "component".

```
function Component(cx, cy, cw, ch, caction) {
    this.pos  = {
        x: cx || 0,
        y: cy || 0
    };
    this.size  = {
        w: cw || 0,
        h: ch || 0
    };
    this.action = caction || false;

    this.activate = function () {
        if (this.action) this.action();
    };
}

```

You'll have to add some properties representing the actual graphics (this depends on how you manage your graphics).

Dialog can call action on components that intersect with a mouseclick (or touch).

```
function intersects(x, y, pos, size) { ... }
function Dialog(components) {
    this.components = components || [];

    //...

    this.onclick = function (x, y) {
        for (int i = 0; i < this.components.length; ++i) {
            if (    intersects(x, y,
                    this.components[i].pos,
                    this.components[i].size)) {
                this.components[i].activate();
                break; // assuming non-overlapping components
            }
        }
    };
}

```

For any non-clickable component, just leave action unset and it will default to false.

You could implement a statemachine for gamestate (menu, levels, credits, etc). Statemachine example I've authored.

Implement an inventory which dynamically creates a dialog with components for each item, or components fill the screen, but only components with items have actions.

The inventory would have to be managed by your game state for that level.

Inventory might look something like this:

```
function Item(component) {
    this.component = component || false;

    if (this.component) {
        // mimic component behaviour
        this.pos      = this.component.pos;
        this.size     = this.component.size;
        this.activate = this.component.activate;

        // im not sure if this.pos and this.size refer
        // to this.component.* or if the assignment creates
        // a copy (however i think it's reference)

        // anyways, test to find out or make sure not to
        // change component after it's added to item.
    }
}

function Inventory(items) {
    this.items = items || [];

    //...
}

```

This would allow Inventory to act as a dialog, and items as components while it's possible to add more data to an item without interfering with regular components.

You can use array.push and .splice to add/remove items from inventory (make sure to implement management for component/item coordinates and sizes).

---
Tags: game-design, gui
---


title: Diffuse Reflection confusion

text:
# Question
Title: Diffuse Reflection confusion
From what I've read, with a simple directional light, the color of a point, if you only take diffuse reflection into account (intensity = 1), should be

```
color = color_of_point * color_of_light * dot(normal, -light_direction);

```

However, this is confusing for me. For example, if the light direction is parallel to the normal, and if the color of the point is pure red (1,0,0) and the color of the light is pure blue (0,0,1) I'd expect the point to have a color of violet - yet the result will be black.

Similarly, if I have a completely white point, or a completely black point, I wouldn't intuitively assume that the result is completely white (regardless of light color) or completely black either.

I guess I'm fundamentally misunderstanding something here. Can someone explain?

# Answer
Your lighting equation is physically correct. However, in real life, one almost never sees highly pure colors. (An exception is when lasers are involved.) That's probably why your intuition is that red * blue = violet - a more realistic red might be something like (1, 0.1, 0.1), and a blue (0.1, 0.1, 1). Multiply those and you get (0.1, 0.01, 0.1), which is indeed a (dark) violet.

Similarly, nothing is perfectly black. Even black plastic, paint or cloth has at least a little specular reflection. The specular albedo at normal incidence doesn't get below about 2% for most materials, and at grazing incidence it rises due to the Fresnel effect. (Super black is an exception - a special material that reflects only 0.4% at normal incidence.)

For a white material, the reflected light will be the light color, not completely white. However, you've got to watch out here as your brain plays tricks on you: it adapts to the overall color of the light around you, so that white objects tend to look perceptually white even when illuminated by colored light. This is why digital cameras have a white balance setting - photographs would look completely wrong without it. (Of course, this only works up to a point - illuminate a room with a red laser and things will look red, not white.) Games don't generally simulate this visual adaptation process, though; instead they just have light colors that are less saturated than in reality.

(By the way, a nitpick: your lighting equation should have `saturate()` around the dot product, to avoid generating negative values on the dark side of an object.)
> 13 votes

# Answer
How do objects show color?

Well, an 100% red object looks red because it absorbs all other wavelengths of light (orange,yellow,green..you know, a rainbow) and reflects only red.

So what if you shone pure blue light on a pure red surface? Well it would absorb the blue light and reflect.. nothing. Hence black.

I'm sorry for the terrible picture
> 15 votes

---
Tags: glsl, lighting
---


# Question
Title: Write colors with alphablending but don't write into the alpha channel
I am using XNA 4.0, hence DX9 and HLSL. I have a RenderTarget2D "MAIN" that I want to add semi-transparent objects "TRANS" to. I want them to blend with MAIN using the TRANS's alpha and inverseAlpha BUT I want to preserve information kept in the MAIN's alpha channel.

If I simply use BlendState.AlphaBlend, MAIN's alpha channel becomes 1 everywhere where TRANS is written. I know there is a property in the BlendState class that prevents writing to color channels Is there an option that prevents writing to alpha?

Thanks.

# Answer
`BlendState.ColorWriteChannels` is a bitfield with a bit for each of the four channels. You can make it write to RGB only by setting

```
blendState.ColorWriteChannels =
    ColorWriteChannels.Red | ColorWriteChannels.Green | ColorWriteChannels.Blue;

```
> 2 votes

---
Tags: xna, hlsl, alpha-blending
---