# Question
Title: How to determine what animation to render in a component-based system without breaking encapsulation?
In a component based system, how should change the rendering/visual state of an entity such that I know what animation to use, without breaking encapsulation?

My guess is that it would have to be message-based system, not a query-based one, because having a few `if`s checked every frame to determine the right animation based on the values of the attributes of the other components doesn't sound very efficient.

# Answer
> 2 votes
The thing is, your animated *is* coupled to the state of the other components in the system. So there really isn't any problem with having your animation component knowing about, or even querying directly, relevant components that contain what kind of internal state you need to represent in an animation.

For basic movement stuff, usually what I do is set up some kind of observer pattern. Every frame I check the velocity vector of the object (in whatever component it's stored in) and use that to determine which movement based animation to play. For other oneoffs, I just have the components that handle them see if there is an animation component, and plays an appropriate animation from there.

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


# Question
Title: How do I implement real-time mesh deformation, with regards to environmental damage?
I would like to be able to add the following feature to my tech demo: at the moment bullets hit the walls, little pieces fly out of them, as well as decals appearing on the walls. Computing power is good enough, now, so that many games have destructible environments.

I would like bullets to shatter small surface segments off the wall, ideally the segments that fly off would directly relate to the hole that is left, though I don't even know if this is how it's done in commercial games.

How is this done? Are there simply a number of different meshes that are swapped out as, and when, objects are hit? I assumed that this would not be an accurate enough solution. Is real-time mesh deformation feasible. and if so, how is it done?

# Answer
There are two basic concepts:

1) Parallax mapping bullet holes (This is what Fear 1 used). It doesn't actually change any geometry, but due to shader magic it looks like there's a hole where you shot.

2) Actually breaking off chunks of geometry. The Unreal engine has something called the Fracture tool which helps author this content. I'm not sure how it works under the hood, but here's the documentation on how to use it: http://udn.epicgames.com/Three/FractureTool.html
> 2 votes

---
Tags: 3d-meshes
---


# Question
Title: What is the simplest method to generate smooth terrain for a 2d game?
What is the simplest method to generate smooth terrain for a 2d game like "Moon Buggy" or "Route 960"?

I got an answer at stackoverflow.com about generate an array of random heights and blur them later. Yes, it's quite okay. But it would be better to give some points, and get a smooth curve.

# Answer
> 14 votes
One way you could achieve this the following:

* Create a point in the middle of the screen, with a random height; you now have two sections, one on each side of this point
* For every section, divide into two placing a point in the middle of this section, with (ranged) random height between its two neighbours
* Repeat n times.

What happens is detail in the scenery gets finer with each iteration.

How you handle boundary cases is up to you: you could assume points at (0,height/2) and (width,height/2) for instance.

Hope this helps!

EDIT: Here is a picture I made for illustration:

This is the same idea!

# Answer
> 12 votes
Assuming that you want an actually smooth terrain, I'd suggest stepping back from the noise-based answers and understanding where they come from. A 'noise' signal is essentially a sum of infinitely many sinusoids of random amplitudes, with the 'average' amplitude at a given frequency given by a function of the frequency *f*. You can get most of the common 'noise' definitions this way. For instance, Brownian motion has a *1/f^2* frequency response (that is, the average amplitude at a given frequency is inversely proportional to the square of the frequency): this means that nearby points have a fair bit of correlation with each other, since the high-frequency components of the signal are heavily damped. By contrast, the classic fractal noise (midpoint displacement, Perlin noise, etc.) has a *1/f* frequency response; there's more variance between nearby points, but still quite a bit of correlation. Going a step further, white noise has a constant frequency response - there's no correlation at all between any points.

What good does this do you? Well, you can get a smooth signal that still has a bit of a noisy look to it by just summing a handful of sinusoids but making sure that they have an appropriate amplitude at any given frequencies. You want the frequencies to be 'random' so that no two of them will have a common multiple (otherwise you'll get a periodic component to the overall shape of your hills), so I'd suggest something like the following procedure (complete with working example):

1. Choose 4 (real) numbers at random in the range \[1..10\] - these will be the frequencies of your sine waves. I 'rolled the dice' at random.org and got: *f0* = 1.75, *f1* = 2.96, *f2* = 6.23, and *f3* = 8.07. There's nothing magical about the number 4 (you can use more, but using any fewer will start to make the individual sine waves more obvious) or the range 1 to 10 here (it'ss just a way of making sure that your highest and lowest frequencies aren't *too* far apart). It might make sense to choose one frequency in the range \[1..2\] and the rest in the range \[2..10\] just so that you have a known 'dominant' sinusoid.
2. For each of these four (or however many) frequencies *fi*, choose an amplitude *ai* somewhere in the range between *-C/fi* and *C/fi* for some constant *C*. The value you choose here controls the overall amplitude of your wave - for convenience's sake, I picked *C* = 1. Then I needed random numbers in the range \[-1/1.75 (= -0.571) .. 1/1.75 (=0.571)\], and similarly in the ranges \[-0.338 .. 0.338\], \[-0.161 .. 0.161\], and \[-0.124 .. 0.124\]. Rolling the dice four times again, I got *a0* = -0.143, *a1* = -0.180, *a2* = -0.012, and *a3* = 0.088 . (Note that this probably isn't quite the best way to do this step - since the maximum possible value of the function is the sum of amplitudes abs(*a0*) + abs(*a1*) + abs(*a2*) + abs(*a3*), it might make more sense to divide each of your four *ai* values by this sum once you've generated them, and then multiply each one by *C* so that you can be sure the precise maximum the function can attain is *C*.)
3. Pick four 'offsets' *oi*, each in the range \[0..2π\] (0..6.28) - these will tweak the starting points of your waves so that they don't all begin at 0. I got *o0* = 1.73, *o1* = 4.98, *o2* = 3.17, and *o3* = 4.63 .
4. 'Plot' the function *f(x)* = *a0* sin(*f0 ( k x + o0)*) + *a1* sin(*f0 ( k x + o1)*) + *a2* sin(*f0 ( k x + o0)*) + *a3* sin(*f0 ( k x + o0)*) - here *k* is another constant, one that controls the horizontal 'stretch' of your functions. You'll have to figure out what this is for your own application; for convenience I just picked *k* = 1, and so my overall function is *f(x)* = -0.143 sin(1.75 (*x* \+ 1.73)) - 0.180 sin(2.96 (*x*+4.98)) - 0.012 sin(6.23 (*x*+3.17)) + 0.088 sin(8.07 (*x*+4.63)).

Here's the result of my example run, as plotted in Wolfram Alpha - note that it fixes the size of its graphs for display purposes, but that you should have plenty of control over the horizontal and vertical stretch of the result via the constants I mentioned above:

# Answer
> 10 votes
The midpoint displacement algorithm can generate beautiful 2d terrain.

There is subtle different between midpoint displacement and what @tykel is suggesting. Tykel's algorithm subdivides the horizon and picks a new height. This creates terrain where the peaks are uniformly spaced. Humans are great at picking out regularities, so the generate terrain will seem generated, not natural.

Midpoint's power comes from picking the midpoint then displacing along the *normal* of the that line. This causes the peaks to vary up and down as well as side to side. The resultant terrain is fractal, and humans perceive fractals as natural.

Random height displacement could result in a descent terrain if you threw in a couple more parameters (horizontal displacement, maximum slope, etc). This highlights another of MPD strengths; it is very simple to tune. Two parameters, bumpiness and level of detail.

# Answer
> 7 votes
You can use *noise* functions to generate random heights. The simplest of them is value noise, which works exactly like your description: you generate some random integer heights, and then *interpolate* heights between them. The most-often used interpolation method is cubic S-curve mapping:

Suppose you have height `h0` at point `x0` and height `h1` at point `x1`. Then to obtain height at any point `x` (`x0<=x<=x1`), you use

```
t = (x-x0)/(x1-x0); // map to [0,1] range
t = t*t*(3 - 2*t); // map to cubic S-shaped curve
h = h0+t*h1;

```

Heights obtained in this way will be smooth, random, but not really interesting. To make your terrain better, you can use *fractal noise*. It works like this: suppose you have generated a function `h(x)` that returns height at a given coordinate (using the method above). This function has a frequency, determined by frequency of original interger heights. To make a fractal out of it, you combine together functions with several frequencies:

```
fbm(x)=h(x) + 0.5*h(2*x) + 0.25*h(4*x) + 0.125*h(8*x);

```

In this example, I combine four frequencies - original, double, 4-times and 8-times original, with higher frequencies given less weight. Theoretically, fractals go all the way to infinity, but in practice only a few terms are required. The `fbm` in the formula stands for fractional Brownian motion - this is the name of this function.

This is a powerful technique. You can play with frequency multiplier, with weights of different frequencies, or add some functions to distort noise. For example, to get more "ridged" feel, `h(x)` can be changed to `1-abs(h(x))` (assuming `-1<=h(x)<=1`)

However, while all this is nice, this technique has a serious limitation. With a "heightline" based approach, you can never have terrain "overhangs". And I imagine them to be a very nice feature to have in a "Moon Buggy"-like game.

Adding nice overhangs is a difficult task. One thing that I can think of - you can start with a fractal "heightline", and "tessellate" it into a series of splines or bezier curves. Then the terrain line will be defined by several "key points". Apply some jitter to these key points - this will result in random deformation of the terrain, probably forming some interesting shapes. However, terrain self-intersections might become a problem with this approach, especially with high jitter amounts.

# Answer
> 4 votes
There are two popular methods for generating terrain height maps.

Some answers given here are already based on the Diamond-square algorithm, but knowing the name makes it easier to search for more information. Perlin noise has other uses as well, so it's good to check it anyway.

# Answer
> 1 votes
My idea would be to create a smoothed noise function. First with a method intNoise(int) which return a "random" int, but wich depends on the input. If you use the same input twice, the result will be the same.

Then use a smoothing method to make a floatNoise(float) which uses the two integers around the input to build a random value.

Then use the X position as the input and the Y as the output. The result will be a smoothed curve but with random height.

---
Tags: algorithm, procedural-generation, terrain
---


title: Ocean waves / ripples

text:
# Question
Title: Ocean waves / ripples
Any suggestions for creating ocean waves / ripples as seen in the pictures here:

http://www.pocket-lint.com/news-gallery/42042/crimson-steam-pirates-ipad-review/10#image

and video here:

http://www.youtube.com/watch?v=AtrZX3e4AL8

I was thinking of setting a background repeating tile. Then making some kind of noise tile which would mostly transparent and moving this in sections across the background tile.

Any improvements or further suggestions on this?

Cheers

# Answer
A different approach to your idea...

Make a large tile that will be the static portion of the water and cut the highlights out of it by making them transparent. Then put a brighter texture with higher frequency underneath the static ocean and scroll it slowly. To not make it very repetative you can also try to scroll with some Lissajous curve.

You can optimize the performance if the cutouts can be fully transparent. Then you can draw the top layer first with depth write and then the back layer with depth test.

I'm thinking of other ideas...
> 0 votes

---
Tags: 2d, art
---


# Question
Title: most efficient Bounding Sphere vs Ray collision algorithms
Is there a known 'most efficient' algorithm for Sphere vs Ray collision detection?

I recently stumbled accross Arvo's AABB vs Sphere collision algorithm, and I am wondering if there is a similarly noteworthy algorithm for this.

One must have condition for this algorithms is that I need to have the option of querying the result for the distance from the ray's origin to the point of collision. Although if there is another, faster algorithm which does not return distance, then in addition to posting one that does, also posting that algorithm would be very helpful indeed.

Please also state what the function's return argument is, and how you use it to return distance or a 'no-collision' case. For example, does it have an out parameter for the distance as well as a bool return value? or does it simply return a float with the distance, vs a value of -1 for no collision?

# Answer
Given a sphere with centre at point `C` with radius `r` and a ray starting at point `A` with direction vector `d`.

First check if the vector `CA` is shorter than `r`, if so `A` lies within the sphere and there is definitely a collision.

Second compute the dot product of `CA` and `d`, if it is negative `A` is "behind" the sphere and there may be a collision, otherwise there is no collision unless `A` is within the sphere.

The key to this problem is to find the minimum length from the sphere centre to the line. Project the vector `CA` onto `d`, subtract the result from `CA`, this gives you `v`, the shortest vector from `C` to the line going through `A` with direction `d`. If `v` is shorter than `r`, there is a collision.

You can find two points where the line intersect the sphere using Pythagoras, `C` \+ `v` +- `d` * sqrt(`r`^2 - |`v`|^2).

Edit:
And for the record, this is as good as it gets, everything is done using simple vector maths, it requires a limited number of basic arithmetic functions, and there are only a few branches.

Edit:
`CA` is the vector from `C` to `A`, computed as `A` \- `C`.

In quick pseudocode, you'd do something like:

```
//input
vector A
vector d
vector C
float r
//end of input

vector collisionPoint
vector v
vector CA = A-C
float rSquared = r*r
float vSquared
if(dotProduct(CA,CA) <= rSquared){
    collisionPoint = A
}
else if(dotProduct(CA,d) <= 0){
    v = CA - projection(CA,d)
    vSquared = dotProduct(v,v)
    if(vSquared <= rSquared){
        collisionPoint = C + v - multiply(normalize(d),squareRoot(rSquared-vSquared))
    }
    else{
        collisionPoint = none
    }
}
else{
    collisionPoint = none
}

```

You could code up all the functions yourself, but it may be handy to use a vector library, note that while `A` and `C` are points I have declared them as vectors in the code as it is common not to differentiate between point and vectors in code. This code finds the point closest to `A` where the ray and the sphere collide. If you are interested in the furthest point that will be `C + v + multiply(normalize(d),squareRoot(rSquared-vSquared))`.
> 5 votes

---
Tags: c++, collision-detection
---


# Question
Title: Determine the cut sections of a polygonal mesh
I have a polygonal mesh, defined by vertices $V$, edges $E$ and face $F$. One can view this as a real life 3D terrain.

I want to obtain cut sections of this terrain, defined by vertical cut planes. What are the algorithms I can use to determine the cut sections of the terrain in an efficient manner? The cut section here is just a polyline that are the intersection lines between the cut section vertical plan and the polygonal mesh.

Edit: Since my elevation map is a mesh, this means that I know every information associated to a vertex, face and edge, e.g, which faces are connected to which edge.Is it possible to leverage this information in order to speed up the cut section further?

# Answer
Since you have just an elevation map you can start by projecting everything on a 2D plane. So your elevation map will become 2D net and the cutting planes will become cutting lines. After finding all the intersecting points in 2D you can unproject them back to 3D points. This will dramatically simplify the algorithms and the processing time.

* To project in 2D plane you can just ignore the Z component
* You can use a line segment intersection algorithm to find the points.
* You can first make a fast check if both vertices of a given edge are on the same side of a cutting line then the edge doesn't have a cutting point.
* If your cutting planes/lines create a concave shape/polygon then you need to extend this previous early out check to and make sure that at least one vertex is on the "inside" side of each line.
* If your cutting planes/lines don't create concave shape/polygon then you should first split them to segments and do only segment/segment intersection checks.
* Once you have all the intersected edges and their intersection points to find your polyline you should traverse the faces by following the shared edges. (be careful if the faces can be convex, in such case they can have more then 2 intersected edges).
* Unproject the polyline in 3D. To unproject a point you can use the ratio of the distances to the two vertices of the line segment that the point belongs to. In 2D and 3D the ratio should be the same.
> 1 votes

---
Tags: computational-geometry
---


# Question
Title: Is HTML5 and Canvas good for rapid prototyping of games?
Are there frameworks and processes for HTMl5 that can be used for the rapid prototyping of 2D games?

# Answer
I built http://gamejs.org partly for this purpose. It follows the PyGame API which I know is sometimes used for prototyping.

I would argue that JavaScript lends itself very well to writing game code quickly; for a more elaborate argument to this effect see Capitalizing on JavaScript's prototypal inheritance

Other advantages if you stay with simple technologies, like html5 & js:

* every computer has an interpreter and a debugger for JS installed (even mobile devices)
* easy to pickup for newcomers
* well documented language, still evolving
* open technologies through & through

Whether html5 is more suitable than, say, Flash or even pen&paper depends on your game and how evolved your concept is.
> 6 votes

# Answer
I've been using PixieEngine. It's a web based game development IDE that lets you develop and publish games without having to download or set up a development environment.

The advantages over plain HTML Canvas and JavaScript are that CoffeeScript is a very syntax light language, and the built in libraries optimize specifically for the prototyping of games.

For example in HTML Canvas when you want to fill a circle you need to call:

```
context.fillStyle = color
context.beginPath()
context.arc(x, y, radius, 0, Math.TAU, true)
context.closePath()
context.fill()

```

But the PixieEngine canvas wrapper provides a simple method

```
canvas.fillCircle(x, y, radius, color)

```

HTML Canvas and JavaScript are good for rapid game prototyping, but PixieEngine is much better.
> 4 votes

# Answer
Well, a cursory Google search produces several results:

I don't know anything about them specifically, but I would think that in general HTML5 is probably a decent way to prototype games even without a framework or engine: quick, direct, low overhead and easy to iterate on.
> 3 votes

# Answer
Yes! I'm part of the 2 man team that builds Construct 2, the HTML5 game creator.

Our tool is popular for building full games and also amongst an audience who wish to rapidly prototype games and ideas.

When creating a prototype anything that can save you time is beneficial and we've worked hard to make Construct 2 a powerful time saving device as well. Results can be created in minutes.
> 3 votes

---
Tags: html5, prototyping
---


# Question
Title: How to learn game graphic design for non artist?
> **Possible Duplicate:**
> Graphics for non-Graphics Designers

I'm more into the technical aspects of a game like programming, mechanics and algorithms.

I'm no artist but I like to make games independently and I'm finding it hard to make graphics for my games. Is there anything that I could do to recuperate with this?

# Answer
I think it depend on what kind of graphics you are looking for. People usually go with pixelart in indie development.

If you are looking for this kind of graphics I would recommend going to deviantart.com and searching "pixelart" or "game pixelart". It will spits out countless game sprites. Download some of them and study them at 300% zoom. Some people say its good to read some books but I would say practice makes perfect. So try some of these:

Pixelart is not THAT time consuming. But if you are looking for some better/complex graphics. I would say choose if you want to be a coder or a designer. Making game assets is very time consuming, and it will make your progress much slower. I would recommend hiring someone OR if you don't have enough money but you have the enthusiasm. Find somebody who shares the enthusiasm and start a small "indie studio" and cooperate.
> 4 votes

# Answer
The best I can say is to read some books about art, and practice using your art programs alot. Apart from that, if you aren't an artist, there isn't much you can do but hire someone else to create your graphics. :)

Here is a website dedicated to giving good tutorials about cg:

http://www.cgtutorials.com/
> 1 votes

# Answer
Common way to 'cheat' is to use '8-bit' pixel art with with modern effects (transparency, transformations, blending) or abstract art.

For example:

* Minecraft - 3d block-based 'voxel' graphics.
* Radiant - 'pixels' that can rotate + glow effects and particles.
* Geodefence - simple shape-based art, some alpha blending, optimized particles and shaders.
> 1 votes

---
Tags: art
---


title: Creating slot reels

text:
# Question
Title: Creating slot reels
Is there any automated way to calculate the slot machine reels icons based on the LIMITS:

* # of reels
* # of lines
* % that is returned to player
* Include free spin icon or not
* Include bonus game or not

I am only looking for an automated way, as there is already a post about manual calculation per case Here

Also note, that I don't explicitly set how many different icons there can be (banana/cherry, bar, 7, etc), this is free for the algorithm to decide.

**Edit:** seems like my question was not understood.

A simple example, in a 3x1 slots machine (only one line of icons on the end result) would be this:

Input:

* 3 reels
* 1 line
* 50%
* no
* no

Logic:

* Randomly start with the minimum type of different icons, ie 5
* randomly construct a reel of size 10(all reels have to be the same for the game to be fair)
* Calculate chance of each icon type appearing (easy, just examine all 10\*10\*10 routes for this example)
* Ad hoc start with a base 1.000 points payout
* Each icon will have a payout value of it's probability * 1.000 * 0,50

PROBLEM SOLVED (in this simpler case). I'm looking for a more general solution, thats all

# Answer
There are a lot more variables in play then you have listed as both the free spins and bonus games will also have their own set of probabilities and payouts pending of the scope of the games.

Most (if not not all) casino slot machines will have weightings associated with how often symbols 'land' on the win lines so it is possible to calculate the icon order on the reels and the symbol probabilities based on the first four limits you have listed although more information is needed about the payouts and winning combinations. I just don't think there is an off the shelf solution so you have to model it yourself.

The last two limits will need more information as the percentage payout will change based on the game mechanics and weightings of the free spin and bonus games.

The gambling industry hires mathematicians to model games on slot machines as bonus games and even free spin games can be wildly different from one game to another.
> 1 votes

# Answer
I think you may have misunderstood something in the related question.

This is a problem of probability and everything that was previously stated directly applies. It's only "manual" in as much as he's using constants. You would merely replace those constants with whatever variables you're using.

Part of that is knowing how many possible icons there are. For example, you wouldn't expect a machine with reels of two icons to have the same probability of success as a reel with seven icons. You would have to calculate how many possible icons they have first then calculate the spin as was explained in the previous question.
> 0 votes

---
Tags: game-mechanics
---


title: Game Programming Junior Demo Design

text:
# Question
Title: Game Programming Junior Demo Design
Consider the following demo:

http://www.ashereinhorn.com/post/11140243390/short-capture-from-the-last-xna-version-direct3d

(It has now almost been converted to C++ and DirecX10, and so the code is not important here, it's the substance I'm interested in)

Basically the little agents move around killing each other, their states are displayed in a corner and you can select one so as to see the items it can see, it's field of view and the things it is holding in memory.

I showed it to someone that works in the industry and they said I should focus on tracking a single agent and make what's going on more clear - so maybe animate each state with simple animations or model swapping to make it more obvious when they are searching / in combat / running away. The other thing they said I should change was the fact that the agents simply disappear when killed, and reappear when spawned because again, it's not clear what's happeneing. As a result I'm going to implement a simple particle system so that agents 'shatter' when killed and possibly reassemble when spawned.

My question is, are there any really obvious changes that I should make to this demo with a view to getting my first game programming job? If you work or know about the industry, is there anything that jumps out at you that should be included? Or is bad? or good for that matter?

Are there any things that would particularly impress or grab your attention in a game demo?

Thank you very much for any help you can give!

**EDIT** \- The walls are actually solid in the C++ version

# Answer
> 1 votes
Off topic, I really like your CV and portfolio presentation so thumbs up on that.

In regards to the video, I agree with the advice that has been given to you so far. Make the agents so that they are recognisable from each other (e.g. make them a different colour). When they change state, do something like add a Metal Gear style '!' appear above their head when they are shooting and maybe a running man icon when they are running to make it more obvious what is going on.

If you have any write up on how it all works, that would be good to read/show if possible.

Do you have any other scenarios for the agents? Eg 2 v 2?

Do you have any other demos like the one that was made for the award shown on your CV?

---
Tags: game-design, game-industry, jobs, demo
---


# Question
Title: What are different methods for managing data that is stored in the main loop and must be used by other systems?
This could probably belong on Stackoverflow but I'm not sure.

I want to change some variables that are in my game loop from different classes, this is probably a simple question with something i'm overlooking but I can't think how to do it easily.

The only way I can think to do is pass a pointer to whatever class I want to change it in, but that seems stupid as if I want to do something else it means passing another pointer.

Any ideas to help me?

# Answer
> 2 votes
You could pass in the pointer, you could make a pointer global that you could access (or make it a singleton), you could set up an event system that changes those variables when those events get called, you could have your main loop query the objects that it owns to see what the variables should be... there are a lot of ways of doing this but without more specifics it seems like a really rudimentary programming question.

# Answer
> 1 votes
I will often create a class specifically made for global data, just because I love having the ease of use, it still keeps my code clean, and namely I have a lot of global data in some projects. I have a large component and entity based system though, so creating an entity and adding components for managing global data is a trivial task. As someone else stated though, it seems like an incomplete question with many varied solutions.

**If you're** not already using a system that I described though, I recommend just making the pointer global.

EDIT: And you're right, this answer is probably slightly better suited for Stack Overflow, though I didn't mind answering it.

# Answer
> 0 votes
Having a class change external data that is just in a loop is not good program design. if you're using classes, that data should be in its own class. If instances of other classes need access to that data, then you need to associate the 2 objects in some way, usually by passing in a reference, or by having a mediator class that communicates for you, or perhaps by some sort of messaging system. But generally speaking classes shouldn't be changing data outside of that class, they should be calling methods on other classes who change their own data.

---
Tags: c++
---


# Question
Title: Programming a game onto multiple platforms
I just had a pretty good idea for a mobile game and I'm having a little trouble selecting what tools or languages to use for the job.

I have experience with flash and AS3 and I know I can put that onto mobile devices via Adobe Air. What I found kind of frustrating was that I have 5 games on my Samsung galaxy tablet and they all look like they were made in flash, but they didn't use Air. The only game that required Air on my tablet was my game that I made in flash. Anyways, how do you guys think/know they are programmed?

A simple game like angry birds... is that programmed in pure java or something or do they use some kind of engine. I've heard of Unity and it looks pretty cool, but now I just found ShiVa and that also looks pretty sick. I'm trying to make a Castle Crashers type game. Side scrolling/2D type of thing. Thanks in advance

# Answer
> 3 votes
Without knowing which specific platforms you intend to support, I'm going to go out on a limb and say that Unity is probably the easiest and most turnkey solution for getting on a lot of platforms.

Other games (like angry birds) are probably a hand rolled collection of libraries (e.g. Box2D) and custom code, and they probably do the porting from one platform to another themselves.

# Answer
> 0 votes
Unity is the easiest platform for such, though I strongly suggest learning (if not known) java, as most (including angry birds) android apps are programmed in Java. In fact I may go out on a limb and say **probably** more than 90% are since it's the recommended and only (last i checked) officially supported by android language/platform to use. And it's a great language to have experience under your belt with, and even awesome for practical use.

Although as previously stated, we don't know what mobile platform you're trying to support, so it's a pretty open question. For your specific game there are plenty of options, I would NOT go with Unity (personally) because it wasn't originally made for 2D in the first place. I would go with Java or even Flash on this one. There are plenty of articles online about side-scroller development. Worry less about what and more about how though, Java has awesome implementations of networking and tons of libraries that you could use for your features. However, on the down side it would require lots of android specific code for controls and things. Which also has the con of a huge learning experience and the experience itself for future projects.

# Answer
> 0 votes
Unity3D has already been suggested and is an amazing tool.

Another option would be MonoGame (an open source implementation of XNA). This might be a bit more advanced then developing for Unity3D, but a good option if you are going for a 2D game (MonoGame is 2D only) and looking to learn something new. There are a lot of tutorials and documentation on the net to help with XNA development, likewise with Unity3D.

---
Tags: cross-platform, mobile
---


# Question
Title: How can I generate my puzzle game's result tables?
I have a pattern game and it is almost done however I am stuck on the last part.

I have a screen with 25 blocks (in a table format 5x5) and the user clicks on it to turn over the blocks, I need to see if the user has turned over a line of blocks.

So I created a bunch of options and I am trying to compare it to the table of the current system (1 = not turned over and 0 = turned over). But the problem is my table looks like

```
local level1o1 ={ 0,0,0,0,0,
                  0,1,1,1,1,
                  1,1,0,1,0,
                  1,1,1,1,1,
                  1,0,1,1,1 }

```

And when I do the compare it doesn't say it is the same because of the other random 0's in the table. I don't want to make every single possible result table, so any ideas of how I could do this?

Compare function

```
-- Table Compare
local function deepcompare(t1,t2,ignore_mt)
    local ty1 = type(t1)
    local ty2 = type(t2)
    if ty1 ~= ty2 then return false end
    -- non-table types can be directly compared
    if ty1 ~= 'table' and ty2 ~= 'table' then return t1 == t2 end
    -- as well as tables which have the metamethod __eq
    local mt = getmetatable(t1)
    if not ignore_mt and mt and mt.__eq then return t1 == t2 end
    for k1,v1 in pairs(t1) do
        local v2 = t2[k1]
        if v2 == nil or not deepcompare(v1,v2) then return false end
    end
    for k2,v2 in pairs(t2) do
        local v1 = t1[k2]
        if v1 == nil or not deepcompare(v1,v2) then return false end
    end
    return true
end

```

Example list of possible answers

```
local level1o1 ={ 0,0,0,0,0,
                  1,1,1,1,1,
                 1,1,1,1,1,
                 1,1,1,1,1,
                 1,1,1,1,1 }

local level1o2 ={ 0,1,1,1,1,
                 1,0,1,1,1,
                 1,1,0,1,1,
                 1,1,1,0,1,
                 1,1,1,1,0 }

.. etc

```

# Answer
> 0 votes
Considering your table is a 5x5 table, and you search for complete lines, I guess there is only 12 results to compare with (considering the 2 diagonals).

That doesn't sound that long and hard to create all of them by hand.

Then it's straightforward to compare the 12 tables one by one with your current table to see if you can find the 0 (from result table) scheme matching your current game table.

---

To be more precise, here is **one of the possible methods** you could use (and the easiest that come into my mind);

1. Select the first result table (of 12) and set a "completeLineFlag" to **false**.
2. Parse the selected result table and each time you find a 0, use the current table index to verify if you can find a 0 at the exact same index of your current game table.
    * If you can find it then change the flag to **true** and keep going on
    * If you can't find the required 0 then stop the parsing of the current result table and set the flag to **false**.
3. At that point you finished to test the selected result table; if you found all the parsed 0 of the result table you should get the flag set to "true", but if any of the required 0 wasn't there you should get the flag set to "false".
4. Now, if the flag is **true** you know that the **complete line** you just tested is in your current game table, whereas if the flag is **false**, you can return to point **1** with the next result table until you find a good one or until you tested them all.

---
Tags: algorithm, procedural-generation, lua
---


# Question
Title: Cocos2d Composition using CCSpriteBatchNode
I'm making a game in objective-c using cocos2d. I have the following:

```
@interface Player : CCNode
{
    CCSprite *mySprite;
    CCSpriteBatchNode *sceneSpriteBatchNode;
    //...
}
@property (nonatomic,retain) CCSprite *mySprite;
- (id)initWithSpriteBatch:(CCSpriteBatchNode *)_spn;
-(void)updateStateWithDeltaTime:(ccTime)deltaTime andListOfGameObjects:(CCArray*)listOfGameObjects;
@end

@implementation Player
- (id)initWithSpriteBatch:(CCSpriteBatchNode *)_spn
{
    self = [super init];
    if (self) {
        sceneSpriteBatchNode = _spn;
        mySprite = [CCSprite spriteWithSpriteFrameName:@"player_image.png"];
        [_spn addChild:mySprite];
    }
    return self;
}
//....
@end

```

Now in the layer I would do:

```
//...
Player *player = [[Player alloc] initWithSpriteBatch:sceneSpriteBatchNode];
[player release];

-(void) update:(ccTime)deltaTime
{
    CCArray *listOfGameObjects = [sceneSpriteBatchNode children];
    for (CCNode *tempChar in listOfGameObjects) {
        [tempChar updateStateWithDeltaTime:deltaTime andListOfGameObjects:listOfGameObjects];
    }
}

```

However, you can only add CCSprite to the spritebatchnode, that way I can't update my custom classes. What do I have to do?

# Answer
I think you have a flaw in your architecture there. The Player should not be a subclass of `CCNode` (or any cocos2d node class for that matter).

The `CCNode` is only the visual representation of your player-character, therefore your Player class should have a `CCNode` as member (or property as it's called in Objective-C). This makes your architecture much more flexible. You could implement a component-based architecture, where your node is part of a "VisualComponent", or you could have an inheritance-based architecture where you inherit from a "GameEntity" base-class etc. But inheriting from `CCNode` is a bad idea and will definitely hurt you in the long run.

**Update:** As requested in the comments, here's a short guide how you could refactor your code using a Player class that inherits from `NSObject` and implements a GameEntity Protocol. For a more complete documentation of protocols, read the Objective-C docs.

Protocols are much like interfaces known from other programming-languages. A very simple protocol could look like this:

```
#import "cocos2d.h"

/**
 Protocol for a game entity
 */
@protocol GameEntityProtocol<NSObject>

/** Visual representation of the entity */
@property(assign) CCNode* node;

/** Update method */
-(void) update:(ccTime)dt;
@end

```

Your Player class could then be implemented like this:

```
#import "GameEntityProtocol.h"

// Player interface
@interface Player : NSObject<GameEntityProtocol>
{
    // player related members
}
@end

// Player implementation
@implementation Player

@synthesize node;

-(void) dealloc
{
    [self setNode: nil];
    [super dealloc];
}

-(void) update:(ccTime)dt
{
    // do something.. update node position etc.
}
@end

```

And finally in your "Level" or "Game-World" you would have something like the following (note that you could also move the initialization of the player-node to the players init method, but it's easier to keep everything "outside" so you could read stuff from a data-file etc.):

```
// in your init method or where you load the level
// entities is a class member of type NSMutableArray*
entities = [NSMutableArray arrayWithCapacity: 4];
Player *player = [[Player alloc] init];
[player setNode:[CCSprite spriteWithSpriteFrameName:@"player_image.png"]];
[sceneSpriteBatchNode addChild: player.node];
[entities addObject:player];

// update loop could look like this
-(void) update:(ccTime)deltaTime
{
    for (id<GameEntityProtocol> entity in entities) {
        [entity update:deltaTime];
    }
}

```
> 2 votes

# Answer
you can add any class inherited from of `CCNode` as a child of another `CCNode` instance.

player is a inherited from `CCNode` and CCLayer is also inherited from `CCNode`, so there is no need for a `CCSpriteBatchNode` instance in there, you can directly add player instance to your layer!

```
-(void) update:(ccTime)deltaTime
{
    CCArray *listOfGameObjects = [sceneSpriteBatchNode children];
    for (CCNode *tempChar in listOfGameObjects) {
        [tempChar updateStateWithDeltaTime:deltaTime andListOfGameObjects:listOfGameObjects];
    }
    [self addChild:player];
}

```

`CCSpriteBatchNode` provides better performance only to render multiple sprites with *same texture*, so if player does not use same texture as other objects in the scene you can't use an sprite batch! but you can define player class to inherit `CCSprite` instead of `CCNode`. this way you can attach it to the existing `sceneSpriteBatchNode` object.
> 0 votes

---
Tags: cocos2d-iphone, cocos2d, component-based, objective-c
---


title: Optional samplers in shaders

text:
# Question
Title: Optional samplers in shaders
I have a scene. Sometimes I draw untextured, coloured, semi-transparent triangles, sometimes I texture them, and I draw a lot of both in a fairly interleaved manner.

In a fixed function pipeline the difference would be if I had set the `GL_TEXTURE_2D` to be 0 or a texture handle. My codebase is being migrated from FFP to OpenGLES 2, so these bindings to 0 already exist everywhere they are needed. My ambition is for my generic OpenGL code to run on both OpenGL 1.x and OpenGLES 2. So I'm looking for shaders that are a cut-down FFP imitation.

How can an OpenGLES 2 shader know if the `Sampler2D` is set to 0 or has a valid texture?

My reasoning is that an if-statement that all fragments take the same branch is much cheaper than switching program pretty much every other statement as I alternate between textured ops and fixed-colour ops.

If I add a uniform then I have to go visit my code and each time I bind a texture I'll have to add a call to set the uniform flag. I have a large codebase that I have to ensure I am strictly setting it appropriately.

If I introduce a opaque white 1x1 texture this is like the uniform - I have to go everywhere in the code base ensuring I am binding it instead of binding to 0 to get colour-only primatives.

So I'd much prefer an approach where the sampler is interrogated in a shader. Is this possible?

# Answer
> 4 votes
Testing for the sampler in the fragment shader is going to make either a useless test or a useless texture lookup for each fragment being rendered. There is really no reason to do that.

A really nicer method is to **bind a program using a specific fragment shader** when you want to render flat triangles:

```
precision highp float;
uniform vec4 u_FixedColor;
void main()
{
    gl_FragColor = u_FixedColor;
}

```

---
Tags: glsl, opengl-es2
---


# Question
Title: Orientation while rotating around a point
I am using this formula to rotate around a point.

```
X := originX + sin(angle)*Size;
Y := originY + cos(angle)*Size;

```

In cartesian cordinates how would I keep the objects orientation in relation to the origin object as it moves around the origin. Any one know where I could look for answer to that?

# Answer
> 1 votes
I am sorry I think I have found my own answer I just plugged in to

rotate at the same rate locally as I am globally for the sattelites if that makes any

sense. So if my angle = 3.6 here than

```
X := originX + sin(angle)*Size;
Y := originY + cos(angle)*Size;

```

Than I just needed to

```
this.rotate(3.6);

```

So you just rotate on the satellite objects at the same rate as the local object and that will keep your satellites facing the same direction as when the rotation started.

---
Tags: javascript
---


title: How does Halo draw projectiles?

text:
# Question
Title: How does Halo draw projectiles?
I am trying to draw projectiles and doing billboarding. A projectile consists of a bill-boarded "particle" and a "tracer". When I billboard a projectile, it cannot be seen when the player's viewing direction is parallel to the projectile axis.

How does Halo or other games solve this problem, so that projectiles can be seen from behind.

# Answer
> 7 votes
I'll take a stab.

First, it looks like there is a very low-poly mesh used for the actual bullet. It's textured with a partially transparent texture. It's rendered far more brightly than other things in the scene. The texture may even be animated.

The 'tracer' may be a simple texture that is not normal billboarding. I think if you rotated this tracer about its local z axis such that it faced the camera that you'd resolve your issue with your billboarding technique. A look-at algorithm may be able to achieve this.

# Answer
> 3 votes
Solution- make your projectile 3D rather than 2D.

---
Tags: opengl, first-person-shooter
---


title: Problem displaying model

text:
# Question
Title: Problem displaying model
I downloaded the FBX of this free model:

http://www.turbosquid.com/FullPreview/Index.cfm/ID/485548

Yet when i try and display it in my project

```
foreach (ModelMesh mesh in player.Meshes)
{
    foreach (BasicEffect beffect in mesh.Effects)
    {
        beffect.View = view;
        beffect.Projection = projection;
        beffect.EnableDefaultLighting();
    }
    mesh.Draw();
}

```

I end up with the teeth of the model way out from the body, and the eyes expanded so large they stick out the sides of the model.

Could someone tell me what i am doing wrong? Or is the model the issue?

# Answer
> 3 votes
Try to set World matrix to BasicEffect, this drawing code should work:

```
Matrix baseWorld = Matrix.CreateScale(1) * Matrix.CreateRotationX(0) * Matrix.CreateTranslation(new Vector3(0,0,0));
Matrix[] modelTransforms=new Matrix[player.Bones.Count];
player.CopyAbsoluteBoneTransformsTo(modelTransforms);

foreach (ModelMesh mesh in player.Meshes)
{
    Matrix localWorld = modelTransforms[mesh.ParentBone.Index] * baseWorld;
    foreach (BasicEffect beffect in mesh.Effects)
    {
        beffect.View = view;
        beffect.Projection = projection;
        beffect.World = localWorld;
        beffect.EnableDefaultLighting();
    }
    mesh.Draw();
}

```

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


# Question
Title: are there any alternatives to developing android apps other than with eclipse
Ever since I installed the android sdk and avd manager in eclipse for java developers, it's been pretty simple to create apps for the mobile device. The only issue I have is eclipse is way too slow for comfort. Sometimes it takes up to a minute to do simple things like opening up a java class file.

Are there any faster ways to utilize the android sdk/avd manager plugins in some alternative IDE that is stable?

# Answer
> 7 votes
You may have a problem with your eclipse setup and perhaps being more specific on the error would help. For instance, there is a known bug with Eclipse Helios autocomplete being very slow with the Android SDK. Do you have the latest dev tools and eclipse plugin?

To answer the question, Netbrains' IntelliJ IDEA has android support and there is a plugin for NetBeans that allows android development also. For C++ code this can even be done in Visual Studio (see most upvoted answer here) as well as C# in Visual Studio with MonoDroid.

I will choose to ignore your comment on notepad and the command prompt and for the sake of completeness list some other tools:

You do not need to use a graphical tool at all in order to develop an Android project. Google provides help for Managing Projects from the Command Line which requires use of adb and Apache Ant. Software can be developed using any IDE or text editor. Personally I use Vim, but Emacs has an Android development minor mode that provides nice key bindings for working with the Android SDK.

For additional information see the StackOverflow questions here and here.

# Answer
> 1 votes
Eclipse shouldn't be that slow, you may have some thing wrong. Anyways to answer you question there is IntelliJ IDEA. I use it for web development and find that it is better at project management than Eclipse one you get used to it.

JetBrains has things such as auto complete down to a science compared to either Eclipse or Visual Studio.

---
Tags: java, android, mobile, ide, eclipse
---


# Question
Title: How should I implement side-scrolling level design?
I'm working on a college project using the educational Java framework Greenfoot, and as stated above we're making an r-type clone.

I've been looking at using an array of strings to populate the levels. The array contains 60 strings, filling the Y axis, each element in the array represents a y co-ordinate += 10. I use "0" to represent empty space, "1" to represent a block of terrain.

Then I use a for loop and charAt() method to create a new array representing each column along the X axis, and populate the screen this way.

I thought I was being clever by making a "block" class that checked to see if it was connected to any other blocks and adjust it's image accordingly to make the terrain look as if it's a single block/shape. However, this is now slowing down the game to a crawl as there are so many objects in it.

I've tried to add the columns as the game is scrolling and removing them once they leave the screen, but I end up with gaps in the terrain.

How are levels in these types of game normally implemented? Would I be better creating a few big objects to make the terrain and build the whole level from start to finish?

Is there some method I've completely missed?

Here is a screen shot of how it looks at the minute, each block is 22 x 10 pixels.

# Answer
Looking at your picture, is that Greenfoot? If it is, then most tips for how it's usually done in other games won't really apply very well.

I've actually created a little sidescrolling platformer (think Mario) on Greenfoot before (to help a friend) and I must say that Greenfoot made everything a lot more complicated than it would be in XNA for instance. Not to mention slower - even as simple as it was, it didn't take too much for the framerate to take a hit.

And I only had one or two dozen platforms and a few enemies and bullets.

Now in your case, where every single tile is an object added to the game world... yikes! Maybe if you implement some intelligent culling for pieces that are outside of view, but still, I just don't think Greenfoot was created with this type of game in mind. It's much more oriented toward smaller, board-sized, experiments.

So my recommendation would be to indeed try to create the levels out of larger pieces, as big as they possible can be, in order to reduce the number of objects to a minimum. That's what I did on the platformer - I probably had between 20-30 pieces in the entire level, and performance was tolerable.
> 2 votes

# Answer
In my mind, there are 2 things related to terrian that you should concern:

* Object-terrain collision detection
* Terrain rendering

In your data representation, object-terrain collision should be done in constant time. You can start from the coordinate of object (player), and check the blocks it overlaps. Please check if you have the right algorithm. It should not cause any performance issue.

For rendring part, I didn't fully understand your description:

> I then use a for loop and charAt() method to create a new array representing each column along the X axis, and populate the screen this way. I thought I was being clever by making a "block" class that checked to see if it was connected to any other blocks and adjust it's image accordingly to make the terrain look as if it's a single block/shape.

I have several questions:

* Did you render each block every frame? (I thought the answer is yes)
* Did you check the string with `charAt()` every frame?
* Did you check the connectivity every frame?

The good answer will be: No, no, no.

Rendering a image to buffer is slow, especially on software renderer (Java doesn't use hardware renderer on a lot of platforms). Anyway, we can do some optimization to minimize the number of draw call.

For example, assuming your window size is 660x480. Your block size is 22x10, so you will have about 30\*48=1440 blocks on your screen.

* You can precalculate a "column" of terrian image. For example, when a column appears, you can calculate the connectivity of the column, draw the image of the column (the size should be 22x480). You will only need to render 48 images each frame.
* Moreover, you can apply a "sliding window" technique. Create a buffer 1 column wider than your window (686\*480). Render all visible columns on the buffer that might be visible. Whenever a column disappears, "slide" the buffer by 22 pixels. You will only need render 1 big image per frame (in amortized).

Last suggestion: Do profiling before and optimization. You can start from some simple test, such as "don't render terrains" and see if FPS is really improved.
> 5 votes

# Answer
I know nothing of this "greenfoot", but with many tile-based games, if you have a way to render to a different buffer (that isn't limited by any specific size), you can get away with rendering your entire world only ONE time to the separate buffer. (Because the world in tile-based games usually never changes, only where you're looking at it from)

You could then just grab your current screen from this larger buffer during your rendering. This can often be a HUGE optimization. Especially for something like yours where you need to calculate where lines are drawn.

Alternatively, if you can't render to a different buffer, you could store the information of which blocks are drawing which lines. For example if you had a character array representing the tiles in your map, you could have another array of the same size storing which lines they would draw, and store the information bitwise.

```
#define TOP_LINE     0x0001
#define BOTTOM_LINE  0x0010
#define RIGHT_LINE   0x0100
#define LEFT_LINE    0x1000

// Then for each cell
// (assuming CellData[height][width] and CellLineData[height][width])
if( NeedsToDrawTopLine(CellData[i][j]) )    CellLineData[i][j] |= TOP_LINE;
if( NeedsToDrawBottomLine(CellData[i][j]) ) CellLineData[i][j] |= BOTTOM_LINE;
if( NeedsToDrawRightLine(CellData[i][j]) )  CellLineData[i][j] |= RIGHT_LINE;
if( NeedsToDrawLeftLine(CellData[i][j]) )   CellLineData[i][j] |= LEFT_LINE;

```

With just these four bits, there are only 16 possible types of cell/lines combos, so you could store them all, and then your render loop could just draw these exact shapes based on the values within CellLineData. That way you can avoid saying something like "Does this cell have a left and right line?" and just instead say "Draw shape 14", etc.

And then for physics, assuming you're going for simple tilemap physics, you only need to store a big binary array, and in your physics checks, you'll (hopefully) only have to check in the exact cells around your character's position.

Also, if you're looking for a simple tool for basic tilemap level design, I recommend checking out Tiled Map Editor. It is really simple to use, and can export a CSV file (comma seperated values) which you can parse EXTREMELY easily to load in your levels.

Pardon if any of my math/code is wrong, it's pretty late. Just trying to help. Best of luck
> 1 votes

# Answer
I recommend that you simply add data to your Block class that decides where to render it out, you should only EVER have to calculate the relationship between blocks being connected to other blocks one time. If more, it's only because it has been modified, and at that point you should decide where it is, so that you only have to test that block, and not all of them.

I would have a method that will setup which blocks have a border in enum, or 4 boolean values in some sort of structure, that show which do. Populate the data only once, right after loading the map.
> 0 votes

# Answer
If you only use '1' to represent terrain and '0' to represent empty space why not use boolean arrays instead of strings/string arrays this will probably help a bit and might be a quick fix. Although I don't think this is really the way to do it, authoring a level will become really hard like this.

I suggest you just use a 2 color bitmap. This would make for easy level creation and finding out if a piece of space is empty or not would be just checking the color at that specific coordinate.
> 0 votes

---
Tags: architecture, java, side-scroller
---


# Question
Title: What do the components of gl_TexCoord[0] mean?
What are the differences between `gl_TexCoord[0].s, gl_TexCoord[0].t gl_TexCoord[0].p` and `gl_TexCoord[0].x, gl_TexCoord[0].y gl_TexCoord[0].z` ?

I understand that `gl_TexCoord[0].x, gl_TexCoord[0].y gl_TexCoord[0].z` are pixel coordinates?

But what do `gl_TexCoord[0].s, gl_TexCoord[0].t gl_TexCoord[0].p` mean and where must I use them?

# Answer
> 15 votes
The difference is only **semantic**. Any GLSL vector can be accessed using `x/y/z/w`, `r/g/b/a` or `s/t/p/q`. Typical use is:

* `xyzw` for **space coordinates**
* `rgba` for **colours**
* `stpq` for **texture coordinates**
* if none of the above applies, any flavour can be used, but when it could be confusing, `var[0]/var[1]/var[2]/var[3]` can be used instead.

You can mix them in expressions: `foo.x = bar.q`, or even `foo.xy = bar.gb + baz.st;`. The major restriction is that swizzling can only be done using letters of the same group, *ie.* `foo.xya` is **invalid** because it mixes `xy` from `xyzw` and `a` from `rgba`.

---
Tags: shaders, opengl-es, glsl
---


# Question
Title: Rendering characters, with cut off limbs (Blender models in Java/OpenGL)
What aspects should I take into consideration for creating character animation and rendering classes if I want to be able to have detachable limbs? I've developed a detailed body system that can have everything down to the nervous system defined. I'm aiming for something similar to the level of damage detail found in Dwarf Fortress. For example, when a character takes damage to their upper arm, there is a chance of nerve damage that can disable the entire arm. Or they could lose the arm entirely.

I have a system written up for handling the data part of this. Each character has a trunk, which has appendages and internal parts. Each appendage can also have child appendages and internal parts. Child appendages are disabled/removed if a parent appendage is disabled/removed. If any of the disabled/removed appendages or internal parts are required for life, the character will soon die.

What I'm working on now is the drawing/animation portion of this. How do I define animations to know which ones are allowed given the current state of the body (missing arms/legs and so on)? How do I set up the drawing system to not draw missing limbs? Does each limb/appendage have to be its own model (I'd like to draw cut off appendages on the ground)?

The simple system I'm transitioning from (I just wrote it for testing) imports all the key frames of an animation as full models into a VBO (along with vertex counts for where key frames start/stop). It doesn't import or utilize the bones defined in Blender, and it doesn't interpolate between frames.

This is likely a pretty big question, so I'm also looking for resources that can get me where I need to go.

EDIT

I ask about the animation knowing which limbs it's animating because I would like to have it set up to perform an alternate animation if a required limb is missing. After thinking about that, I imagine I would perform that check before activating an animation, and activate the appropriate animation at that time.

# Answer
I'm currently working on a similar system. Procedural animation + dismemberment etc.

**How do I define animations to know which ones are allowed give the current state of the body (missing arms/legs and so on)?**

I don't quite follow this bit, if the limbs aren't there, then who cares if it's being animated or not, because it can't be seen.

**Does each limb/appendage have to be its own model (I'd like to draw cut off appendages on the ground)?**

I dynamically build these from using vertex bone weights. The quality is probably slightly lower than doing every limb by hand, but it's less effort once I've done it once, because I can then apply it to every model.

With the sane approach from the following section, yes, each limb would have it's own model.

I'd likely have a complete model on hand of the entire entity, and each of the limbs cut up.

**How do I set up the drawing system to not draw missing limbs?**

2 major choices, the simplest way is to simply draw the limbs separately, and where the limbs join have additional faces that are normally hidden with "raw flesh" textures that will be seen when the limbs are removed.

The second choice is to do it dynamically on the fly, this will only work with relatively simple models. The approach is to take the base model, and find the vertices that are weighted to the limb you wanted to dismember. Remove those vertices, noting what they connect to such that you know the open section. You then dynamically close over the open section with triangles with a "raw flesh" texture. From the perspective of a sane software developer, this approach isn't a good one (run time model deformation), and less "flat" performance characteristics, but I kinda like it.

While the first method will generate many more draw calls, it's also a bit more approachable.

I'm personally going with the second, with relative success, but all my models are very low poly, so dynamically cutting up a model and re uploading the VBO within the frame is doable for now.

**It doesn't import or utilize the bones defined in Blender, and it doesn't interpolate between frames.**

This makes it really hard to do dismemberment in a procedural way, because how do you know what vertices belong to what joint? Vertex bone weights and dismemberment go hand in hand so nicely I suggest you to rethink this bit.

I also suggest you invest in interpolation. Without it you can't speed up/slow down your animations, and you're coupled with the framerate. This means you'll be able to get less out of your animations. e.g. you can't slow the walk animation when someone is coming to a stop etc.
> 7 votes

# Answer
Your best option is to cut off the limbs and use multiple submodels depending of the current state of the wounds. Your approach of using a VBO per keyframe is just overkill; use a skeletal animation system and play different animations depending of the damage received (limping with one leg, crawling without the two legs, etc).

Valve published a good set of slides about the wounds and dismembering in L4D2. I really like the approach of using a model for the organs and bones, and clipping the "skin" model based on texture projections of cuts, gunshots, etc.
> 5 votes

---
Tags: opengl, java, animation, blender
---


# Question
Title: How do I find the point of impact with 2D per-pixel collision detection?
I'm creating a platformer and have implemented per-pixel collision detection. However, this has caused 2 obstacles that I've yet to figure out. The first obstacle, which this question is about, is that I don't know how to efficiently find the point of impact (my other problem will probably be a different question on this StackExchange).

I have my character fall or jump at a given rate in pixels. That is, every frame the character might fall 4 pixels or jump 4 pixels, for instance. If the character falls and intersects an object then the character should land on that object (and vice versa, if they're jumping and hit an object they should start falling again). However, if, for instance, a character falls 4 pixels and this puts them 3 pixels into an object, they'll stop falling but won't be in the proper location. The character should appear to stop at the first pixel of impact.

So, how can I efficiently find the point of impact? I only have a vague idea of only comparing the outline pixels, testing for collision, and incrementing them up or down by one until there's a collision, but it seems like it might be complicated to pull off.

If you want to know the platform, I'm developing using XNA for Windows Phone 7.

# Answer
I've read a really good article before that described how collision detection was implemented in earlier Sonic games.

That article would have been an excellent reference for this thread, but I just can't seem to find it at the moment. If I do I'll update my post. Meanwhile I'll try to take it from memory!

I believe this technique is very interesting and might solve your problems, without needing to change to a physics engine nor let go of per-pixel collision entirely.

Basically what the article described was a tile-based platformer engine where each tile *type* had per-pixel collision data like this:

**But** your character only had a limited set of points of contact. For instance in the article I remember there being only 3 pixels near sonic's head (one on the left of the sprite, one in the middle and one on the right) that would be used for collision detection when jumping, 3 pixels near sonic's feet to detect collisions with the floor, and 2 near the middle on each side to detect collisions with walls.

I'll just do a quick mock up of what I recall. Something like (don't rely on the accuracy of my pixel placement, I just made them up):

This way you only need to check for collision using these individual points (which ones depend on the situation, such as jumping or falling) and in case of collision you only need to adjust the sprite based on those points. For instance if one of the upper points collided with some blocked pixel in the ceiling tile, you only needed to bring the sprite down until that spot no longer collided.

**Edit**

While this is still not the link I originally read, it also mentions the collision points (named *sensors*) and should give a great deal of information. Read the other sections of the guide too!

http://info.sonicretro.org/SPG:Solid\_Tiles
> 5 votes

# Answer
First of all, I wouldn't go for pixel perfect collision detection in a mobile 2D platform game for obvious performance reasons. These kind of checks are CPU intensive and, unless you perform a broad check to filter separated objects, it'll surely negatively affect your game.

I'd use bounding boxes and/or spheres (depending on your entities shapes). The detection quality would be good enough. You could even use more than one shape to model an entity. Tests between those shapes are easy and you can know points of impact and fix entities positions.

But, if you don't want to implement everything youself, you might want to use Box2DX (C# port of Box2D) and use only the collision detection part of the library.
> 2 votes

---
Tags: collision-detection, efficiency
---


# Question
Title: What happens when I implement IUpdateable or IDrawable in XNA?
I've been fooling around with XNA today, attempting to develop a pure-component model game engine.

I've been working on a GraphicsSubsystem class, and realized that it will need both an Update method (to update the individual graphics components, e.g. animated sprites), and a Draw method (it'll be the only Subsystem with a draw method).

My original plan had been to simply add a "GraphicsSub.Draw()" line in the main game's Draw method, and a "GraphicsSub.Update()" line in the main game's Update method. Totally valid, works fine.

However, I've discovered that XNA has two interfaces, "IUpdateable" and "IDrawable" that seem like they might be designed for exactly that, and that they'd provide a better framework for achieving this functionality compared to my simple method calls.

**When I implement IUpdateable or IDrawable, what am I telling the XNA.Game to actually do?**

Is it as simple as being included in the `base.update()` and `base.draw()` during the main game's `Draw()` and `Update()` calls?

# Answer
> 7 votes
**TL;DR**

Just implementing IUpdateable or IDrawable will do nothing.

Instead have GraphicsSubsystem *inherit* from the DrawableGameComponent class, and override the virtual Update and Draw methods. Then all you have to do is create your GraphicsSubsystem object and register it using Components.Add(objectName) on the Game class.

If you wanted to do the same thing using those interfaces, you'd actually need to implement *IGameComponent, IUpdateable and IDrawable*, which is exactly what DrawableGameComponent already does. And of course you'd still need to register the class on Components for it to do anything.

**Long Answer**

Just implementing an interface does nothing other than guarantee your class will have a certain set of methods/properties/events (and be compatible with anything that expects that interface).

XNA has a components system where you register a component at the start of your game, and the Initialize/Update/Draw methods will be automatically called back for you, along with a series of other functionalities (such as controlling the update order or hiding components).

This system is related to three basic interfaces that you should know: IGameComponent, IDrawable, IUpdateable.

You can create your own class and implement from any/all of these interfaces and this is what they do basically:

* IGameComponent - Has an Initialize method and has the added catch that you can only add a class to Components if it implements this interface.
* IUpdateable - Has an Update method. If an IGameComponent *also* implements this method, *then* Update will be called for you automatically.
* IDrawable - Same as IUpdateable but for the Draw method.

But since it would be troublesome to implement these interfaces everytime, XNA already provides two implementations which you can just inherrit from and they're ready to go. They are:

* GameComponent - This one implements both IGameComponent and IUpdateable but *not* IDrawable. Use this for components that have no visual representation.
* DrawableGameComponent - Inherits from GameComponent and implements IDrawable on top of it. Use this for components that have a visual representation.

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


# Question
Title: What kind of environment is expected in elevated, hot areas?
I'm creating an "exploration" game where the overworld map will be randomly generated. The biomes are generated using the data given by a "temperature map" , a "humidity map", and an elevation map for instance : cold + humidity = snow, hot + humidity = jungle, etc The problem I'm left with is how to deal with elevated zones in hot climate. Right now it is set to the "bare" biome (the gray areas in the following pic), which I guess is supposed to mean "deserted dry land". On the other hand, elevated zones with colder temperatures is set to snow (in white), which is ok. So, how should I deal with the elevated zones in cold climate? I have several ideas but I feel that none of them works: 1) set it to snow as well, but I think it would feel weird 2) set it to "bare" but I don't think it actually exists IRL or that i'd have any interesting gameplay perspectives

# Answer
I travelled in a lot of "hot" countries in the 10 last years and each time I went to elevated areas it was cold or very cold even when I was close to the equator.

In fact elevated areas are semi-arid to arid. Vegetation is small (except some special species like cactus) and burned (by sun and cold). Most of the time, there is very little snow except at mountaintops. So it depends what "elevated" exactly means. Because indeed, when you go down the valley temperature goes higher and vegetation goes taller.

It's cold, but it doesn't look like a cold place in North America or Europe with snow etc. it's more like a kind of desert mapped on a mountain.

---

Let's take as example Bolivia. The north of the country is in the Amazon basin and the average temperature is 30°C (86°F) with jungle etc. So it's definitely a "hot" country when the altitude is near sea level.

But the south of the country is on the Altiplano, one of the most extensive areas of high plateau on Earth (altitude from 3500 to 6500 meters). The average temperature varies from 3°C to 12°C, which is cold.

And it looks like this:

In order to avoid a too-big answer, I will link other photos instead of displaying them directly: Uyuni area 4, Uyuni area 5, Uyuni area 6, Uyuni area 7, Uyuni area 8, Uyuni area 9, Uyuni area 10, Uyuni area 11, and so on ... (Sorry I didn't clean my pics)

All of these photos were taken at an average altitude of 5000 meters, and the white on ground is salt or sulfur not snow. As I said, it might look like hot desert area but it's very cold. At lower altitude (around 3000 meters) there is much more vegetation.

I hope I answered your question. If you need more examples well tell it ;)
> 16 votes

# Answer
Honestly the only elevated hot things I can really think of are volcanoes. I find this question interesting because I'm also using a temperature and humidity biome structure for my game :\]. Another thing, is that if you're game is fantasy adventure, you could have something special there, not just a volcano but I mean tons of things.

The native ancients of central America (Mayans, etc.) believed that they needed to build a monumental massive staircase on the highest mountain to get closer to god, these people are also quite famous for living in hot areas in central America. A similar if not equivalent "biome" could work too.

Another suggestion is to have a more realistic area which is actually probably more what you were looking for. I live in Utah and if you got down mid-south and lower, you get Moab, Canyonlands, Capitol Reef, Zion, etc. They're extremely mountainious areas that are actually pretty high up. I mean compared to the regular desert stuff. Here's some shots of Goblin valley to let you know what I mean:

Valley with some mounds

A mountain

Down in goblin valley area (those formations on the ground are about 7-11 feet tall)

Valley showing what you see A LOT (you can easily see the other mountains in the background because Utah is like that)

EDIT: Sorry forgot to note. As far as temperature goes it gets damn near melting skin during the middle of the day, just a few hours later it's tolerable but when it gets night time (9pm-5am -ish) you better have a coat. I think this probably your best bet on making the biome work realistically.
> 4 votes

---
Tags: maps, procedural-generation
---


# Question
Title: Graphics Pipeline, how exactly it works and how graphics card interprets it?
I've looked at this Wikipedia's link, http://en.wikipedia.org/wiki/Graphics\_pipeline, but the article lacks in-depth explanation.

The only thing, I suppose, I understand and can expand upon, is, Texture part:

* Apply bump map
* Apply specular map
* Apply displacement map
* Apply texture map
* In between apply any other maps(?)

What interests me in the answer, is, what happens with the model on every frame rendered, like:

1. Application launched, requests a 3d model (OpenGL/D3D)
2. OpenGL/D3D calls hardware for help
3. Polygons get loaded into graphics card memory,
4. Something gets done, blah, blah
5. The Texture part comes in (the upper list), loading every texture in memory card memory texture that needs to be applied to the mesh.
6. Maybe something more?
7. Display to monitor or send out to operating systems display interface?

In short: OS -\> Application -\> OS -\> Hardware -\> OS -\> Display device.

My examples are just what I understand/can make out of all this. But I'm looking for an answer that goes well in depth on graphics pipeline.

Would like to know how AAA tools like CryEngine, UDK does graphics rendering, where we have all the dynamic lightning and stuff like that.

I'd be more than thankful with answer that contains an example of, for instance, what does the character model (CryEngine/UDK) has to go through to get rendered in full fashion, with approximate included memory consumption/hardware instruction called, like:

* Load polygons \[OpenGL issues command, hardware instruction, memory used, possibly GPU usage?\]
* Next function \[OGL, HW, Memory, GPU\]

And, what are the best practices for graphics pipeline?

P.S. Please correct me if that's not Graphics Pipeline I'm referring to.

Thanks in advance!

# Answer
> 13 votes
In my opinion you're asking for information on a topic that is so broad and extensive - a topic for which entire books (or a great part of many books) have been written - that it might be extremely difficult to try and summarize everything in a concise fashion. This is just much more likely the subject of an entire article, chapter, or book, than something that could be easily written out as an answer.

I can also tell that your understanding of the topic is *very* hazy, even on the parts you claim to understand. For instance, most *maps* that you mention are not just textures that are applied by the graphics cards! In fact they're usually nothing more than data (of any kind) encoded in image format in order to be used in computations further down the pipeline (e.g. in the pixel shader).

This data may range from storing the surface normals at each pixel of the scene, to the coefficient of specularity, motion vectors, pretty much anything.

So my recommendation would be to take the long trip, and turn to the bibliography. In particular I'd recommend Real-Time Rendering 3rd Edition as the flagship of all graphic programming books in order to provide a real in depth coverage of this and many other related topics.

Well, but I guess could try to give a basic overview of the pipeline. But think of it as watching the earth from space. You can get a grasp of the shape of the continents, how there's oceans, etc. But if you need a more detailed view, you'll need to come down and do a lot of exploring on your own.

---

**Summary of the Graphics Pipeline**

The graphics pipeline is a name given to the entire process that relies on hardware and software to transform the representation of some 3D scene into a 2D image that you can see on the screen.

It can be roughly divided into three big stages:

* The Application Stage
* The Geometry Stage
* The Rasterizer Stage

Taking the following as input/output:

* Input - The Application Stage takes as input a 3D scene, which is in rough terms just a collection of data. This data takes the forms of geometry (which is usually made up of triangles), light sources, textures, camera, etc. Geometry is usually organized in a very specific way, for instance as a list of triangles.
* Output - The output of the Rasterizer Stage is the image you see on screen.

**Stage Description**

**1)** The `Application Stage` is everything that happens in your side of the application, before and up to actually submitting the scene to the graphics hardware. This might include things such as collision detection as animation for instance.

**2)** The `Geometry Stage` has many, many subphases, but they're mostly all concerned with the manipulation and transformation of the data you submitted. It's responsible for taking your initial scene representation and apply a series of calculations that will end up *describing* the final 2D image. For instance it needs to:

* Apply world transformations in order to place your objects properly in the scene
* Apply view transformation in order to render from the point of view of your camera
* Calculate how much light is reaches each point in your scene which is a very intricate process relying on a lot of different variables
* Transform your 3D coordinates onto the 2D screen plane usually by applying a perspective projection
* Trim out (or clip) everything that ended up being outside of your screen
* Adapt the 2D representation of the scene to your screen's actual resolution

In sum, the Geometry Stage takes care of per-vertex operations.

**3)** Finally, the `Rasterizer Stage` is a bit like a painter. It takes the (2D) description of your scene that was generated by the Geometry Stage, and starts filling it with color, pixel (or fragment) by pixel. It also takes care of applying any textures, and deals with the sorting of what you see (look up z-buffer).

In sum, the Rasterizer Stage takes care of per-pixel operations.

---

And I guess that's the best I can describe it. I might have ended up being inaccurate on a point or two, but this is my current understanding of the usual 3D graphics pipeline. Feel free to edit in any corrections.

---
Tags: 3d, graphics, pipeline
---


# Question
Title: Creating a rotation offset based on camera position with XNA
I have an XNA project where characters have the ability to pick up and move objects around (in 3d). When an object is picked up by a character, I want ithe objects position to always be out in front of the character (as if the character was holding it in their arms). I'm having trouble creating the offest using the charactors forward vector. The main issue is that I don't know how to properly incorporate the characters rotation into the objects position. I'm hoping somebody can give me an example of how to accomplish this to help point me in the right direction. Thanks!

Currently I'm just matching the held object's world matrix with the characters as a work around:

```
grabbedSceneObject.World = Matrix.CreateScale(20F) * Matrix.CreateTranslation(viewPosition);

```

# Answer
A simplified version would be:

```
if(objectGrabbed)
{
    grabbedSceneObject.World = grabbingCharacterWorld;
    grabbedSceneObject.Translation += grabbedSceneObject.Forward * distanceInFontOfCharacter;//possibly offset the vertical height as well
}

```
> 1 votes

# Answer
It's important to know what sort of forward vector you're talking about. If you're using Vector3.Forward directly that's simply a unit vector looking down the Z axis. Let's suppose your 3D model is designed such that its also facing that direction by default.

In order to get the real forward direction of your character you'll need to tranform it using the character's rotation first. For instance if your character can only rotate around the Y axis (i.e. has a Yaw property), you can get the character's current forward vector like this:

```
Vector3 characterForward = Vector3.Transform(Vector3.Forward, Matrix.CreateRotationY(character.Yaw));

```

Once you have that and you'd like to offset the object's position in front of your character, simply do something like:

```
grabbedSceneneObject.World = Matrix.CreateTranslation(character.Position + characterForward * horizontalDistance + Vector3.Up * verticalDistance);

```

Where *horizontalDistance* and *verticalDistance* are floats controlling the offset in world units from the character's origin. You may also add the scaling operation as in your example before the translation.

And you might also want to change the object's rotation so that it remains fixed in relation to the character when being grabbed. For that try adding a rotation matrix before the translation with a magnitute of character.Yaw degrees or character.Yaw + 90 degrees or whatever fits your need.
> 0 votes

---
Tags: xna, camera, rotation
---


# Question
Title: How do you do AI path following within a 2d physics engine like farseer/box2d?
I'm in the process of moving a 2d top down game I've been working on into a proper rigid body physics engine like Farseer. Up until now, I had just hacked together my own physics code where needed.

I'm trying to learn the proper way of doing things here.

What is the proper way to make your AI follow a set path once you have made them rigid bodies inside of the physics engine?

If I have a path of navigation nodes on my map that I need the AI to follow, previously I would just move them along the path manually by calculating the next position they should be at for the next time step and manually setting them to that position.

But now they are rigid bodies and subject to collisions and any forces that may hit them and knock them off path.

So to make the AI move I believe I should now be applying impulses/forces to them? I should no longer be manually setting their position each frame.

So I think I need to go from a deterministic world where I force the AI to strictly follow a path to a non-deterministic world where they could get knocked about in any direction if hit and I simply nudge them towards the next node in the path to make them move.

Is that right? Is that how other people do it?

This raises some questions about how to then avoid your AI getting stuck on corners of scenery now that they aren't walking a precise path, how do you guys handle that type of thing?

Or is it better to somehow mix the two and still have your AI follow a fixed path by setting their position manually, and only react to other forces under certain circumstances you can easily control?

Thanks for any advice guys.

# Answer
> 7 votes
Steering behaviors work very well in combination with a physics-engine, as they are usually implemented in a way that they return a "steering force" which can then be applied to your physics-body.

To make a unit follow a path, you could use *Seek* to go from path-node to path-node (make sure to avoid overshoot) and then use *Arrival* at the last node in your path.

As for your concerns about getting stuck: Modelling the path-following using forces should actually be quite accurate. You're right that an object might get thrown off the path if it collides with another object, but since you'll calculate a steering-force in every update, the object should be on track again in no time. If the deviation from the path after a collision can potentially be huge, then I suggest you remember your last position whenever a collision occurs and then steer the object back to that last position before continuing the normal route.

# Answer
> 0 votes
I'd say you're on the right track, you might want to look at this article.

It explains some basic collision avoidance and path-finding using the A\* algorithm.

Edit:

If you really only need what the best way of propelling your objects in the right direction is, then you should use a force (say, MovementForce or something) pointing in the direction of the best path you found using the path-finding algorithm of your choice

# Answer
> 0 votes
Judging by what @davidluzgouveia commented on annonymously's post, I'll bring up my project. Path following and path finding are very different though. Path finding is more of what annonymously was posting about, and for path finding I would look into Dijkstra's algorithm. For path following I use my choice physics engine entirely. The way I have it set up is that each location a unit class walks to, is set up in it's pathing subclass via 2D offsets, yes they are 2D and not 3D this is because of the way I have my physics set up in my game.

**3D explaination:** Each unit has only one main collider that is exclusively set up for collision with the terrain and world objects. It's a capsule shape and has a radius, and height programatically speaking. It's built at the center of the model and should extend just past the front and top of the model. But I also have a surface offset for how far it is off the ground at all times, and a float of how much it's allowed to slide down before bouncing up slightly, at a time. This sounds like I'm applying some sort of screwed up fix for a terrain collision problem, but I have my reasons.

Anyways, you should apply force to this capsule object, and it should remain hovering above the ground at all times. That's not to say it can't go any higher, just that it can't go any lower. The reason why it needs to hover (in my case) is because in a rigid body and ragdoll physics engine, the legs of my units are procedurally animated. So by applying a simple force to the capsule, the legs of my entity will reposition themselves on their own. They will also have their separate gravity applications! What this does is allows that if my character is on a slant, one foot can be at a lower elevation than the other.

This is exactly how you should do it. Judging by what you're asking that is. If you want to leave out some features, that's obviously fine, especially if it's an RTS or FPS and no one will ever see units feet or care anyways. But in general, the unit should have one MAIN collision object that works with movement of the character almost exclusively.

**Specifically 2D:** You still should have a main point, or just some sort of reference, for the engine to push around that is for the movement of a unit. You could give each unit a pathing subclass that has a few locations it needs to go, you could specify it in the level code, (e.g. location1(x,y) location2(x,y) etc.) the best way (I don't know what kind of game you're working on) would probably be to specify locations in the level and have that each unit will process them in order specified by the level and after it reaches each location, have it replace it's desired location with the next one it needs to get to.

There are tons of ways you could modify that, like having a list of locations in the first place for each unit, since this would mean not all units have to go to the same locations. However, as the same way, you could do this in the level code as well ( unit1.location1(x,y) unit1.location2(x,y) grunt.l1(x,y) knight.loc3(x,y) whatever)

Just a few ideas! I suggest you read the 3D version even though it's far less relevant.

EDIT: I decided to just supply both for anyone who might read this (Yea that's true).... (I originally only skimmed your question and didn't realize it was pretty 2D specific till I reread it \>.\>)

---
Tags: xna, physics, box2d, path-finding, farseer-physics-engine
---


# Question
Title: What rendering techniques would I use to draw a drop shadow effect for cards in a card game?
What type of shading algorithm might be used to create shadows like these?

the one I'm making is similar but it is all done with a 2D drawing API powered by OpenGL so there is no Z coordinate.

In addition, for the hand itself, I'd really like to get a shaded feel like seen here:

I'm just not sure how to achieve a shaded look close to that.

The number of cards is bound to change and the cards get thrown onto the table so I can't use any type of light map of sorts.

What sorts of algorithms should I look into (aside from blur which I know 'll need to do?)

Thanks

## Update

I'm making a 2D card game. I want to add dropshadows offset from the cards, a bit like:

The way I'm thinking of doing it is:

* Keep a texture that is the same size as the backbuffer.
* Draw dark rectangles as makeshift cards to that texture.
* Blur that texture.
* Draw my cards to that texture.
* Do additional lighting on the cards.
* Draw this texture to the backbuffer.

My questions are:

* Is this the right way to do this?
* Is there a way to do it without render to texture (keeping a bitmap
as big as the backbuffer)?
* Is it safe to assume that the maximum texture size will not be
exceeded by the backbuffer size? (What I mean is, if the backbuffer
is 2000x3000, then is it safe to say that I can create a texture in
video memory of that size?

Thanks

# Answer
I think everybody's giving way too complicated solutions to this problem..

So first, we have the card (or whatever you want to draw), depicted here by (a). Next, we take a copy of it, fill it in black and run a gaussian blur on it (b). All of this happens in photoshop or whatever your favorite art tool is.

Next, in-game, when we want to draw the card, first draw the blurred black image with multiplicative (or alpha) blend, offset in some direction a bit, and then draw the card on top of that. Voilá.

For further trickery, you can alternate between shadow and card render to get effect like (d), or first draw all shadows and then the cards, like in (e) (I colored the cards in the (e) case to show that they're still separate =)

It's also best not to use pure black (or full alpha) for the shadow to create more subtle, transparent shadows.
> 19 votes

# Answer
The first one isn't too hard. If you render an alpha channel for your hand of cards (which could be as simple as black for a pixel with a card in it, and white for transparent), you can perform any kind of blur you want on just the alpha channel, and then offset it and use that to control the lighting of the table. (Presumably, if you don't have a Z-buffer, you'd have to first render out the alpha channel offscreen somewhere, then do the table with the mask, *then* render the actual cards.)

The second one looks a bit like SSAO (screen-space ambient occlusion). That technique requires a Z coordinate. However, if you don't have the varying angles between cards (which is what I would guess if you have no Z-buffer), you can probably do a pretty good approximation by rendering a drop shadow (like the first one) for each card. The performance could be a little tricky, though—every plane would need a blurred alpha channel for all the planes above it, and if there are a bunch of cards on the table, that could be quite a few rendering passes.
> 2 votes

# Answer
Could you not do a shadow map? Render the scene to a fbo. Save only the depth values and do the normal depth value check in the shader to see if a shadow should be rendered or not.
> 0 votes

# Answer
The following process doesn't require an off-screen render target. However, in so doing, it gains the requirement that the table be drawn *first*. Or at least, nothing is drawn on the pixels that the table will cover before the table is drawn. It also requires that the table itself be one, single, non-overlapping piece: an image.

Also, your framebuffer needs an alpha component.

1. Get a greyscale image of a card. Make it fuzzy around the edges, possibly expanding its size. This is your shadow card image. Note that this is a single-channel image. When you access this texture in your shader, you should make sure that you put the single value in the alpha component. This can be done in your shader or somewhere else.

A value of 0.0 in the image means that there is no shadow. A value of 1.0 in the image means *total shadow*. That is, completely pitch black. You probably want a value of 0.5 or so as your darkest color.
2. Clear the screen such that the alpha is set to **zero**.
3. Before rendering *anything* (or at least anything that will be rendered "under" the table), for each card, render the fuzzy texture, offset from the actual position of the card (but with the same orientation). The color output by the shader should be The blend configuration for this should be (in OpenGL parlance):

```
glBlendEquation(GL_MAX);

```

This blend mode is used to keep overlapping shadows from growing ever darker or lighter. It simply takes the darkest value written to that pixel. It should look good enough.

You should also use the color write mask to turn off color writes.
4. Render the table. When doing so The blending should be set up as follows:

```
glBlendEquation(GL_ADD);
glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ZERO);

```

If the restrictions are too restrictive for you, then you have to use a render target. This is done as follows:

1. Create the shadow card image as before.
2. First, render the shadows. Bind the shadow framebuffer (which only needs to be a single-channel image, if your hardware can render to one of those). Clear its value to zero.
3. For each card, render the shadow card image, offset as before. Your shader should write the same value to all four components of the output color. The blend mode again should be `glBlendEquation(GL_MAX)`.
4. Switch back to the regular framebuffer. Draw everything you want to be shadowed.
5. Now draw a full-screen quad with shadow image we rendered. The shader should store the texel fetched from the shadow image in the alpha of the output; the RGB is irrelevant. The blend mode should be:

```
glBlendEquation(GL_ADD);
glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);

```
> 0 votes

# Answer
I'd use the stencil buffer. Clear it to 1 (preferably at the same time as you clear depth), draw your table. Then enable stencil test, draw the shadows using a blurry rectangle texture, incrementing if stencil and depth pass, doing nothing if stencil fail, nothing if depth fail, and set your stencil func to GL\_EQUAL (ref 1, mask 0xff), disable stencil test. (I haven't fully tested this but it's derived from code that does similar and should work fine; you *may* need to tweak the params). Then draw everything else.

The calls would be:

```
glEnable (GL_STENCIL_TEST);
glStencilFunc (GL_EQUAL, 1, 2);
glStencilOp (GL_KEEP, GL_KEEP, GL_INCR);

// draw shadow textures

glDisable (GL_STENCIL_TEST);

```

The only time this may cause trouble is if you have two blurred edges that overlap slightly; otherwise it needs nothing fancy beyond what basic OpenGL 1.1 offers and will work on all hardware (expect perhaps old 3DFX cards, which I assume you're not really worried about supporting...)

A second alternative, that should work very well in a non-performance-critical game, is glCopyTexSubImage2D. That will work with a texture smaller than the backbuffer too and is also supported well on all hardware (it's part of OpenGL 1.1 and Doom 3 used it, so you can expect support to be very good).

The basic setup would go like this:

* Clear colour to black.
* Disable depth writing (although this method doesn't need a depth buffer, so you can ignore that part as you're not using one).
* Set a viewport the same dimensions as your texture.
* Draw cards as white filled geometry.
* glCopyTexSubImage2D to your texture.
* Switch viewport back to full window size.
* Draw table as normal.
* Draw texture as a fullscreen blended quad, using a shader to blur it and invert colour.
* Draw everything else.

That should also work very well, it's a little more GPU intensive than the stencil buffer method but handles the overlapping case correctly and - like I said - I think a game like your one will have GPU power to burn, even on a low-end card.
> 0 votes

---
Tags: algorithm, shaders, shadows, fragment-shader
---