# Question
Title: Set Sampler states: Linear, Bilinear, Trilinear Filtering/Interpolation
How do you set each of these sampler states in the hlsl

1. Linear filtering
2. Bilinear filtering
3. Trilinear filtering

# Answer
Filter mode is not set in HLSL. It is part of the `ID3D11SamplerState` object, specified as part of the D3D11\_SAMPLER\_DESC struct during creation.

For example:

```
D3D11_SAMPLER_DESC desc;
desc.Filter = D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT; // bilinear
desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; // trilinear
desc.Filter = D3D11_FILTER_ANISOTROPIC; // anisotropic
// no such thing as "linear" for 2D textures
// ...
device->CreateSamplerState(&desc, &sampler);
context->PSSetSamplers(0, 1, &sampler);

```

And in HLSL:

```
Texture2D foo : register(t0);
SamplerState bar : register(s0);
// ...
foo.Sample(bar, coord);

```
> 2 votes

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


title: Basic DirectX app creates whistle noise

text:
# Question
Title: Basic DirectX app creates whistle noise
I'm in the process of learning DirectX and in the book examples they have a very basic application which sets up DirectX and displays a blank screen. When I run this app however my computer starts making a whistling noise and I'm really curious as to why it does this.

If I maximize the screen the noise stops and this is the only time the noise happens. When I play normal games, run apps in XNA or do anything that doesn't involve directly using DirectX it doesn't happen.

The FPS is going up to 3000-4000 when the app is running and drops down to 1000 when the window is made to stretch the screen (and the noise stops). I'm taking a guess and saying it's something to do with that?

Anyway, does anyone have any ideas on what is creating this noise?

Thanks

# Answer
> 2 votes
In most cases this is due to excessive framerates causing audible-frequency power fluctuations on the GPU. Certain elements like capacitors (to steady the power line voltage) will actually physically vibrate if they're doing enough work. To avoid this, set SyncInterval to 1 in the argument to `IDXGISwapChain::Present`. This will lock your framerate to the maximum display framerate, and sleep the thread if it finishes rendering early.

---
Tags: directx
---


# Question
Title: LUA - Keeping track of game state for a digital card trading game
I am building a card game. Let's say it's similar to Magic the Gathering, Hearthstone, etc.

The problem I am trying to figure out is how to architect "auras" and how much damage each card takes.

Right now I have a deck and I store card data as follows. I've made up names for the types of cards that will exist.

```
M.card = {}
-- Minion cards have health and damage
M.card[1].name = "Minion"
M.card[1].hp = 1
M.deck[1].dmg = 1

-- Super Minions have more health and damage
M.card[2].name = "Super Minion"
M.card[2].hp = 4
M.card[2].dmg = 4

-- Spell cards have no health and damage. Instead they affect the health and damage of other cards.
M.card[3].name = "Heal"
M.card[3].details = "This card heals any character for +2 health"
M.card[3].healthboost = 2

M.card[4].name = "Damage Boost"
M.card[4].details = "This card gives + 1 damage to any other card for 1 turn"
M.card[4].dmgboost = 1

-- Super damage boost gives more damage boost to other cards
M.card[5].name = "Super Damage Boost"
M.card[5].details = "This card gives +3 damage to any other card permanently"
M.card[5].dmgboost = 3

```

So when one card attacks another card, I need to keep track of the damage taken by both cards. I don't want to change the base stats of each card so I need to keep track of adjustments.

I could do something like this

```
-- Super Minion takes 3 damage
M.card[2].newHp = 1
-- or
M.card[2].adjHp = -3
-- Not sure which is better.

```

During the battle I need to keep track of which auras are played. So for example if the Damage boost card is played. I need to give another card +1 damage for just one turn.

Let's say that I am keep track of each turn number starting from 1.

Should I do something like this M.aura\[1\] = 4 -- ( aura 1 is card # 4) M.aura\[1\].target = 2 -- (this aura is applied to card 2) M.aura\[1\].expires = 5 -- (this aura expires on turn 5)

```
M.aura[2] = 3    ( second active aura is heal, card #3 )
M.aura[2].target = 2
M.aura[2].expires = 0   -- this is a one time aura.  So I need to apply it to card #2 and then immediately expire it so it never activates again.

```

Then on every new turn I loop through all the auras and make sure they are still active before a fight begins?

Just wondering architecturally what is the best way to keep track of Damage that characters have taken and spells that are active that are giving characters special abilities.

# Answer
> 0 votes
Looks like you want Lua metatables! (http://www.lua.org/manual/5.2/manual.html#2.4)

Metatables are a way of adding extended functionality to Lua tables by changing the effect of different operations on the table. (addition, subtraction, indexing, inserting into a table, etc.) If you set the \__index metafunction for a metatable to the original card's table, you can - in a sense - inherit properties/functions of that card.

For example,

```
-- Hold a list of master cards, that wont change
Cards = {}
Cards["Minion"] = { name = "Minion", hp= 1, dmg= 1 }

-- Insert a card to the player's hand: (In Lua, arrays start at 1)
-- Realistically, you'll want a function to do this.
M = { cards = { [1] = {} }}
setmetatable(M.cards[1], { __index = Cards["Minion"] });

-- Then, when you alter the value of "hp", you aren't changing the original health.
M.cards[1].hp = M.cards[1].hp - 1;
print(M.cards[1].hp) -- Prints '0'
print(Cards["Minion"].hp) -- Prints '1'

```

Generally, this is the method you want to follow for giving state to an object in Lua. Create a table, and apply a metatable that represents the functionality of the "class" or "object" it represents.

Keep in mind this is the approach if you want to stay completely in Lua.

EDIT (For misinformation):

I am sorry, when I originally posted my clarification, it was incorrect. You can, in fact, edit the value you inherit off \__index. \__index will copy the value into the table, so numeric values can change without any issues. (Please see changes above!)

# Answer
> 1 votes
The easiest approach is to have separate "card instance" objects from "card template" objects. A deck then is a collection of card instances, and each instance references its template. Something like:

```
 class CardTemplate {
   uuid id;
   string name;
   int base_hp;
 };

 class CardInstance {
   CardTemplate template;
   int current_hp;
 };

```

This has several advantages. The most relevant to your question is that you can have the card's HP change fully independent of the template, both above and below (useful for damage, buffs, debuffs, etc.).

You might find that you need to also have a third struct to make things easier as these types of games often have a large amount of data that can change, e.g.

```
struct CardInfo {
  int base_hp;
  int current_hp;
};

```

Because your mechanics might want to differentiate from damage and buffs/debuffs in its UI, e.g. a buff to health might increment both `base_hp` and `current_hp`. You can check if a card has its health buffed by comparing its `base_hp` against that of its template, and can check if it's damaged easily by comparing `current_hp` against its own `base_hp`.

It will further come in handy to have stacks of effects with their modifiers (which field they modify and by how much), source cards, durations, all kinds of stuff.

---
Tags: game-loop, lua, corona-sdk
---


# Question
Title: Creating a 2D texture array for depth view
Following my question here, I decided to create an 2D texture array for all of my depth screen texture so that I can use them for shadows for all my lights.

I'm having an issue setting it up, I'm getting an `E_INVALIDARG` when I try to create it.

This code is what I use to create the 2D array Texture

```
D3D11_TEXTURE2D_DESC sTexDesc;
sTexDesc.Width = this->Width;  // 1024
sTexDesc.Height = this->Height;// 1024
sTexDesc.MipLevels = 0;
sTexDesc.ArraySize = arraySize; // The value is 25 here
sTexDesc.Format = DXGI_FORMAT_R24G8_TYPELESS;
sTexDesc.SampleDesc.Count = 1;
sTexDesc.SampleDesc.Quality = 0;
sTexDesc.Usage = D3D11_USAGE_DEFAULT;
sTexDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
sTexDesc.CPUAccessFlags = 0;
sTexDesc.MiscFlags = 0;

HRESULT hr = pd3dDevice->CreateTexture2D(&sTexDesc, NULL, &(this->shadowTexture));
if(FAILED(hr))
    throw std::exception("Failed at creating texture array for shadows");

```

This is the code that I use to create the depth view

```
D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
ZeroMemory(&dsvDesc, sizeof(dsvDesc));
dsvDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DARRAY;
dsvDesc.Texture2DArray.ArraySize = arraySize; // The value is 25 here
dsvDesc.Texture2DArray.FirstArraySlice = index;
HRESULT hr = pd3dDevice->CreateDepthStencilView(shadowTexture, &dsvDesc, &pDepthMapDSV);
if(FAILED(hr)){ throw std::exception("Error creating 2d texture for shadow"); }

```

`CreateDepthStencilView` will return `OK` for the first texture but it crashes for the second.

What have I done wrong here?

# Answer
I found what the issue was.

```
dsvDesc.Texture2DArray.ArraySize = arraySize; // The value is 25 here

```

I thought that it wanted to know the full size of the array, but as I read the msdn article, it is actually the number of texture to use and so that value should be set to 1.
> 1 votes

---
Tags: c++, directx, directx11, shadows, depth-buffer
---


title: XNA flip SpriteBatch on click

text:
# Question
Title: XNA flip SpriteBatch on click
Is there any way to make a `SpriteBatch` flip when its clicked, something like Android Animation?

I know that `spriteBatch.Draw()` have `SpriteEffects`, but it literally flip it and I want to flip it like an animation.

# Answer
In XNA, you won't find any direct analog to the Android method you linked. You are also correct that `SpriteEffects` is not the answer to your problem (it's a very short enumeration).

If you want to display an animation, you will have to manually display different sprites sequentially, which is commonly accomplished with a sprite sheet that contains the frames. You must implement some form of a counter that updates each frame, and use that counter to select the correct frame of your animation. For example, if the animation frames are arranged into a grid, you could progress through that grid's rows and columns using a pair of simple loops (again, based on your counter).
> 1 votes

---
Tags: xna, c#, windows-phone-7
---


title: Unity3D free in game purchase solution

text:
# Question
Title: Unity3D free in game purchase solution
Am making an android game with unity and i want to add an in-game purchase feature, i looked around and all the suggestion lead to non-free plugins (mainly prime31 plugin) but in the current moment i cannot afford to invest in some of these plugins, does anyone of you have a free solution for this "problem" ?

thank you

# Answer
You could try these plugins, they are both free.

http://project.soom.la/

https://github.com/onepf/OpenIAB/tree/master/unity\_plugin
> 3 votes

---
Tags: unity, microtransactions
---


# Question
Title: Error compiling irrlicht android using ndk in Mac
I'm new to irrlicht and I have started with irrlicht android port. I have made the following changes to android.mk file:

```
LOCAL_CFLAGS := -O3 -DANDROID_NDK -DDISABLE_IMPORTGL -I./../include/ -I./include/ -I/documents/karthik/android/android-ndk-r9/platforms/android-18/arch-arm/usr/include

LOCAL_LDLIBS := -L/documents/karthik/android/android-ndk-r9/platforms/android-14/arch-arm/usr/lib/libGLESv1_CM.so -ldl -llog -L/documents/karthik/android/android-ndk-r9/platforms/android-14/arch-arm/usr/lib/libGLESv1_CM.so

```

I have tried compiling irrlicht android using ndk-build in terminal.It showed the following errors at first:

```
In static member function 'static void irr::os::Printer::log(const c8*, irr::ELOG_LEVEL)':
error: format not a string literal and no format arguments [-Werror=format-security]
In static member function 'static void irr::os::Printer::log(wchar_t const*, irr::ELOG_LEVEL)':
 error: format not a string literal and no format arguments [-Werror=format-security]
In static member function 'static void irr::os::Printer::log(const c8*, const c8*, irr::ELOG_LEVEL)':
error: format not a string literal and no format arguments [-Werror=format-security]
In static member function 'static void irr::os::Printer::log(const c8*, const path&, irr::ELOG_LEVEL)':
error: format not a string literal and no format arguments [-Werror=format-security]
make: *** [obj/local/armeabi/objs/irrlicht/os.o] Error 1

```

and then I googled that and made changes in os.cpp file as follows:

Changed the code,

```
__android_log_print(ANDROID_LOG_INFO, "log", message);

```

to

```
__android_log_print(ANDROID_LOG_INFO, "log","%s", message);

```

This change solved that issue, and then I got another error:

```
In file included from jni/importgl.cpp:55:0:
jni/importgl.h:37:22: fatal error: GLES/egl.h: No such file or directory

```

Again I changed `GLES/egl.h` to `EGL/egl.h` and solved that issue, got:

```
fatal error: irrlicht.h: No such file or directory

```

I even solved this , atlast I'm here with this error:

```
error: 'EglDisplay' was not declared in this scope
error: 'EglSurface' was not declared in this scope
error: 'EglWindow' was not declared in this scope
error: 'EglContext' was not declared in this scope

```

# Answer
> 0 votes
Found the solution for the issue, There is no need to edit `Android.mk` file while compiling `irrlichtandroid`. In `project/default.propeties` , I have changed:

```
target=android-4

```

to

```
target=android-18

```

And when:

```
In file included from jni/importgl.cpp:55:0:
jni/importgl.h:37:22: fatal error: GLES/egl.h: No such file or directory

```

this error occurred I did a mistake by changing `GLES/egl.h` to `EGL/egl.h` but that is not the solution for the issue. In `include/IrrCompileConfig.h` I have commented out:

```
//#define _IRR_COMPILE_WITH_OGLES1_

```

since I need only OpenGL ES 2. This solved the issue , `irrlichtandroid` compiled successfully using `ndk-build` , `libirrlicht.so` file generated in my project `libs` directory.

---
Tags: android, macos, irrlicht, ndk
---


# Question
Title: How to detect collision between a camera and a mesh?
I am wondering how you would be able to extract mesh properties (i.e. faces, vertices, and vertex normals) and use them to create a collidable object, one that a camera can't go through ?

I am using @TheCodingUniverse's OBJLoader. The files are in the **episode\_24** and **utility** folders.

# Answer
Just before going into how to do it in details, let me summarize what you need to do:

1. Calculate Bounding Volume for your mesh (pre-process).
2. Calculate distance between your camera and the bounding volume.
3. Check if the camera position is less than a specific distance from the object.
4. Trigger your collision response.

### Calculate a bounding volume for your mesh

This is useful because a bounding volume is usually much simpler than your actual mesh, which makes your intersection test much simpler and much faster. As a simple example, in order to calculate an axis aligned bounding box:

```
  //Axis aligned bounding box, cannot be rotated in a direct way.
  struct AABB
  {
    Vec3 min;
    Vec3 max;
  };

  // Loop through vertices and get
    AABB CalculateAxisAlignedBox()
    {
    Vec3 max( MIN_FLOAT, MIN_FLOAT, MIN_FLOAT);
    Vec3 min(MAX_FLOAT, MAX_FLOAT, MAX_FLOAT);

    for (int i=0; i< m_vertices.size(); ++i )
    {
        if( m_vertices[i].x > max.x)
        {
            max.x= m_vertices[i].x;
        }
        //Do this for Y,Z

        if( m_vertices[i].x < min.x)
        {
            min.x= m_vertices[i].x;
        }
        //Do this for Y,Z
    }

    return AABB( min, max );
    }

```

### What about the camera?

Unlike, the mesh, the camera can be considered as a single vertex. This gives us two simple options when dealing with the camera:

* Consider the camera a single vertex.
* Consider the camera a single vertex with a radius. In other words give your camera a sphere.

I will go with the first option because it's simpler.

### Calculating Intersection

This is as simple as calculating the distance between the camera position and the bounding volume, if the distance is less than some distance stop the camera from entering the volume (do collision response).

```
// Calculates the square distance between point and an AABB
float SquaredDistPointAABB(Point p, AABB b)
{
float sqDist = 0.0f;

for (int i = 0; i < 3; i++)
{
// For each axis, count any excess distance outside box extents
float v = p[i];
if (v < b.min[i]) sqDist += (b.min[i] - v) * (b.min[i] - v);
else
if (v > b.max[i]) sqDist += (v - b.max[i]) * (v - b.max[i]);
}
return sqDist;
}

```

Here we calculate the distance squared, to avoid square root calculation, because it's faster, but you can simply take the square root.

### What this solution doesn't do

This is a simple solution that can be enough for a simple game. But in the following scenarios it will clearly fell short.

**What if I want trignle level collision detection?**

In this solution we only checked for collision with the bounding volume, this good enough in case of the camera, but if you want more accurate collision detection, like for example Shooting a ray (bullet) in an FPS game, you need to check collision with the mesh triangles, there are other techniques can be used like using a proxy mesh which could be much simpler than the actual one, also check the next point.

**What if I have N objects?**

Well, for example if you have million objects it doesn't make sense to check for every intersection with those objects, what people do, is they do spatial partitioning to reduce checks to only those objects that are near (most likely will hit each other).

**What about if my camera/object is moving at 1 bazillion km/h ?**

Well, I doubt any collision engine can solve this (because of floating point accuracy). But (lame) jokes aside, moving objects (especially at high speeds) suffer from what is called Tunneling, in order to solve this you need to predict when the two objects will intersect, this will add the time variable to the static equation, so you need to calculate the possible time that two objects will collide. Which makes things a little bit more complicated.
> 1 votes

# Answer
Games use Collision Detection and Response to ensure no interpenetration of objects. Collision Detection is divided in broad phase and narrow phase. In the broad phase coarse representations of the objects are tested for collision, for performance reasons. These representations are called Bounding Volumes (BVs) and are easy to test. Examples are spheres, boxes, k-dops.

The narrow phase is more accurate and checks for collisions of the primitives (faces in your case) of the objects that collided in the broad phase. How this is done depends which primitives you are using and other factors, such as if you are doing continuous or discrete collision detection.

Collision Response is about what the system does to resolve the interpenetrations detected. There are several ways of doing this, each one with different levels of accuracy and performance. For example, you can project one of the objects so there is no more collisions. This approach is fast and solves the problem, but lacks physical accuracy since velocities and accelerations are not taken into consideration. Others approaches such penalty-force and impulse-based methods

As you can see it is a very broad area and is an entire branch of Computer Graphics. I would suggest the book Real-time Collision Detection for deep explanation of algorithms and their tradeoffs. It's the Bible of the area. Another good books are Geometry Tools for Computer Graphics and Real-time Rendering, but they are more focused on the intersection algorithms.
> -1 votes

---
Tags: collision-detection, mathematics, camera, collision-resolution, obj
---


# Question
Title: Collision function calls before colliding
My Box2D contact listener class is calling post solve and beginning the contact function before colliding? This is causing my object to bounce back before hitting the ground. What could be causing this?

# Answer
A common mistake is to assume the body's visual representation (ie sprite) matches the actual body shape.

Common causes for getting this wrong:

* Box2D rectangle shape uses center and half-width and half-height of the resulting rect shape. Same with circle which is initialized with radius, not diameter.
* Pixels/Point to meter conversion not or incorrectly applied.
* Shape not centered on the visual. For example not all rendering engines put the sprite's position at the center, some have position at a corner of the rectangle respectively in all engines one can change this anchor point. This will only offset the sprite, but not the body shape.

Tip: enable Box2D debug drawing to see if your shapes match expectations.
> 0 votes

---
Tags: box2d, cocos2d, cocos2d-x
---


title: How to optimize my A* algorithm

text:
# Question
Title: How to optimize my A* algorithm
I'm working on a roguelike, and I think my A\* algorithm is insufficient. My general algorithm for building the dungeon is:

1. Place rooms
2. Figure out which rooms should connect by a relative neighborhood graph
3. Use A\* to connect the rooms

The relative neighborhood algorithm I'm using is naive; it ends up having O(n^3) running time. The connections it generates are relatively short and straight forward; despite that, the A\* pathfinding ends up taking around 3 times as long as the room placement and relative neighborhood combined.

For example, here's how it clocks when I make a 300-room dungeon

```
events = [("Start time", time.clock())]
dungeon = NewDungeonGenerator.Dungeon(300)
level = Level.Level.FromGrid(dungeon.map)
events.append(("Created dungeon", time.clock()))
level.connect(dungeon.connectedRooms)
events.append(("Connected paths in dungeon", time.clock()))

```

Output:

```
Start time: 0.0
Created dungeon: 1.66705377095
Connected paths in dungeon: 5.48920304303

```

(that's time in seconds)

This is the A\* code I've written:

```
def FindPath(level, start, end):
    validX = range(level.width)
    validY = range(level.height)
    unvisited = [[True for i in validY] for i in validX]
    unvisited[start[0]][start[1]] = False
    paths = [{
        "cost": 0,
        "steps": [start]
    }]
    while True:
        paths.sort(key=lambda path: path["cost"] + computeOffset(path["steps"][-1], end))
        if len(paths) == 0:
            return False
        best = paths[0]
        paths = paths[1:]
        lastStep = best["steps"][-1]
        if lastStep == end:
            return best["steps"]
        for neighbor in ((0, -1), (1, 0), (0, 1), (-1, 0)):
            x = lastStep[0] + neighbor[0]
            y = lastStep[1] + neighbor[1]
            if x in validX and y in validY and unvisited[x][y]:
                unvisited[x][y] = False
                cell = level.getCell(x, y)
                if cell.immutable and not cell.passable:
                    # We don't want to dig through an immutable wall
                    continue
                cost = best["cost"] + cell.digCost
                steps = best["steps"][:]
                steps.append((x, y))
                paths.append({
                    "cost": cost,
                    "steps": steps
                })

def computeOffset(start, end):
    return abs((start[0] - end[0])) + abs((start[1] - end[1]))

```

I feel like there's got to be a way to optimize this... One potential cause of the slowdown is how I compute the cost of a cell. If a cell is passable, its cost is 1; otherwise, I check the cell and its neighbors against some 3x3 masks to determine what it is (wall, corner, 'earth'). You can see the code for the Cell class, and the masks, here. All the other code for this project is in available at that link as well.

EDIT: As was suggested below, I changed to a heapq for storing the paths and it's shaved about a second off the time. That's good!

```
def FindPath(level, start, end):
    validX = range(level.width)
    validY = range(level.height)
    unvisited = [[True for i in validY] for i in validX]
    unvisited[start[0]][start[1]] = False
    paths = []
    heapq.heappush(paths, (0, 0, [start]))
    while True:
        # paths.sort(key=lambda path: path["cost"] + computeOffset(path["steps"][-1], end))
        if len(paths) == 0:
            return False
        best = heapq.heappop(paths)
        lastStep = best[2][-1]
        if lastStep == end:
            return best[2]
        for neighbor in ((0, -1), (1, 0), (0, 1), (-1, 0)):
            x = lastStep[0] + neighbor[0]
            y = lastStep[1] + neighbor[1]
            if x in validX and y in validY and unvisited[x][y]:
                unvisited[x][y] = False
                cell = level.getCell(x, y)
                if cell.immutable and not cell.passable:
                    # We don't want to dig through an immutable wall
                    continue
                cost = best[1] + cell.digCost
                steps = best[2][:] # clone list
                steps.append((x, y))
                heapq.heappush(paths, (cost + computeOffset(steps[-1], end), cost, steps))

```

# Answer
the biggest problem I see is the `sort` call each step which is `O(n log n)`

I suggest using the heapq so it will be reduced to `O(log n)` per insert and pop saving you a factor of `n`

you will need to add the steps as lists with the sort key (the `path["cost"] + computeOffset(path["steps"][-1], end)` as first and then the tuple so natural ordering will be used

```
paths = []
heapq.heappush(paths, [0,{
    "cost": 0,
    "steps": [start]
}]
while True:
    if len(paths) == 0:
        return False
    best = heappop(paths)[1]

```

and to insert:

```
heapq.heappush(heap, [cost + computeOffset(steps[-1], end),
                      {
                          "cost": cost,
                          "steps": steps
                      }])

```

(I have no idea if I indented this correctly...)
> 5 votes

# Answer
In my Hex-Grid Utilities for Board Games library I obtained almost linear-in-path-length behaviour, over a grid of about 780 x 460 cells, by using eight landmarks (the four corners and four side-midpoints of the map) and the triangle inequality as outlined in Computing Point-to-Point Shortest Paths from External Memory. (Fair warning for Python developers - there be C# code; prepare for discomfort and disorientation.)

The parallel pre-computation (by Dijkstra's ,i.e. breadth-first) of distances from each landmark to every hex takes 2-3 seconds at start-up, while the computation of the longest and most complex path on the map runs so fast I can barely measure it; under 0.05 sec. Before adapting the code to use this technique, the calculation of complex diagonal paths took up to 1.6 seconds each.

I have used some additional optimizations, such as Bi-Directional A-star, but I estimate those as only providing a factor of 3-4 times in the speedup recorded.

All code in the library referenced above is available for use under The MIT License.

**Note:**
It is **not** necessary to store the pre-computed paths from each landmark at each cell - simply the minimum path-length to each landmark. This allows an extremely accurate heuristic to be computed, so that few false-steps are ever evaluated.
> 1 votes

---
Tags: path-finding, python, optimization
---


# Question
Title: Is OpenGL just for graphics when it come to game design?
I am a computer science major interested in learning how to create games. I know c++ very well and I am familiar with opengl. I want to know if opengl is just for graphics or can it be used for things like networking, collision detection, and sound for designing a game?

# Answer
> 1 votes
OpenGL is just for drawing graphics. It cannot help you with any of the things you mention, eg networking, collision detection, sound, etc.

Look for a game engine in C++ that uses OpenGL and has facilities for those sorts of things.

# Answer
> 1 votes
OpenGL is a Graphics API. It provides functions and methods for rending high performance graphic images; more information here.

However, things like collision can be implemented for use with OpenGL rendered objects using third party libraries or, of course, you can write you're own, which isn't recommended seems it would take too long; there are already many resources available; one that comes recommended is Havok or there is Bullet Physics for real-time simulation, (you might have more luck asking questions about collision using bullet here).

There are also cross-platform Audio APIs like PortAudio for example.

Ideally, you would just use a third party games/physics engine and include it's libraries much like you would include OpenGL libraries.

---
Tags: opengl
---


# Question
Title: Drawing sprites to a permanent Texture2d using Monogame / XNA
I'm working with Monogame to do a 2d sprite engine. I've gotten it work pretty well where I can move lots of sprites around the screen with the effects and positions that I want.

Last night I tried to add a feature and I can't quite get it to work right.
I'm trying to create permanent trails that the moving sprites can leave behind. So I have a mostly transparent PNG with some white lines on it called "streak". The idea is that I set up a new Texture2d surface (called streakoverlay) and I draw the streaks on to it.

I switch back to the back buffer and draw: The background, the streakoverlay, and finally the sprite on top of it. The streaks should build up over time. It almost works, but the trouble I have is that streakOverlay seems to clear itself every time. How I'd like it to behave would be the same behaviour as having the graphics display without this line "GraphicsDevice.Clear(Color.White);" - everything would just pile up in it.

Instead it resets back to the Purple transparent color that is the default for that texture. Any suggestions? Here's the core piece of the rendering engine:

```
GraphicsDeviceManager graphics;
RenderTarget2D streakOverlay;
SpriteBatch spriteBatch;

private Texture2D bkg;
private Texture2D prototype;
private Texture2D streak;

//Initialize
graphics = new GraphicsDeviceManager(this);
GraphicsDevice.Clear(Color.Transparent);
streakOverlay = new RenderTarget2D(GraphicsDevice, 200,200);

//Load Content
bkg = Content.Load<Texture2D>("bkg"); //Background image
prototype = Content.Load<Texture2D>("prototype"); //Prototype sprite that moves around
streak = Content.Load<Texture2D>("blueStreak"); //Trails being left by Prototype sprite

graphics.GraphicsDevice.SetRenderTarget(streakOverlay);
GraphicsDevice.Clear(Color.Transparent); //Attempt to make the streakoverlay is fully transparent.
graphics.GraphicsDevice.SetRenderTarget(null);

//Draw
Random r = new Random();
graphics.GraphicsDevice.SetRenderTarget(streakOverlay); //Switch to drawing to the streakoverlay

spriteBatch.Begin();
//Draw some streaks that should accumulate
spriteBatch.Draw(streak, new Vector2(r.Next(0, 200), r.Next(0, 200)), null, Color.White, 0f, new Vector2(25, 25), 1f, SpriteEffects.None, 1f);
spriteBatch.End();

//Switch back to drawing on the back buffer.
graphics.GraphicsDevice.SetRenderTarget(null);

spriteBatch.Begin();
spriteBatch.Draw(bkg, new Rectangle(0, 0, 2000, 2000), Color.White);    //Draw our background
spriteBatch.Draw(streakOverlay, new Vector2(0, 0), Color.White); //Put the overlay on top of it
spriteBatch.Draw(prototype, new Vector2(_spritePrototype.getX, _spritePrototype.getY), null, Color.White, DegreeToRadian(rotationSprite), new Vector2(25, 25), .5f, SpriteEffects.None, 0f); //Draw the sprite that's moving around.
spriteBatch.End();

base.Draw(gameTime);

```

# Answer
> 2 votes
In **XNA**, setting a render target (including the backbuffer) onto a device will, by default, clear that render target to the "uninitialized surface" purple colour.

To avoid this, set the `RenderTargetUsage` of your render target to `PreserveContents` when constructing it.

`DiscardContents` is the default for performance reasons: On mobile systems and on the Xbox 360, retaining the contents of a render target is an expensive operation. This default is used on all platforms to aid portability.

I am not sure whether MonoGame's implementation matches this behaviour exactly.

An alternative approach would be to "bounce" the texture between two render targets, alternating which is rendered to on each frame. (This can also allow you to do effects like fading out the existing streaks.)

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


title: Collision method for multiple circles

text:
# Question
Title: Collision method for multiple circles
This is a bouncing ball program. There is 1 dynamic circle and 3 static ones. The static ones are obstacles for the dynamic circle, and the dynamic circle is supposed to bounce off of the static circles.

So I have an ArrayList of static circles:

```
public static List<Circle> circles_Static = new ArrayList<Circle>();

```

Something is wrong with my method for checking if the dynamic circle collides with any of the static ones. Currently, the dynamic circle starts bouncing all over the canvas extremely quickly and even disappears. So, if I don't use this method and call each static circle separately and see if it collides with the dynamic one, it's working perfecly. There's definitely something wrong with how the method is working and I really can't see what it may be.

Here's the method:

```
    public void collision() {
        for (int i = 0; i < circles_Static.size(); i++) {
            double dx = circles_Static.get(i).getLayoutX() - circle1.getLayoutX();
            double dy = circles_Static.get(i).getLayoutY() - circle1.getLayoutY();
            double minDistance = circles_Static.get(i).getRadius() + circle1.getRadius();
            double distance = (dx * dx) + (dy * dy);

            if (distance < minDistance * minDistance) {
                double angle = Math.atan2(dy, dx);
                double targetX = circle1.getLayoutX() + Math.cos(angle) * minDistance;
                double targetY = circle1.getLayoutX() + Math.sin(angle) * minDistance;
                double ax = (targetX - circles_Static.get(i).getLayoutX()) * spring;
                double ay = (targetY - circles_Static.get(i).getLayoutY()) * spring;
                c1SpeedX -= ax;
                c1SpeedY -= ay;
                return;

            }
        }
    }

```

You can find the full source code below:

```
public class VideoGame1 extends Application {

    public static List<Circle> circles_Static = new ArrayList<Circle>();
    public static Circle circle1;
    public static Circle c1_Static;
    public static Circle c2_Static;
    public static Circle c3_Static;
    public static Pane canvas;
    double spring = 1;
    private long counter = 0;
    double c1SpeedX = 1;
    double c1SpeedY = 1;

    @Override
    public void start(Stage primaryStage) {

        canvas = new Pane();
        Scene scene = new Scene(canvas, 800, 600);

        primaryStage.setTitle("Ball Game");
        primaryStage.setScene(scene);
        primaryStage.show();

        c1_Static = new Circle(100, Color.BLACK);
        c1_Static.relocate(300, 200);
        circles_Static.add(c1_Static);

        c2_Static = new Circle(20, Color.CORNFLOWERBLUE);
        c2_Static.relocate(550, 250);
        circles_Static.add(c2_Static);

        c3_Static = new Circle(40, Color.CORAL);
        c3_Static.relocate(500, 500);
        circles_Static.add(c3_Static);

        canvas.getChildren().addAll(circles_Static);

        circle1 = new Circle(30, Color.BLUE);
        circle1.relocate(100, 60);

        canvas.getChildren().addAll(circle1);

        Timeline loop;
        loop = new Timeline(new KeyFrame(Duration.millis(1), new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {
                if (counter++ % 2 == 0) {
                    // Moves the ball
                    circle1.setLayoutX(circle1.getLayoutX() + c1SpeedX);
                    circle1.setLayoutY(circle1.getLayoutY() + c1SpeedY);

// Dynamic ball bounces off the walls
                    final Bounds bounds = canvas.getBoundsInLocal();
                    boolean leftWall = circle1.getLayoutX() <= (bounds.getMinX() + circle1.getRadius());
                    boolean topWall = circle1.getLayoutY() <= (bounds.getMinY() + circle1.getRadius());
                    boolean rightWall = circle1.getLayoutX() >= (bounds.getMaxX() - circle1.getRadius());
                    boolean bottomWall = circle1.getLayoutY() >= (bounds.getMaxY() - circle1.getRadius());

      //Check if dynamic ball collides with any of the static balls

                    collision(); ////// HERE ////////

      // So the issue has gotta be on the line above. The collision() method.

                    // If the bottom or top wall has been touched, the ball reverses direction.
                    if (bottomWall || topWall) {

                        c1SpeedY = c1SpeedY * -1;

                    }
                    // If the left or right wall has been touched, the ball reverses direction.
                    if (leftWall || rightWall) {
                        c1SpeedX = c1SpeedX * -1;
                    }
                }

            }

            public void collision() {
                for (int i = 0; i < circles_Static.size(); i++) {
                    double dx = circles_Static.get(i).getLayoutX() - circle1.getLayoutX();
                    double dy = circles_Static.get(i).getLayoutY() - circle1.getLayoutY();
                    double minDistance = circles_Static.get(i).getRadius() + circle1.getRadius();
                    double distance = (dx * dx) + (dy * dy);

                    if (distance < minDistance * minDistance) {
                        double angle = Math.atan2(dy, dx);
                        double targetX = circle1.getLayoutX() + Math.cos(angle) * minDistance;
                        double targetY = circle1.getLayoutX() + Math.sin(angle) * minDistance;
                        double ax = (targetX - circles_Static.get(i).getLayoutX()) * spring;
                        double ay = (targetY - circles_Static.get(i).getLayoutY()) * spring;
                        c1SpeedX -= ax;
                        c1SpeedY -= ay;
                        return;

                    } else {
                        break;
                    }

                }
            }

        }));

        loop.setCycleCount(Timeline.INDEFINITE);
        loop.play();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

```

# Answer
In this line:

```
double targetY = circle1.getLayoutX() + Math.sin(angle) * minDistance;

```

Certainly you meant `getLayoutY`.

As a side note, it is useless to compute `angle = atan2(y,x)` if the only thing you are doing afterwards is `cos(angle)` or `sin(angle)`. The cosine and sine of the angle are simply `x/sqrt(x²+y²)` and `y/sqrt(x²+y²)`, which is also a lot faster to compute.
> 3 votes

---
Tags: java, 2d, collision-detection
---


# Question
Title: Can Unity 2D be used to make pixel-art games?
I'm looking at the new 2D features introduced in Unity 4.3, and I think I might be missing something.

To me it looks like they are designed for high-res 2D games, where scaling the sprites is ok, but it is unsuitable for pixel-art games.

A pixel-art sprite is designed to be displayed exactly 1:1 pixels on the screen: scaling destroys it (linear up-scaling is an exception, i.e. you may scale it 2x, 3x, 4x etc.).

However I've found no way to "just display it as-is", apparently Unity insists in scaling it to whatever resolution it sees fit: I may control the Camera.size parameter, and the "pixels to units" parameter of the sprite, but I didn't manage to obtain this result.

# Answer
> 19 votes
This article gives some useful explainations, even if that's before 4.3 came out:

> If you’re going for the “pixel art” look then the camera’s orthographic size is of critical importance; this is the trickiest part of nailing 2D in Unity.
>
> The orthographic size expresses how many world units are contained in the top half of the camera projection. For example, if you set an orthographic size of 5, then the vertical extents of the viewport will contain exactly 10 units of world space. (The horizontal extents are dependent on the display aspect ratio.)
>
> Recall that your sprite quad is 1 unit to a side. That means the orthographic size tells you how many sprites you can stack vertically in the viewport (divided by 2).
>
> To render the pixel-art look cleanly, you need to ensure that each pixel of the sprite’s source texture maps 1:1 to the viewport display. You don’t want source pixels being skipped or doubled-up, or your sprites will look distorted and “dirty”. The trick to ensuring this 1:1 ratio is to set an orthographic size that matches your vertical screen resolution divided by the pixel height of a sprite.
>
> Let’s say you’re running at 960x640, and you’re using 64x64 sprites. Dividing the vertical screen resolution (640) by the pixel height of a sprite (64) yields 10, the number of 64x64 sprites that can be vertically stacked in 640 pixels. Remember that the orthographic size is a half-height, so your target orthographic size in this case is going to be 5 (one-half of 10). It should look like this:
>
> If you set your orthographic size to half or double that target you may still get usable results, because the sprite’s vertical size will still divide evenly into the viewport’s vertical size. But if you set the orthographic size incorrectly, you will see some pixels skipped or doubled, and it will look very bad indeed:
>
> **Variable Resolution**
>
> You don’t need to be confined to a single, fixed resolution in order to render clean pixel art. **The simplest way to handle variable resolutions is to attach a custom script to your camera which sets the orthographic size according to the current vertical resolution and a known (fixed) sprite size**:

```
// set the camera to the correct orthographic size
// (so scene pixels are 1:1)
s_baseOrthographicSize = Screen.height / 64.0f / 2.0f;
Camera.main.orthographicSize = s_baseOrthographicSize;

```

> While that is a simple fix, it does have a drawback: as the screen resolution decreases, you’ll see less and less of the world, and sprites will take up more and more of the screen. That’s the consequence of keeping a 1:1 ratio between source and screen pixels: a 64x64 sprite takes up more apparent space at 640x480 than it does at 1920x1200. Whether this is a problem or not depends on the needs of your specific game.
>
> If you want your sprites to remain the same apparent size regardless of screen resolution, then simply set the orthographic size to a fixed value and leave it there regardless of the screen resolution. The drawback there is that your sprites will no longer have a 1:1 source-to-screen pixel ratio. You can mitigate the ill effects of that by only allowing resolutions which are exactly half or exactly double your target resolution.

*(some emphasis added)*

This obviously works better if the height resolution is divisible by the sprite size, but even when it isn't, it still gives a good approximation of a decent result.

---

**TL;DR**: `cameraSelf.orthographicSize = screenH / (float)spriteSize / 2f;`

---
Tags: 2d, unity, sprites, pixel, pixel-art
---


# Question
Title: Drawing behavior when a fragment is written to multiple times in a single pass
This seems really basic, but I'm confused and can't find a clear answer anywhere.

What happens to a target fragment of a rendertarget if the fragment is written to multiple times within one pass (e.g. by drawing two identical triangles above each other), assuming depth and stencil testing is disabled?

Does this just use the behavior specified with the current blend state? If not, can I modify this behavior?

# Answer
It does indeed use the blend state to determine what happens (along with the depth and stencil states).

The result will be exactly the same as if you'd drawn the two triangles in separate draw calls.
> 2 votes

---
Tags: opengl, rendering
---


title: Send info about gun shots via UDP

text:
# Question
Title: Send info about gun shots via UDP
I am writing a small multiplayer game in C++. But I am confused about how to send info about gun shots to achieve best performance. I am thinking of different ways to do that: Let's say we have a gun that can shoot 10 times per second (when left mouse button is held).

* When user presses LMB game sends TCP packet telling that shooting has started. When user releases LMB game send TCP packet telling that shooting has stopped.
* When LMB is held game send UDP packet every (1/10) sec telling about one shot.
* When LMB is held game send TCP packet every (1/10) sec telling about one shot.

I think that the last one is the best because it allows to check hits on the server side, not on the client side (cause this way it can be easily hacked). But I am not sure if TCP can handle 10 packets per second. What do you suggest?

# Answer
UDP does not ensure that the package will arrive properly or that will arrive ordered, but is faster than TCP. TCP ensures the aforementioned features but is slower because of acks. Usually, action based games like FPS should use UDP because of the volume of data that must be sent/received over network. On the other hand, turn-based games should use TCP because the demands are more loose. Since your game is a shooter I would suggest you go for UDP at least for the shot data. But, you should profile if the ratio of lost packets is adequate and make aditional code to handle the packet loss. Some libraries implement reliable UPD which is an UDP that ensures the arrival of packages.

As a rule of thumb, use UDP for data which you don't mind to lose and TCP for data which is necessary to arrive at destiny.
> 2 votes

# Answer
I believe losing a message about a gun shot event cannot be tolerated since it has the potential of affecting the player's responses, unlike the position updates.

You can use TCP to let the client know about the 'shooting started' event. When the enemy player stops firing, send the 'shooting finished' event. None of the packages will be lost, therefore, the game will stay synchronized. However, you can implement your own reliable application layer protocol using UDP if the TCP performance seems low.
> 1 votes

# Answer
In a project I once was involved (not game related) they decided to send each UDP message twice to reduce losses with an event id so if both messages were received the receiver could ignore the second, sounds basic but it did the trick.

first define burst:

shotgun and sniper has a burst of one bullet

smg has a burst of 5 (?!)

for each bullet send a UDP, for each burst send a TCP. the UDP is only for show the TCP is for synchronization.
> 1 votes

---
Tags: c++, algorithm, multiplayer, socket
---


# Question
Title: How can I support more than one resolution/language on WP7/8?
I want that my Windows Phone game runs on the following three resolutions: 480x800, 768x1280 and 720x1280. And maybe later on 1920x1080. But in the XAP file information, it's just written "Resolution(s) WVGA". What can I support more resolutions than just WVGA?

In addition, I want to support more than one language. At the moment, I can just choose English in the Dev Center menu, but I want to support French, Spanish and German too. How can I support French, Spanish and German? I don't know how to add these languages.

I uploaded my XAP file in the Dev Center and it gives me the following informations:

> Select a XAP above to view or edit its Store listing and other info.
>
> XAP version number 1.0.0.0
>
> XAP details detected from file
>
> File name WindowsPhoneGame2.xap
>
> File size 167 KB
>
> Supported OS 7.1, 8.0
>
> Resolution(s) WVGA
>
> Language(s) EnglishNorthAmerica
>
> Capabilities ID\_CAP\_NETWORKING
>
> XAP's Store listing info
>
> A XAP file can contain multiple languages. Select a language to add Store listing info specific for that language.
>
> English
>
> Description for the Store:

# Answer
For the multi language support, you are looking for something called *localization* , it's a common process used almost in every software development that have more than a single language, here is a special tutorial for How to: Create a Localized Game on XNA .

For the multi resolution issue, as Homer\_Simpson said (lol), you cannot use resolutions above 800x480 on windows phone with XNA, and in case you moved to MonoGame, as far as i know, there is no magic trick to make such a thing, you have to build it yourself, game engines like unity3D use something called "Virtual Resolution" (World scale and position in unity), the whole principle is about using your own resolution for the whole development, and then scale all the objects based on the target resolution, i myself always use percentage to scale and set positions, specially for GUI cause even unity3D use current screen resolution when it comes to gui,so my suggestion would be to make the whole game in 1 resolution, then calculate the percentage of each object size and position relative to your resolution,

> Example :
>
> Resolution = 800x600 Object = Width=120;Height=80;
>
> 120 = 15% of 800
>
> 80 = 13.33% of 600
>
> based on that, you have now to change your object parameters to this :
>
> Object.Width = (Screen.width * 15 )/100
>
> Object.Height = (Screen.Height * 13.33)/100
>
> if you saw some HTML or CSS codes, you'll notice that they also use percentage to place and scale everything
>
> *PS : sometimes when i was coding GUIs i needed to do the same thing for X & Y*
> 0 votes

---
Tags: xna, c#, windows-phone-7, windows-phone-8
---


# Question
Title: How do I draw an isoline in a shader with a triangle topology?
I have some problems with my displacment. So I would like to have a simple little isoline starting in every triangles face center of the mash pointing in the direction of the corresponding faces normal direction. like in the following picture (okay these are no triangles, but still something like that): Can I draw isoline in my shader when the topology is a trianglelist? if yes, how do I do that?

# Answer
> 2 votes
No, you cannot mix different primitive types in the same shader / draw call. If you're drawing triangles, you can't also draw line segments.

To draw face normals like this, you could do a second draw call with a geometry shader that generates the line segment for each face.

---
Tags: shaders, hlsl, directx11, normals
---


# Question
Title: textures in tilemap games: use 2d planes or 3d objects? (example with Dragons of Atlantis)
How to create the textures in games such as Dragons of Atlantis?

I was thinking about 2 ways:

* using 2d planes to save space and memory, using the color from the 3d software
* adding a very simple mesh and stick a detailed texture onto it in Unity

Is there a preferable way to choose between the two? The first solution could save some memory, but maybe a bit difficult to change the camera view for example at the end of the game.
As for the second solution, it would be creating a very detailed mesh in the 3d software, paint the texture, cut the texture and add it to a very simple mesh, such as cubes. Could be better, but maybe it would take more work.

What do you think?

Thanks

# Answer
It looks like it's a 2D isometric tilemap with pre-rendered tiles.

Some or actually most structures are larger than a single tile, sometimes spanning large areas, one looks like 5x5 tilea, another looks like an arbitrary shape but still isometric on its outline to hide the fact that it's a flat 2D isometric tilemap composed of individual sprites/textures.
> 1 votes

# Answer
Although I'm not sure whether this will fully answer your question, I want to point you to a tutorial series that might be very helpful to you if you want to make some kind of tilemap. The guy in the video first explains the "wrong" way (have each tile be a plane) and why exactly it's "wrong", then he goes on to explain what the "right" way and showing how he would implement it. The series in total is a bit long (~5 hours), but you'll probably be able to skip some parts where he might be explaining things you might already know.
> 1 votes

---
Tags: unity, textures, tilemap
---


# Question
Title: Why swapping buffers takes different amounts of time?
When my program starts, almost nothing is on screen, just couple of lights and spheres. My FPS is at ~50. The Speed measurements looks like this:

```
UpdateFrame took 0 ms
Clearing lights queue: 0 ms
Queue floor for rendering: 0 ms
Clearing and starting deferred: 0 ms
base.OnRenderFrame: 0 ms
ModelRenderer.Render (): 0 ms
LightingEngine.RenderFrame (): 0 ms
deferred.RenderOnScreen (): 0 ms
Gui.Render (): 1 ms
SwapBuffers (): 18 ms
ModelRenderer.Clear (): 0 ms

Whole rendering took: 19 ms

```

But then after a while the program has been running for some time and more lights and spheres are added, the FPS is ~40 and the speed measurements are as follows:

```
UpdateFrame took 0 ms
Clearing lights queue: 0 ms
Queue floor for rendering: 0 ms
Clearing and starting deferred: 0 ms
base.OnRenderFrame: 5 ms
ModelRenderer.Render (): 4 ms
LightingEngine.RenderFrame (): 7 ms
deferred.RenderOnScreen (): 0 ms
Gui.Render (): 0 ms
SwapBuffers (): 7 ms
ModelRenderer.Clear (): 0 ms

Whole rendering took: 23 ms

```

I had VSYNC off for this test. This clearly implies that my GPU has too much to chew. I want to know why the SwapBuffers() is taking less time with more stuff on screen, shouldn't it take more or equal time then?

# Answer
> 5 votes
OpenGL sometimes defers your commands until later -- when you see a 0 ms runtime for a particular GL operation, it doesn't mean that operation took 0 ms, it just means *that function call* (which may have simply queued an operation, not did an actual GPU operation) took a small amount of time. See glFlush().

So, it depends on what work is being done where. `SwapBuffers` requires *all* queued work be complete (to actually display the frame), so depending on how much work got done earlier in the frame, more or less work will have to be done at the time that `SwapBuffers` is called.

Also, another reason you'll see this type of difference and apparent jumps in the `SwapBuffers` call is because `SwapBuffers` likely waits for VSYNC. If your VSYNC is 60 Hz, and actual frame render time jitters between 15ms and 17 ms, then on the 15 ms frame, you will see a frame rate of 60 FPS, and for the frame that took 17ms, one VSYNC will be *missed*, so you'll have to wait for the next one, apparently halving the frame rate (for those 2 frames).

So you're going to have jumps between 60 FPS and 30 FPS, which averages out to about 45 fps, depending on how many 60FPS frames you got, and 30 FPS frames you got.

# Answer
> 0 votes
My guess would be that you're GPU bound. Looking at CPU side timings when you're GPU limited won't tell you very much - a lot of that CPU time will be spent idle waiting for the GPU.

What you need is some kind of GPU profiler to tell you what's going on

---
Tags: opengl, opentk, double-buffering
---


title: Quads Vs Triangles

text:
# Question
Title: Quads Vs Triangles
I'm curious to know which is better for games: quads or triangles? Wouldn't quads be better for rendering performances and smoothing out tessellation?

# Answer
> 27 votes
Triangles, the reason is triangles' ratesrization algorithm is faster, and also natively supported in hardware. So it would be faster to convert one quad into two triangles and do the rasterization. Actually that is what happens when you draw a quad on modern graphics hardware.

### So the question is what makes it faster ?

There are certain characteristics in the triangle that makes working with it simpler and faster:

* Any three non colinear points form a triangle.
* Every triangle forms a unique plane. Triangle points cannot be part of two planes at the same time, unlike a quads, which save us the trouble from dealing with degenerate cases like this:  **Notice how the top quad in the middle vertices don't lay entirely in the same plane.**

* Any shape can be broken down into triangles, and triangles can only be broken down into triangles(not counting the degenerate cases).
* **"Point in triangle test"** is much simpler and faster than "point in polygon test" ( also called odd even test). The point in triangle test is done using the Barycentric coordinates which is the main reason why triangles are faster to rasterize. Which brings us to the next point.
* Barycentric coordinates are not only useful for point in triangle test, but also for other interpolation operations, which are so common in computer graphics, color and texture coordinates to name few.

### But I am still not convinced, quads ftw! We still need them..

Well, yes! It makes a lot of sense for artists to use quads. (I am not artist myself, but I did study arts- and I suck at it, weird?) Dealing with quads is more intuitive when modeling a 3D shape, providing texture coordinates is also much easier, but this doesn't deny the fact that you only need to deal with quads at the assets creation level, games and 3d engines usually need every bit of performance, so it would some kind of naivety to provide a sub-optimal structure of geometry to the GPU when it's doesn't really have any direct advantage, why use sub-optimal structure when we can take the best of each worlds? Quads at the assets creation level, and triangles at the engine level!

---
Tags: optimization, 3d-meshes, computational-geometry
---


title: Superclassing RPG Game Entities

text:
# Question
Title: Superclassing RPG Game Entities
I am in the design process of an RPG game and I have no experience at all in game dev. This question is about how I should approach entity management using OOP classes.

My train of thought is as followed:

* Have Entity interface with basic update() function
* "Mortal" class and "NPC" class implement Entity
* "Hero" and "Monster" class inherit from "Mortal" class

In this case, Mortal class are all those entities that have statuses such as HP and MP. NPC are self explanatory.

I am sure my approach is naive so I would like to know the pros and cons and what would be a better way to approach this.

# Answer
Your approach is fine, and was used widely by game developers of the past. You see with inheritance hierarchy you often find yourself in a situation there you want inherit from a multiple classes, but they don't usually mix well (including The diamond problem). Because of that, a component based architecture is being widely adopted. One variation of this approach is called Entity component system or ECS. This approach uses composition instead of inheritance to build up functionality of the entity (note that entity have a very special meaning in ECS). If you are interested in ECS here is some references for you to start: one, two, three.

As Sean Middleditch correctly noticed ECS is just one type of implementation, you are free to use other approaches.

As a side note, I really suggest you not concentrate much on architecture for your first attempts. It's really hard to make all right and nice in games. There are many other aspects which are important for a novice: handling game loop, input, graphics, sound, physics, collision detection, and the list goes on. You should try to make small game (like Tetris or Breakout) ignoring architecture nuances, to become comfortable with your tools, and see the whole picture.
> 8 votes

---
Tags: entity-system, oop
---


# Question
Title: When creating the horizontal blur, how is the vertex shader being called for each pixel?
I am following this tutorial. I am confused as to why the VertexShader is being called each time for the PixelShader. I was under the assumption the VertexShader is called only **6 times during the pipeline**. Additionally, what is the order in which the shaders are being called.

```
Horizontalblur.fx

////////////////////////////////////////////////////////////////////////////////
// Filename: horizontalblur.fx
////////////////////////////////////////////////////////////////////////////////

/////////////
// GLOBALS //
/////////////
matrix worldMatrix;
matrix viewMatrix;
matrix projectionMatrix;

Texture2D shaderTexture;

float screenWidth;

///////////////////
// SAMPLE STATES //
///////////////////
SamplerState SampleType
{
    Filter = MIN_MAG_MIP_LINEAR;
    AddressU = Wrap;
    AddressV = Wrap;
};

//////////////
// TYPEDEFS //
//////////////
struct VertexInputType
{
    float4 position : POSITION;
    float2 tex : TEXCOORD0;
};

struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
    float2 texCoord1 : TEXCOORD1;
    float2 texCoord2 : TEXCOORD2;
    float2 texCoord3 : TEXCOORD3;
    float2 texCoord4 : TEXCOORD4;
    float2 texCoord5 : TEXCOORD5;
    float2 texCoord6 : TEXCOORD6;
    float2 texCoord7 : TEXCOORD7;
    float2 texCoord8 : TEXCOORD8;
    float2 texCoord9 : TEXCOORD9;
};

////////////////////////////////////////////////////////////////////////////////
// Vertex Shader
////////////////////////////////////////////////////////////////////////////////
PixelInputType HorizontalBlurVertexShader(VertexInputType input)
{
    PixelInputType output;
    float texelSize;

    // Change the position vector to be 4 units for proper matrix calculations.
    input.position.w = 1.0f;

    // Calculate the position of the vertex against the world, view, and projection matrices.
    output.position = mul(input.position, worldMatrix);
    output.position = mul(output.position, viewMatrix);
    output.position = mul(output.position, projectionMatrix);

    // Store the texture coordinates for the pixel shader.
    output.tex = input.tex;

    // Determine the floating point size of a texel for a screen with this specific width.
    texelSize = 1.0f / screenWidth;

    // Create UV coordinates for the pixel and its four horizontal neighbors on either side.
    output.texCoord1 = input.tex + float2(texelSize * -4.0f, 0.0f);
    output.texCoord2 = input.tex + float2(texelSize * -3.0f, 0.0f);
    output.texCoord3 = input.tex + float2(texelSize * -2.0f, 0.0f);
    output.texCoord4 = input.tex + float2(texelSize * -1.0f, 0.0f);
    output.texCoord5 = input.tex + float2(texelSize *  0.0f, 0.0f);
    output.texCoord6 = input.tex + float2(texelSize *  1.0f, 0.0f);
    output.texCoord7 = input.tex + float2(texelSize *  2.0f, 0.0f);
    output.texCoord8 = input.tex + float2(texelSize *  3.0f, 0.0f);
    output.texCoord9 = input.tex + float2(texelSize *  4.0f, 0.0f);

    return output;
}

////////////////////////////////////////////////////////////////////////////////
// Pixel Shader
////////////////////////////////////////////////////////////////////////////////
float4 HorizontalBlurPixelShader(PixelInputType input) : SV_Target
{
    float weight0, weight1, weight2, weight3, weight4;
    float normalization;
    float4 color;

    // Create the weights that each neighbor pixel will contribute to the blur.
    weight0 = 1.0f;
    weight1 = 0.9f;
    weight2 = 0.55f;
    weight3 = 0.18f;
    weight4 = 0.1f;

    // Create a normalized value to average the weights out a bit.
    normalization = (weight0 + 2.0f * (weight1 + weight2 + weight3 + weight4));

    // Normalize the weights.
    weight0 = weight0 / normalization;
    weight1 = weight1 / normalization;
    weight2 = weight2 / normalization;
    weight3 = weight3 / normalization;
    weight4 = weight4 / normalization;

    // Initialize the color to black.
    color = float4(0.0f, 0.0f, 0.0f, 0.0f);

    // Add the nine horizontal pixels to the color by the specific weight of each.
    color += shaderTexture.Sample(SampleType, input.texCoord1) * weight4;
    color += shaderTexture.Sample(SampleType, input.texCoord2) * weight3;
    color += shaderTexture.Sample(SampleType, input.texCoord3) * weight2;
    color += shaderTexture.Sample(SampleType, input.texCoord4) * weight1;
    color += shaderTexture.Sample(SampleType, input.texCoord5) * weight0;
    color += shaderTexture.Sample(SampleType, input.texCoord6) * weight1;
    color += shaderTexture.Sample(SampleType, input.texCoord7) * weight2;
    color += shaderTexture.Sample(SampleType, input.texCoord8) * weight3;
    color += shaderTexture.Sample(SampleType, input.texCoord9) * weight4;

    // Set the alpha channel to one.
    color.a = 1.0f;

    return color;
}

////////////////////////////////////////////////////////////////////////////////
// Technique
////////////////////////////////////////////////////////////////////////////////
technique10 HorizontalBlurTechnique
{
    pass pass0
    {
        SetVertexShader(CompileShader(vs_4_0, HorizontalBlurVertexShader()));
        SetPixelShader(CompileShader(ps_4_0, HorizontalBlurPixelShader()));
        SetGeometryShader(NULL);
    }
}

```

# Answer
> 5 votes
The vertex shader *is* called only 6 times, if you're drawing a full-screen quad using two triangles.

I'm guessing that you're getting confused because the outputs of the vertex shader (here, the `PixelInputType` struct) are being fed as inputs to the pixel shader. What's going on is that those values are being linearly interpolated between the vertices, to generate values for each pixel in the triangle.

For example, if the vertex shader outputs a value of 4 for one vertex, and 7 for another vertex, then each pixel in the triangle will get a value intermediate between 4 and 7, depending on where it is relative to the vertices. The pixel values change smoothly and linearly from 4 to 7 as you move across the triangle. This is calculated automatically by the hardware for each variable output by the vertex shader - such as position, normal, texture coordinates, etc.

The vertex shader runs first, and outputs the clip-space positions of the vertices, as well as all the values to be interpolated. The hardware rasterizer then uses that information to determine which pixels are part of the triangle, and the pixel shader is then called once for each of those pixels, passing in interpolated versions of all the variables output from the vertex shader.

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


title: Cocos2d-x cross platform development

text:
# Question
Title: Cocos2d-x cross platform development
I want to make a game with my friends on iOs, Android, WP operating systems. We decided to use a cocos2d-x and develop the core of the game on C++. What will be the right way of developing so that we can write the game all together simultaneously but just build the project differently on every platform.
We thought of writing the core of the game in C++ in Visual Studio, but there is the problem: How can we test it fast on every platform? How people usually develop multi-platform projects?.
Also we would really like to hear some recommendations about the source controlling of the whole project. Thank you in advance.

# Answer
You can just write your code in C++ in Visual Studio. It is very easy to port your win32 application to Android or iOS with cocos2d-x. There are a lot of tutorials to teach you how to do it. If you create the project with the `python` scriptLINK . You will find there different project in the folder. After you finish your C++ project, all cocos2d-x Android project needs is the `Classes` and `Resources` folder.

This link shows how can you set up cocos2d-x environment both C++ and Android project, but is in Chinese written by me. In brief,for Android project, you need Android SDK and NDK. And follow some step to set up your Android development environment. And you can debug your project.

If you want more details just @me.I am glad to help. PS.I am new in cocos2d-x, I really don't know how other people develop multi-platform projects.
> 1 votes

---
Tags: android, ios, cross-platform, cocos2d-x, windows-phone-8
---


# Question
Title: How can I get my Android camera system working more like Google Earth's?
I'm implementing a touch screen interface whereby the user dragging their finger on the screen will rotate the camera in a sphere around the central point.

My code works well for the horizontal swipe (rotation around the y axis), but only covers a smaller angle from the vertical swipe (rotation around the x axis) instead of the full 360. I used the article - Spherical coordinate system form Wikipedia (http://en.wikipedia.org/wiki/Spherical\_coordinate\_system), specifically the Cartesian Coordinates section, to do this. I've posted my code below. Can anyone help get this working through the full 360 degrees on both axis? See how Google Earth works when you swipe the globe for what I want.

This must have been done a billion times, but Google searches confuse with the phone built in camera, gps and the like. Thanks!

```
//Get current position
oldX = getPosition().x;
oldY = getPosition().y;
oldZ = getPosition().z;

//convert to inclination/azimuth
camRadius = Math.sqrt((oldX * oldX) + (oldY * oldY) + (oldZ * oldZ));
inclinationTheta = Math.acos(oldZ / camRadius);
azimuthPhi = Math.atan2(oldY,oldX);

.
.
.

//use touch screen changes (deltaTouchX and Y)
inclinationTheta = (inclinationTheta + deltaTouchScreenX) % (2 * pi);
azimuthPhi = (azimuthPhi + deltaTouchScreenY) % (2 * pi);

//get new co-ordinates
newX = camRadius * Math.sin(inclinationTheta) * Math.cos(azimuthPhi);
newY = camRadius * Math.sin(inclinationTheta) * Math.sin(azimuthPhi);
newZ = camRadius * Math.cos(inclinationTheta);

//set new position
setPosition(newX, newY, newZ);

```

# Answer
> 0 votes
I've decided to rotate the objects in the scene, instead of the camera. It works almost as I want. Those articles where a bit beyond my abilities.

```
//Y
float oldX =  myObject.getX();
float oldZ =  myObject.getZ();

float newX = (float) (oldZ * Math.sin(rotationAngleY) + oldX * Math.cos(rotationAngleY));
float newZ = (float) (oldZ * Math.cos(rotationAngleY) - oldX * Math.sin(rotationAngleY));

myObject.setX(newX);
myObject.setZ(newZ);

//X
float oldY =  myObject.getY();
oldZ =  myObject.getZ();

float newY = (float) (oldY * Math.cos(rotationAngleX) - oldZ * Math.sin(rotationAngleX));
newZ = (float) (oldY * Math.sin(rotationAngleX) + oldZ * Math.cos(rotationAngleX));

myObject.setY(newY);
myObject.setZ(newZ);

//Z
oldX =  myObject.getX();
oldY =  myObject.getY();

newX = (float) (oldX * Math.cos(rotationAngleZ) - oldY * Math.sin(rotationAngleZ));
newY = (float) (oldX * Math.sin(rotationAngleZ) + oldY * Math.cos(rotationAngleZ));

myObject.setX(newX);
myObject.setY(newY);

```

---
Tags: java, android, 3d, camera, graphics-programming
---


# Question
Title: How can I handle errors when there is no valid OpenGL context?
I'm writing cross-platform (iOS, Android, OSX, Windows) library code that draws its output using OpenGL. I expect my users will often try to call my library's rendering functions without a valid OpenGL context (especially when they are first getting started), so how can I cleanly handle the error?

So far I have tried calling some OpenGL function and then calling `glGetError()` to see if it failed (and printing my user a helpful error message), but `glGetError()` segfaults if there is no context:

```
// Test for OpenGL Context

glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // This line segfaults

if (glGetError() != GL_NO_ERROR)
    printf("You tried to call a rendering function but no OpenGL context was found!");

```

Is there a way to check for a valid context within OpenGL without getting a segfault?

# Answer
> 3 votes
You can use these vendor specific functions:

* `wglGetCurrentContext()` on Windows,
* `aglGetCurrentContext()` on OSX,
* `glxGetCurrentContext()` on unixoid systems with X and
* `eglGetCurrentContext()` on GLES based systems like iOS or Android

They all return `NULL` (except for `eglGetCurrentContext`, which returns `EGL_NO_CONTEXT`) if there is no valid context currently active.

---
Tags: opengl, opengl-es, cross-platform
---


title: Storing attributes in static geometry

text:
# Question
Title: Storing attributes in static geometry
I have a Minecraft like world where I statically create one instance of each tile type, and then place it around the world. However, I don't know how to actually change individual attributes for each tile. For instance, I need to change the lighting per tile, but if I do, it'll change the color of ever single tile. I was thinking about storing two arrays per chunk, one for the tiles and one for the light, and when I want to change the lighting, I can just change the value in the lighting array that coincides with the position in the tile array. However, this will mean I'll have to have store twice as much data per chunk, but is it something I have to accept?

# Answer
> -1 votes
You should check deferred shading system. It implies that you capture the original color of the tiles into a rendertarget and normals and depth of the tiles into other rendertargets (usually done in a single pass with multiple render target technique). You then apply lighting only to those pixels that you store in the rendertargets. So basically your tile data will be completely separated from your lighting and from how you store your tile date in memmory.

Here are some links for deferred shading: http://en.wikipedia.org/wiki/Deferred\_shading http://ogldev.atspace.co.uk/www/tutorial35/tutorial35.html

You should also study general lighting theory for 3d graphics as it seems to me that you might not completely understand how it works:

http://en.wikipedia.org/wiki/Phong\_shading http://www.opengl.org/sdk/docs/tutorials/ClockworkCoders/lighting.php

---
Tags: opengl, java, voxels
---


# Question
Title: What would be a suitable way to model projectiles in an action game?
I'm designing a 2d fighting game in which characters can shoot out some projectiles like arrows, ninja knives, Hadouken (like the one in Street Fighter), etc...

My current character design is actually in a component based manner, however, I've no idea about how to model these projectiles. I've thought about treating each single projectile as a single object, but I'm afraid that there will be performance problem as long as I keep creating these projectiles in the game.

I've read this question also, but it seems that it's to quite suitable to my situation

Bullets and projectiles in component based entity systems

Any comments would be appreciated! :)

# Answer
I have seen this accomplished in a number of ways. One in particular that I favor is creating a "*pool*" of projectiles, or a set -concrete number of objects that the game can never exceed. This will solve a number of issues,

* Performance: You will always be able to test what happens when the max allowed projectiles are in game.
* Memory: Hopefully you are taking measures to make sure your textures are only being used once (persistent/static). IE, the same texture memory address is being referenced by all the projectiles of type *knife*. From a memory standpoint -especially if you are working with a physics engine, having a set number of objects in a pool will keep your engine from having to consistently allocate and deallocate vectors.

Typically starting with a core layer projectile class that all projectiles inherit you will need the ability to determine if the projectile is currently being used or if it is *inactive* and hidden from view of the user. From there I would create a projectile management class that allows you to *queue projectiles*. The management class will simply not create anymore projectiles if the *pool* is empty.

From a performance standpoint I would then run a routine at 1/6 the frequency of the game updating engine -or even slower- to cleanup and detect stray projectiles (knives and hatchets that have flown off screen) -which will replenish your pool. At this point the projectile management class will mark the object as inactive in the physics engine and make the object invisible. Also great from a testing standpoint, by mashing on your fire button and using up all the projectiles in the pool -does the pool fill all the way back up with free projectiles when you stop firing? If you have a memory profiler -do you have a memory leak when all the projectiles are fired and restored to an inactive state?

Hope this helps!
> 2 votes

---
Tags: performance, software-engineering, projectile-physics
---


# Question
Title: How would one construct a realistic "infrared vision" effect?
How would you go about constructing a realistic infrared vision effect with shaders? By realistic I mean one that *looks* realistic, like this example.

I have an idea about making a texture to determine how much heat a material emits and then determine by using the dot product of normal and view vector how much of that heat reaches the viewer but I'm not even sure that this is how thermal vision even works so I wanted to check if there's a better approach before starting to implement something that might be entirely wrong.

# Answer
There's IR, and then there's IR. The range of light wavelengths commonly called "infrared" extends from the edge of the human visual range (about 700 nm) up to 1 mm = 1,000,000 nm.

Philipp's answer is correct for "near-infrared" light (about 700 to 1,400 nm), which is basically just like normal visible light, except that it's invisible to the unaided human eye. To model near-IR vision, you'd just replace your object textures and light source colors with alternative ones that model their reflectances and light intensities at different wavelengths than usual

However, based on the wording of your question and the video you linked to, you seem to be more interested in the "thermal infrared" range (8,000 to 15,000 nm), which corresponds to the peak of the thermal radiation spectrum of most everyday objects, including the human body. This radiation still behaves in most ways like "light" and can be modeled using standard computer graphics techniques (as opposed to radio waves, where the wavelengths get long enough that standard assumptions of ray optics start to break down), but the world as seen in thermal infrared does have its peculiarities:

* As noted above, most objects will glow in thermal IR. For visible light, you can generally assume that there are only a few actual light sources, with everything else just reflecting light emitted by other sources. For thermal IR, depending on the exact wavelength(s) chosen, the opposite is often the case.
* Conversely, most surfaces will also absorb thermal IR pretty efficiently. This will, in turn, warm them up, causing them to re-emit more IR themselves. In effect, it's as if almost every surface was phosphorescent.
* The thermal IR spectrum (i.e. "color") emitted by most surfaces will mainly depend on their temperature. The intrinsic emissivity of the surface material does have an effect too, but a relatively limited one.

Thus, compared to normal light vision, modeling *realistic* thermal infrared vision would require more emphasis on global illumination and on dynamically changing emissivity values. Depending on your setting, you might be able to cheat a bit here: for example, for static scenes, the global radiative thermal transfer functions can be precomputed once and baked into a static lightmap, just like you'd do to fake global illumination in the visible spectrum.

If you want to simulate the view through a thermographic camera in your game, I'd recommend at least the following:

* Draw and/or compute special IR emissivity and/or reflectivity textures for your objects. Pay special attention to the emissivity of warm objects (like humans or machines), which should correspond to their surface temperature. The reflectivity is relatively less important.
* You'll probably want to use just a single spectral channel (i.e. draw everything in monochrome) corresponding to the total thermal IR flux. You can postprocess the image by mapping the resulting grayscale values into a false color gradient to simulate the traditional density slicing used for thermal images.
* Consider explicitly tracking the temperature of your surfaces, such that, say, a spot on the ground that a person was lying on will remain warm (and thus glowing in IR) for a while even after the person has moved away. There are several ways you could handle that (e.g. per-vertex temperature tracking, adding decals for transient local temperature changes, etc.) with different trade-offs between realism and computational cost. You probably don't need to make it *very* realistic, but even having this effect present *at all* would be a nice touch.
> 26 votes

# Answer
What you normally see from the world is the visual part of light which is reflected by objects. A green object reflects only green light, a red object only red light and a blue object only blue light. Infra-red can be considered a fourth color which your eyes can not perceive. An infra-red camera makes infra-red light visible to you by perceiving it with a sensor and converting the infra-red image into wavelengths you can see.

Just like some materials are more or less bright in red, green or blue, they are also differently bright in IR. The IR brightness can but doesn't necessarily has to correspond to how bright it is in visible light.

Here is a scene in visible and in IR. Note how the leafs of the trees are much brighter in IR than the trunks, but the IR brightness of the different parts of the facade of the building is similar in visible and IR light.

What you could do is create two versions of all of your textures: an RGB texture for visible light and an alternative monochrome texture for infra-red. In normal mode you use the RGB texture and in IR mode you use the IR texture.

You might also consider to use different light-sources in IR mode. The sun produces as much IR light as visible light. But artificial light-sources (like halogene lamps or light-emitting diodes) produce few or almost no IR light, so they don't illuminate anything in infra-red. On the other hand there are light-sources which are much stronger in IR (like open fire) or only visible in IR (hot objects which aren't hot enough to glow red. Or artificial IR light sources. Did you know that when you wear IR goggles, you can use a TV remote as a flashlight?). Different light-conditions in normal and IR light could be an interesting gameplay element.
> 11 votes

---
Tags: shaders
---


# Question
Title: Using tex2Dlod to determine the appropriate size of the texture
We have a top-down game with fixed camera position. We also use orthographic projection so every model in the game will always be viewed from the very same angle and from the very same distance. The question we want to answer is what size should our textures be for each model. I tried turning off mipmapping and clearly saw that the game does not use the highes mip level when drawing our stuff. I also know that tex2Dlod can be used to specify which mip texture level to use for sampling, so my plan is to gradually change this value to manually specify lower and lower mip levels until I see that decreasing it further reduces the quality of the picture. The problem is I cannot figure out how to set the mip level. The value passed to the tex2Dlod function is float4 and as I understood x and y hold te texture coordinates and w holds the mip level. But it should be set in fractional representation and I cannot know what the step size is. So basically I need to know what number I need to send into the function to gradually switch mip levels.

# Answer
The w component is simply the index of the desired mipmap. A value of 0.0 will fetch the first mip level (the highest resolution), 1.0 will fetch the second level (half resolution), etc.

Fractional values are used for trilinear filtering. For example, w = 0.5 will fetch both the first and second levels and then blend 50% between them.
> 1 votes

---
Tags: textures, hlsl, level-of-detail
---


# Question
Title: Compiling 2 Dimensional Constant Arrays Right into Pixel Shader to use as Lookup Table
I want to use a small 2 dimensional look up table in a fragment shader, but I don't want to pay for the performance cost of fetching it from memory for every fragment.

Is it feasible/reasonable to simply declare or hardcode the table as an array right inside the fragment shader? If yes, any indicator as to how big I can make it?

Thanks, \- Jim

# Answer
Yes, this is a perfectly reasonable approach. When you have a static global table like this, it can be dynamically indexed without going out to memory or consuming general purpose registers. As a general rule, you should keep the table small enough to fit in a single constant buffer (4096 float4s). Here's an example:

HLSL:

```
static const float LUT[] =
{
    0, 1, 1, 2,
    3, 5, 8, 13,
    21, 34, 55, 89,
    144, 233, 377, 610,
    987, 1597, 2584, 4181,
    6765, 10946, 17711, 28657
};

float4 main(float a : TEXCOORD) : SV_TARGET
{
    return LUT[a];
}

```

Disassembly:

```
ps_5_0
dcl_globalFlags refactoringAllowed
dcl_immediateConstantBuffer { { 0, 0, 0, 0},
                              { 1.000000, 0, 0, 0},
                              { 1.000000, 0, 0, 0},
                              { 2.000000, 0, 0, 0},
                              { 3.000000, 0, 0, 0},
                              { 5.000000, 0, 0, 0},
                              { 8.000000, 0, 0, 0},
                              { 13.000000, 0, 0, 0},
                              { 21.000000, 0, 0, 0},
                              { 34.000000, 0, 0, 0},
                              { 55.000000, 0, 0, 0},
                              { 89.000000, 0, 0, 0},
                              { 144.000000, 0, 0, 0},
                              { 233.000000, 0, 0, 0},
                              { 377.000000, 0, 0, 0},
                              { 610.000000, 0, 0, 0},
                              { 987.000000, 0, 0, 0},
                              { 1597.000000, 0, 0, 0},
                              { 2584.000000, 0, 0, 0},
                              { 4181.000000, 0, 0, 0},
                              { 6765.000000, 0, 0, 0},
                              { 10946.000000, 0, 0, 0},
                              { 17711.000000, 0, 0, 0},
                              { 28657.000000, 0, 0, 0} }
dcl_input_ps linear v0.x
dcl_output o0.xyzw
dcl_temps 1
ftou r0.x, v0.x
mov o0.xyzw, icb[r0.x + 0].xxxx
ret
// Approximately 3 instruction slots used

```
> 1 votes

# Answer
It's probably fine as long as when you access the table, the index at which you access it is always a compile-time constant, or in a loop where the compiler unrolls it. For instance, you can do stuff like this:

```
float myTable[10] = { /* hardcoded values here */ };

// Using hardcoded indices
foo = myTable[0] * bar + myTable[5] * baz;

// Using indices in a loop which the compiler can unroll
// (since it has a hardcoded, not-too-large iteration count)
for (int i = 0; i < 10; ++i)
    foo += myTable[i] * farb;

```

This works because when the compiler optimizes the shader, it can optimize away the table, substituting the appropriate hardcoded table value in each place where the table is accessed. In this case the table can be as large as you like since it will only be used at compile time.

However, this is not likely to go well if you use dynamic indices in your table, or use it from a loop that the compiler can't unroll, since then the table can't be optimized away. It will have to be stored in registers, and if there are many table entries it will take up a large number of registers - which will impact performance since it reduces the number of shader invocations that can run concurrently. Also, at the beginning of the shader, you will have to spend a bunch of time populating the table, just executing a lot of move instructions to store the hardcoded values into the registers. It's not pretty, and it will almost certainly be faster to store the table in memory at that point.
> 1 votes

---
Tags: fragment-shader
---


title: string on GUI.Button not showned

text:
# Question
Title: string on GUI.Button not showned
I am sure that inventoryItem.Name contains "Wood" cause i see it when i add a breakpoint. Still i get nothing in the game. Just empty buttons.

```
void DrawInventoryContent (int id)
    {
            var buttonIndex = 0;
            var x = 0;
            var y = 0;

            foreach (var item in inventoryItems) {
                    //create position rectangel for button
                    var startMargin = buttonMargin;
                    var leftStartPosition = startMargin + buttonMargin * x + buttonWidth * x;
                    var topStartPosition = startMargin + buttonMargin * y + buttonHeight * y;
                    var buttonRectangel = new Rect (leftStartPosition, topStartPosition, buttonWidth, buttonHeight);

                    //Get inventoryiten by index
                    var inventoryItem = inventoryItems [buttonIndex];
                    var name = inventoryItem.Name;

                    //Create and place buttin
                    GUI.Button (buttonRectangel, name);

                    // check if this button is at end of row and change to next row
                    if (x == buttonsPerRow - 1) {
                            x = 0;
                            y++;
                    } else {
                            x++;
                    }
                    //go to next item
                    buttonIndex ++;

            }
    }

```

# Answer
I see a couple of potential problems. Ensure that GUI.Button is being called in OnGUI. Remember that you need to put GUI.Button in a conditional, otherwise you'll never know if someone clicks on it. Also check that you're using the appropriate GUI Style, perhaps the font size is tiny or the colour is the same as the background.
> 1 votes

# Answer
Sorry for taking up your time. The answer can be found here. http://answers.unity3d.com/questions/582692/string-on-guibutton-not-showned.html#answer-583425
> 0 votes

---
Tags: unity, gui
---


title: Blending and shadowmapping?

text:
# Question
Title: Blending and shadowmapping?
I am trying to implement shadow mapping, and currently I have 2 point lights and 1 global ambient light source and my rendering loop looks roughly like this (the details are not relevant):

```
void OpenGLRenderer::DrawRenderables(const uint32_t windowWidth, const uint32_t windowHeight, const RenderQueue& renderQueue, const RenderableLighting& lighting)
{
    GLCALL(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));

    for (uint32_t lightIndex = 0; lightIndex < lighting.mUsedLights; lightIndex++)
    {
        if (lighting.mLights[lightIndex].mLightType == LightType::LIGHT_TYPE_POINT)
        {
            GLCALL(glUseProgram(mShadowMapProgram.mProgramHandle));
            GLCALL(glBindFramebuffer(GL_FRAMEBUFFER, mFrameBuffer));
            GLCALL(glViewport(0, 0, mShadowTextureWidth, mShadowTextureHeight));
            for (uint32_t faceNum = 0; faceNum < CUBEMAP_NUM_FACES; faceNum++)
            {
                GLCALL(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_CUBE_MAP_POSITIVE_X + faceNum, mShadowMapTexture, 0));
                GLCALL(glClear(GL_DEPTH_BUFFER_BIT));

                ShadowPass();
            }
            GLCALL(glBindFramebuffer(GL_FRAMEBUFFER, 0));

        }

        // final pass
        GLCALL(glUseProgram(mDefaultProgram.mProgramHandle));
        GLCALL(glViewport(0, 0, (GLsizei)windowWidth, (GLsizei)windowHeight));

        // enable blending, how?

        ShadingPass();
    }

    GLCALL(glUseProgram(0));
}

```

The problem is the screen will only be shown with last light in the light list, for example the ambient light and therefore ignoring the effects of the point lights. I assume I somehow needs to do blending but I was wondering how and where is this done?

Thanks

# Answer
You enable or disable blending with:

```
glEnable (GL_BLEND); // disable blending
// objects that you want blended go here
glDisable (GL_BLEND); // disable blending

```

The type of blend you want to do is controlled with glBlendFunc; for accumulating multiple lights you generally lay down the scene objects all-black to start with, then use additive blending, i.e:

```
glBlendFunc (GL_ONE, GL_ONE);

```

In some cases this may give an end result greater than 1, in which case it will be clamped and your lighting might look duller than you'd like. One solution here might be to dim your lights a little during the additive passes, then perform one final fullscreen pass to brighten them back up again. That loses some bits of precision and is a little old-fashioned, a more modern approach might be to use a floating point FBO (64-bit should suffice for most cases).
> 1 votes

---
Tags: opengl, lighting, blending
---


# Question
Title: Circle vs. Rect Collision accuracy problem
The blue ball is dynamic and is supposed to bounce off the walls, as well as the rectangle. Currently, the green rectangle is adding an invisible line to the scene, which doesn't let my ball go where I want it to. You can see the issue on the picture below and also see my source code.

Source code for dynamic circle vs. stationary rectangle collision:

```
public void collisionRect() {
                double dx = Math.abs(circle1.getLayoutX() - rect1.getLayoutX());
                double dy = Math.abs(circle1.getLayoutY() - rect1.getLayoutY());
                double rect1XRadius = rect1.getWidth() / 2;
                double rect1YRadius = rect1.getHeight() / 2;

                boolean xWalls = dx <= rect1XRadius;
                boolean yWalls = dy <= rect1YRadius;

                if (xWalls) { //if the ball hits any of the X walls
                    c1SpeedX = c1SpeedX * -1; //Invert direction of X
                }
                if (yWalls) { //if the ball hits any of the Y walls
                    c1SpeedY = c1SpeedY * -1; //Invert direction of Y
                }

            }

```

I don't understand where I've made a mistake and how I can make my code work. Source code examples will be greatly appreciated! Thanks.

# Answer
In order for the collison with the rectangle to happen, the object must be both inside its bounds in the x and the y dimension. Try only reversing the velocity only if both xWalls and yWalls is true. To tell which side it collides with, just choose the smallest of dx and dy. If dx is smallest, it collided with the x sides, if dy is smallest it collided with the y sides.
> 1 votes

---
Tags: java, 2d, collision-detection, physics
---


# Question
Title: How do I smooth out of the effects of a too-sensitive control?
I have a game that takes input from a joystick. If you tilt the joystick right, the ship moves right linearly according to how much the joystick is tilted. So if you tilt the joystick twice as much the ship tilts twice as much. This feels fine in cases when you want to bank the ship through a steep turn (ie. lots of tilt). But for small tilts, the controls feel far too sensitive. How do game devs flatten/smooth the effects of controls? Do I just take the log of the tilt? Mostly, I want to flatten things in the middle of the range of possible tilts.

# Answer
> 4 votes
A common approach is to raise the values coming from the joystick to a power, for instance squaring them, which improves the sensitivity for small deflections but still allows you to access the whole range of movement with large deflections.

Usually a joystick value comes to you in the \[-1, 1\] range. You'll want to preserve the sign when raising it to a power, so you'd do something like this:

```
if (joy > 0)
    joy = pow(joy, p);
else
    joy = -pow(-joy, p);

```

Here's an interactive graph where you can see how this function works when you adjust the value of `p`. As you can see, the curve flattens out in the middle, meaning that a given joystick deflection produces a smaller response.

# Answer
> 1 votes
Usually, a joystick axis goes from 0 to 1, with 0 being no movement and 1 being full movement. So if you are holding the left thumbstick halfway to the right, it would be 0.5f, and if you are holding it three quarters of the way to the left it would be -0.75f.

What I suggest is only registering movement if the value is bigger than some threshold. For example:

```
float minForce = 0.2f;

if (Math.Abs(Joystick.Thumbstick.Left.X) > minForce) {
    // Do Movement
}

```

---
Tags: mathematics, input
---


# Question
Title: Where does XNA 4.0 takes memory from to perform operations?
I found this question which talks around the question *I'm* interested in. In particular I focused on the line where the guys says that *GraphicsDevice object is literally a representation of the underlying graphics card*.

Now, can I assume that XNA automatically uses the memory directly from the underlying graphics card (to perform the most expensive calculations like updates and drawing)?

If so, is everything (like thread management) already optimized or there are way to configure the device depending my various cases? If not, do I have to tell the GraphicsDevice object whether to use or not the GPU memory rather than the CPU?

# Answer
All this stuff happens at DirectX level (or driver level). You don't have to worry about it. The engine will handle textures for you (like determining how much can be kept in video memory at any given time).

However, there's still room for optimizations or slowdowns based on bad strategies. For example, switching the active texture can be a costly operation. If you keep doing this over and over again (rather than using sprite batches for example), you can indeed slow down rendering.

Also keep in mind that you'll always have to go the way through system memory. There's no way for you to directly alter anything stored on the graphics card.

If you've got like 512 MB VRAM and you're using textures which got a total of 1 GB data, then data is copied as needed, i.e. you'll have the full 1 GB in RAM, but only a subset (whatever is used right now) as a copy in VRAM.
> 1 votes

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