# Question
Title: Drawing large 2D sidescroller level terrain
I'm a relatively good programmer but now that it comes to add some basic levels to my 2D game I'm kinda stuck.

What I want to do: An acceptable, large (8000 * 1000 pixels) "green hills" test level for my game.

* What is the best way for me to do this?

It doesn't have to look great, it just shouldn't look like it was made in MS paint with the line and paint bucket tool.

Basically it should just mud with grass on top of it, shaped in some form of hills.

But how should I draw it, I can't just take out the pencil tool and start drawing it pixel per pixel, can I?

# Answer
Photoshop has layer-effects which can be used to draw good looking levels really fast. I don't know if that would work with GIMP, but here are some steps how to get something on screen fast using Photoshop:

## Instructions

1. Get some dirt and grass textures. The one I'm using in my example are from this freetexture set.
2. Open a dirt texture in Photoshop. Select all `Ctrl-A` and copy `Ctrl-C`. Then select `Edit > Define Pattern...` from the Menu. Name your Pattern "Dirt".
3. Do the same for the Grass texture, name it "Grass".
4. Create a new Layer in Photoshop and apply the `Pattern Overlay` and `Stroke` Effect to your layer. Select the "Dirt" pattern for the overlay and the "Grass" pattern for your Stroke (see images below).
5. Paint with any brush on your layer... instead of having a boring single color, it should render as a landscape, thanks to the layer effects. The beauty of this is, that you can freely add/remove parts of your landscape by using regular drawing tools like the brush or eraser.
6. *(optional)* Draw a gradient from dark blue (top) to light blue (bottom) on the background layer for your sky (you could also use layer-effects for that).
7. *(optional)* Add some more layer-effects like a gradient and drop-shadow to your "landscape" layer in order to achieve a better look.

## Images

### Pattern Overlay settings

### Stroke settings

### Final result

With some more layer effects and a background.

You can also download the PSD file here to have a look at it.
> 21 votes

# Answer
Many platformers and games of all kinds use a tile-based level system, where each level is made up of a grid of tiles, sometimes in multiple layers. You might have several "grass surface" tiles, several mud tiles, and so on. Then, instead of drawing a huge image, you lay the tiles out into a map. It tends to save on texture space, among other things.

More advanced 2D games take a similar approach, but with large "stamps" that can be freely moved, rotated, and/or scaled to make up a level and aren't stuck to a grid like in the tile-based technique. *Aquaria* uses this method.
> 4 votes

# Answer
If you don't mind it looking a little boring, you could just draw a bunch of circles of varying sizes along a flat line (your ground plane) and flood fill them in. Then you can go back and draw a brown box covering the "underground" portion of the map, and then add in little touches of ground to meet the top curves of the circle. Then you could do a detail pass to add grass or whatever (very easy if you have Photoshop with the different brushes).

That help?
> 2 votes

# Answer
I would highly recommend you grab a copy of Paint.NET its free, and 100x better than MS Paint -- its got some basic tools to facilitate generating art in the sense you are looking for.

It will, for example, allow you to make a selection and fill the entire selection with a given color/gradient, this will save you from using the pen tool and drawing pixel by pixel.

Its not even close to photoshop, but its excellent for this type of use-case, where you are looking for basic style art.
> 2 votes

---
Tags: 2d, level-design, side-scroller
---


# Question
Title: When does a game idea cross the line between homage/parody to ripoff?
I'm not sure where this question belongs, but as it pertains to the development of a game **idea**, I figured I'd try to post it here.

Recently I've been inspired to create a game based on another game I've played. However, the idea that I have is very similar to the original game. I was wondering, when does a game idea cross from being a homage or parody into the realm of being a ripoff? Are there any hard or fast rules or does this cross into a gray area?

# Answer
Other answers seem to be looking at this from a legal standpoint, but it sounds like you are talking more conceptually.

First, note that Parody and Homage are two very different categories; in the former case you're ridiculing the game's weaknesses, in the latter celebrating its strengths.

I would say in either case, the question of when you cross the line to "just another ripoff clone" is answered by whether your game adds anything new to the discussion.

For a parody, your game should not just be copying another game's mechanics, but it should be engineered to point out the flaws in the original in a way that the original game does not. For example, a parody of an old-school CRPG might not only have the player do a meaningless treadmill-grind for XP, but constantly remind them of how meaningless this is and how the game is just artificially increasing their required play time. Or it might eliminate the grind entirely, shortening the entire epic 40-hour experience to five minutes. In either case, the original game's mechanics are selectively copied (or not) to showcase a weakness with the form. To tell whether you are successful, I suppose a worthwhile question would be, "after playing this parody do you feel different about playing the original game?"

For an homage, you should be taking the original game further, improving it in some meaningful way. Here the question would be, "what reason is there to play this homage game, rather than playing the original?" and you should have a good answer!
> 7 votes

# Answer
Really, games are fluid, they're concepts, and you haven't implemented your game yet, so to me, that begs the question: Why even bother doing something that seems to you excessively similar to the other concept?

If there's any question in your mind that it's too similar, then it -is- too similar, by a long shot. And why would you want to put lots of work into something that someone else might consider similar as well? Now is the perfect time to throw some original ideas into the game to take it in a different direction.
> 0 votes

# Answer
I am not a lawyer, and this is not legal advice.

In the US, parody is a class of "fair use" of copyrighted material. The primary litmus test used appears to be whether the derivative work offers significant *commentary* on the original work. If the derivative work simply emulates the original, parody as a defense to an infringement claim is hollow.

An example of a parodic commercial game derived from another commercial game was 1996's *Pyst*, a parody of *Myst*. It was basically a tour of Myst Island as interpreted after everyone who bought a copy of *Myst* had tromped through it. It didn't have significantly similar gameplay to *Myst*, and obviously presented a significantly transformed version of its setting. It was also subtitled ***A PARODY*** at every possible opportunity, which came across as a slightly desperate "please don't sue us".

Intellectual property law outside the US should *not* be assumed to grant any protected status to parody.
> 0 votes

# Answer
It's worth noting the similarities between commercial games from the same creator, but after the rights were lost. Compare Total Annihilation and Supreme Commander, for example, which are exceedingly similar games from Chris Taylor after he lost the TA rights.

I personally would start by looking at the significant differences, rather than the obvious similarities. If the game is significantly different, you can probably escape, even if they have a lot in common.
> 0 votes

# Answer
Personally, I find this line is when the game that uses concepts from another game doesn't include anything new at all, and is generally worse than the original game. A homage should almost exactly replicate the original game, lest with some fixes or different content; a parody should do the same, except possibly exaggerate some flaws in the game. Finally, a ripoff is something that tries so hard to be another game, yet doesn't really achieve it. The developers have tried to add something new to the mix, yet it isn't very original.
> 0 votes

# Answer
When you have to ask your question, it is safe to assume that at least some people will cry "ripoff!" (assuming that your game reaches a certain amount of people, that is)

Now, this isn't necessarily a bad thing. Game devs have been doing this for years, with some impunity - Torchlight and Diablo, or Zelda and 3D Dot Heroes.

It seems to me that the best "marketing strategies" around the problem are being honest about it and admitting that your game is "a tribute of game xxxx" or "heavily inspired by xxxx".
> 0 votes

---
Tags: game-industry, copyright
---


title: How to use the chipmunk physics-engine?

text:
# Question
Title: How to use the chipmunk physics-engine?
I am developing a game demo where I want a physics simulation with balls and obstacles.

I know that this is possible with the chipmunk physics-engine but I don't know how to use it. Can anybody give me suggestions how to get started and provide links to the API documentation?

# Answer
A quick search gave me these two links.On which platform you need?

http://code.google.com/p/grabbed/source/browse/#svn%2Ftrunk \[Sample done with ChipMunk\]

http://www.alexandre-gomes.com/articles/chipmunk/ \[detailed description on usage \]
> 0 votes

---
Tags: iphone, physics, cocos2d-iphone
---


# Question
Title: Projectiles in tile mapped turn-based tactics game?
I am planning to make a Laser Squad clone and I think I have most of the aspects covered. But the major headache is the projectiles shot/thrown.

The easy way would be to figure out the probability of hit and just mark miss/hit. But I want to be able to have the projectile to hit something eventually (collateral damage!).

Currently everything is flat 2D tile map and there would be full (wall, door) and half height (desk, chair, window) obstacles.

My idea is to draw an imaginary line from the shooter to the target and add some horizontal&vertical error based on the player skills. Then I would trace the modified path until it hits something. This is basically what the original Laser Squad seems to do.

Can you recommend any algorithms or other approaches for this?

# Answer
> 2 votes
The idea you have is to raytrace into the scenery to see what it hits. This is viable because your game is (presumably) tile based. When the bullet starts, you must know its 3D position, even if it is fake. Once you know the direction of the bullet, you can use a Bresenham algorithm (more commonly used for line drawing) to see which squares the bullet will "touch". You can then do collision checking only for the objects touched by the Bresenham line.

Basically:

* Determine 3D starting position of bullet
* Determine 3D direction of bullet
* Determine in which square the bullet will land (if it hits nothing)
* Draw a line (in data) with the direction of the bullet using Bresenham
* For each square the bullet enters, check if the bullet hits anything

# Answer
> -1 votes
On my tiled shooter I basically start the projectile at the origin point with a given vector, that specifies its direction/velocity. On every move I test the distance to other actors and check if it's less than the projectile radius.

We also have projectiles that will spawn explosions. The explosions themselves are just like projectiles, with zero or very little reach but with larger radius.

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


# Question
Title: Any technical references for game-oriented icons and symbols?
To make localizing easier, I'm using icons to show in-game information like achievements and bonuses. Coming up with good designs isn't easy, especially when it has to be integrated into the rest of the game's art style.

Can I do better than looking at some random selection of existing games?

Are there any reference books or sites that cover game graphics specifically?

I'm looking for more theory and best-practices rather than pre-made graphics.

# Answer
Why keep it in the game's subject? Take a look at subways, airports, train stations... you can go anywhere in the world and it's relatively easy to move around the city or arrive at the correct gates just looking at maps or signals. There are good designs all around the world, you just have to hunt them.
> 3 votes

# Answer
I don't think icons for games are that much different from any other icon. You want it to be clearly recognizable and well.. *iconic*.

Integrating an icon into the games art-style is basically the same as creating an icon for any existing platform. You'll have to respect the art-style that has been established for that platform (example: have a look at the Windows guidelines or Mac OS X Guidelines). For your game you can come up with your own set of guidelines though. It can be as simple as: Icon must have the shape of a circle and must be provided in two sizes, a big and a small version.

I'm afraid there's no guide to the best game icon though. Creating good icons requires a lot of talent, because you'll have to be able to reduce stuff to the max, while still keeping it recognizable and maintain a consistent style. So definitely not something that should be done by a programmer (no offense).

Maybe these tutorials are of some help to you.
> 2 votes

---
Tags: graphics-design
---


title: Broken alpha of two-sided OpenGL mesh

text:
# Question
Title: Broken alpha of two-sided OpenGL mesh
How do I get rid of this alpha transparency artifacting with classic fixed function OpenGL?

I tried all kinds of settings but I'm not sure why it's good in the upper half of the mask but not in the lower half.

alpha illustration | 1.7M GIF

I have a two-sided concave mesh and want to fade out the edges with an alpha vector on the vertex colors. I get the same artifact with an RGBA texture also.

# Answer
You can't do this in a single pass.

Well, maybe I should clarify.

If you look at the way a triangle rasterizer works, is that it takes a bunch of triangles and puts them on the screen. But, for each pixel, it checks its z value to a value in the z-buffer. If the z of the pixel that wants to be drawn is greater than the pixel that was already there, the z in the z-buffer is set to that value and the pixel on the screen is set to that pixel.

However, you might be able to work around this, like so:

```
glDepthMask(GL_FALSE);

// render polygons

glDepthMask(GL_TRUE);

```

Now you *read* from the z-buffer, but you don't *write* to it. This way, every pixel is drawn regardless of depth. However, this probably won't work for you. It will mean that some background triangles will be rendered on top of foreground triangles.

What you want to do is split the rendering into two passes: a normal pass and a pass for alpha-transparent polygons. When you render the second batch, you can look up the color of the pixel behind the one you're drawing and alpha blend with it.
> 2 votes

---
Tags: opengl, transparency
---


title: What does vsynched mean?

text:
# Question
Title: What does vsynched mean?
I'm always looking for ways to improve the smoothness of my games. When I read around the net I come across the term "**vsynched**" quite often. **What does vsynched mean**?

# Answer
It just means that the game matches the refresh rate of the monitor/screen. So if you have a 60Hz monitor (meaning the monitor image is refreshed 60 times a second), the game won't perform above 60 FPS.

If you have vertical synchronisation (vsync) turned off, then if the GPU and monitor go out of sync, then you get an artifact commonly known as "tearing" like so:
> 12 votes

---
Tags: graphics, performance
---


# Question
Title: 2D Game Physics: How to evaluate when an accelerating ray is close to a point?
Given a ray in a 2D world at position **p** with initial velocity **u** and acceleration **a** how can I tell when it's within a certain distance **r** from a certain point.

# Answer
> 1 votes
Uniform motion: s = ut + at^2/2

Or p(t) - p(0) = ut + at^2 / 2

You want the first t \>= 0 for which (p(t) - C).(p(t) - C) = r^2.

If u and a could be non-perpendicular then I think you have to solve a quartic.

---
Tags: 2d, physics
---


title: Interpolating Matrices

text:
# Question
Title: Interpolating Matrices
Apologies if I am missing something very obvious (likely!) but is there anything wrong with interpolating between two matrices by:

```
    float d = (float)(targetTime.Ticks - keyframe_start.ticks) / (float)(keyframe_end.ticks - keyframe_start.ticks);
    return ((keyframe_start.Transform * (1 - d)) + (keyframe_end.Transform * d));

```

As in my app, when I try an use this to interpolate between two keyframes, the model begins to 'shrink' - the severity based on how far between the two keyframes the target time is; its worst when the transform split is ~50/50.

# Answer
Put very simply, linear interpolation of matrices is not always a good idea. If you have an animation you are trying to accomplish, and you are using matrices to handle the bones rotation, you can't just take a linear combination of them. You'll need to use slerp, extract the axis of rotation and interpolate the angle and recalculate the rotation matrix, or you'll need to just use quaternions. Translation is linear, rotation is not (except for small angles theta).

Here is agood writeup on matrices and 3d applications
> 7 votes

# Answer
Interpolating the matrices like that isn't going to give a useful result, especially for anything involving a rotation. Ideally you want to decompose your animation into some other format (quaternion for rotation, for example) and then interpolate in that form before building the matrix.
> 2 votes

# Answer
Here is a graphical example of what I meant in the comment I wrote in the comment section of the OP's question. While the ticks representing the d values progress evenly from one vector to the other, the angular change (red lines) are not even. the changes near the middle of the sequence represent greater change than near the ends. so an animation of interpolated vectors will start slow, speed up near the middle, and slow down towards the end. If the angle between start and end is not great, it may not be noticeable.

The varying lengths of the interpolated vectors (red lines) are the reason your model was shrinking in places too as they will scale the model to their lengths.

If you used quaternions, the blue line would arc from vec A to vec B and each tick would cause equal angular change as well as an equal distance along the arc.
> 2 votes

---
Tags: xna, animation, matrix, interpolation
---


title: xbox open source project

text:
# Question
Title: xbox open source project
im looking for some open source xbox project, I just wanna join it and try myself as game programmer, does anybody know such project?

# Answer
First off, this is a question and answer site, rather than a project finding site.

Secondly, you can only get an SDK for the Xbox if you are a licensed developer and pay a lot. So I doubt you'll find an open source one.

However, you can create Xbox Live Community Arcade (?) games with XNA and C#, for $99 a year for a license. They won't be open source, but you can join them. Gamedev's help wanted forum is good.
> 8 votes

---
Tags: xbox360, open-source, xbox
---


title: Inconsistent accessibility error in xna

text:
# Question
Title: Inconsistent accessibility error in xna
Hey all, you may remember me asking a question regarding a snake game I was creating about two weeks ago.

Well I'm quite far now into making the game (thanks to a brilliant tutorial I found). But I've come across the error described named above.

So heres my problem;

I have a SnakeFood class that has a method called "Reposition". In the game1 class I have a method called "UpdateInGame" which calls the reposition method to load an orange that spawns in a random place every second.

My latest piece of code changed the reposition method to allow the snake I have on the screen to not be overlapped by the orange that randomly spawns.

Now I get the error (in full):

Error 1 Inconsistent accessibility: parameter type 'TheMathsSnakeGame.Snake' is less accessible than method 'TheMathsSnakeGame.SnakeFood.Reposition(TheMathsSnakeGame.Snake)' C:\Users\Tom\Documents\Visual Studio 2008\Projects\TheMathsSnakeGame\TheMathsSnakeGame\SnakeFood.cs 33 21 TheMathsSnakeGame

I understand what the errors trying to tell me but having changed the accessiblity of the methods, I still can't get it to work.

Sorry about the longwinded question.

Thanks in advance :)

Edit: Code I'm using

```
 (Game1 Class)
private void UpdateInGame(GameTime gameTime)
    {
        //Calls the oranges "reposition" method every second
        if (gameTime.TotalGameTime.Milliseconds % 1000 == 0)
            orange.Reposition(sidney);
        sidney.Update(gameTime);
    }

(SnakeFood Class)
 public void Reposition(Snake snake)
    {
        do
        {
            position = new Point(rand.Next(Grid.maxHeight),     rand.Next(Grid.maxWidth));
        } while (snake.IsBodyOnPoint(position));
    }

```

# Answer
> 5 votes
The accessibility levels of C# are `public` \> `protected` \> `internal` \> `protected internal` \> `private`. Your class' accessibility must by \>= to the accessibility of the methods it contains.

---
Tags: xna
---


title: Storing Tiled Level Data in J2ME game

text:
# Question
Title: Storing Tiled Level Data in J2ME game
I'm developing a J2ME game which uses tiled backgrounds for the levels. My question is how do I store this tile information in my game. At the moment it is stored as an array; with each number representing a different tile from the tile-sheet. This works well enough, however I don't like the fact that it is 'hard-coded' into the game because (at least in my opinion) it is harder to edit the levels, or design new ones. I was also thinking that it would be difficult if you wanted to add a 'level pack', I'm not sure on how this would be achieved though; it's not something I was planning on doing, I'm just curious.

I was wondering if there was a way I could store level data in some external file and then load this in to the game. The problem is I don't know what the limitations are for J2ME regarding file I/O, can it read in any file like Java? I am aware of the RMS, but from my experience I don't think this would work (unless I am mistaken).

Also, would loading the data in this way be too big a performance hit? Or is there another way I can achieve what I am trying to do. As I said, the way I have it at the moment works fine, and if this is the only viable option then it will suffice.

# Answer
Loading the tile information from file would work just fine. A very basic format would be a matrix with IDs like this:

```
0 1 1 1 0 2 0
0 1 1 1 0 2 0
0 0 0 0 0 2 0
0 3 3 3 3 3 3
... etc.

```

You can then read this in and split by space/newline to get an array.

Another option is using an editor like Tiled or OgmoEditor which can both save to an XML format you can read and parse within Java. You should be able to read files using J2ME too.
> 3 votes

---
Tags: java, tiles, mobile
---


# Question
Title: How to manage enemy movement and shoot in a shmup?
I'm wondering what is the best (or at least a good) way of managing enemies in a shoot-em-up.

Basically, what I'd do would be a class that manages displaying and updating positions of all the enemies. But how to create good deplacements for enemies? A list of where-to-go points? *gravitating* around some fixed points (with ponderation, distance evaluation etc.)?

Same question for the shoot patterns?

Can you please put me on a track?

# Answer
> 3 votes
Use BulletML to define shot patterns:

> BulletML is the Bullet Markup Language. BulletML can describe the barrage of bullets in shooting games. (The storm of Progear, Psyvariar, Gigawing2, G DARIUS, XEVIOUS, ...)

Most simple enemy movement can also be expressed in BulletML; bosses may need a bit more state. It has been used in many games and prototypes.

The reference implementation is in Java. If you want to use C+++, you can use libBulletML.

# Answer
> 1 votes
It sounds like what you're asking is a general question, "what is a good enemy movement pattern / AI for a shmup?" - a design question more than a programming one. There is no single right or wrong answer here. It all depends on your game and especially the design of your level environments. For example, in a level without much maneuverability and lots of tight spaces, enemies that just sit there and do nothing can make sufficiently challenging obstacles, while enemies that pass through walls and head directly to the player are just mean. In a wide-open space, enemies with no movement would be trivial to avoid (unless there's a lot of them!) while enemies that track the player movement might work better.

My advice would be, play a lot of shmups, but as you play, pay attention to enemy movement patterns in relation to level design, and also which levels feel fun versus too easy versus really frustrating. After awhile you will probably get a good feel for what kinds of common patterns there are, and what makes them good or bad. But there is no simple answer other than that, I don't think, if I understand your question correctly.

---
Tags: c++, movement, shoot-em-up
---


# Question
Title: How to use OpenGL blend mode/functions to brighten/darken a texture.
Tried this code, but the texture didnot get any lighter.

```
    try {
        texture = TextureLoader.getTexture("png",
           Game.class.getResourceAsStream("/brick.png"), true, GL_NEAREST);
    } catch (IOException e) {
        e.printStackTrace();
    }

    GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getTextureID());

    glEnable(GL_BLEND);
    glBlendFunc(GL_CONSTANT_ALPHA, GL_CONSTANT_ALPHA);
    GL14.glBlendColor(1.0f, 1.0f, 1.0f, 0.5f);

    glColor4f(1, 1, 1, 0.5f);
    GL11.glBegin(GL11.GL_QUADS);          // Start Drawing Quads
    // Front Face
    GL11.glNormal3f(0.0f, 0.0f, 1.0f);    // Normal Pointing Towards Viewer
    GL11.glTexCoord2f(0.0f, 0.0f);
    GL11.glVertex3f(-1.0f, -1.0f, 1.0f);  // Point 1 (Front)
    GL11.glTexCoord2f(1.0f, 0.0f);
    GL11.glVertex3f(1.0f, -1.0f, 1.0f);   // Point 2 (Front)
    GL11.glTexCoord2f(1.0f, 1.0f);
    GL11.glVertex3f(1.0f, 1.0f, 1.0f);    // Point 3 (Front)
    GL11.glTexCoord2f(0.0f, 1.0f);
    GL11.glVertex3f(-1.0f, 1.0f, 1.0f);   // Point 4 (Front)
    glEnd();

```

# Answer
> 2 votes
This is not how blending works, it doesn't work on the same polygon. Blending blends between more polygons (or fragments to be more correct). But you can use blending for lighting or darkening textures of course, its good idea actually.

Simple solution is to draw first quad with texture and then draw quad with blending enabled with blending color on it. But the second quad must be slightly moved to the direction of the camera. Something like this: `GL11.glVertex3f(-1.0f, -1.0f, 0.99f);`

Much **nicer and cleaner solution** would be first draw quad with texture and than qaud with color at the same position but setup zBuffer comparison function to equal.

And remember with alpha blending do not forget that you always first render opaque objects and then transparent.

And once you start using shaders this will be trivial operation on fragment/pixel shader with no need of blending.

---
Tags: opengl, java, lwjgl
---


title: One True Event Loop

text:
# Question
Title: One True Event Loop
Simple programs that collect data from only one system need only one (blocking) event loop. For example, Windows applications have the message loop, POSIX network programs usually have a select/epoll/etc. loop at their core, pure SDL games use SDL's event loop. But what if you need to collect events from several subsystems? Such as an SDL game which doesn't use SDL\_net for networking.

I can think of several solutions:

1. Polling (ugh)
2. Put each event loop in its own thread, and:

1. Send messages to the main thread, which collects and processes the events, or
    2. Place the event-processing code of each thread in a critical section, so that the threads can wait for events asynchronously but process them synchronously
3. Choose one subsystem for the main event loop, and pass events from other subsystems via that subsystem as custom messages (for example, the Windows message loop and custom messages, or a socket select() loop and passing events via a loopback connection).

Note that I'm talking about an event loop that blocks execution until an event arrives. This allows writing event-based games that don't pointlessly burn 100% CPU, and can process events even during drawing or performing a logic update. Checking if a subsystem has events and continuing execution otherwise is what I'd call polling.

Option 2.1 is more interesting on platforms where message-passing is a well-developed threading primitive (e.g. in the D programming language), but 2.2 looks like the best option to me.

# Answer
So, the tech that I'm working with right now has a notion of a central message stream shared by all threads via subscription and duplication (threads install handlers which may or may not duplicate consumed messages).

This stream is fed by a thread dedicated to translating/polling different event queues/devices. If need be, because event sources all expose the same API to this thread, I can (in, say, the case of XInput which seems to be polling-only) create a class containing a thread devoted to handling a particular sort of input; this lets me handle things as diverse as 360 controllers and asynchronous social media querying.

One nice thing about having this unified stream is also that I can do weird things like have a handler that consumes events and pattern matches them with a state-machine to handle things like attack combos for a fighting game and then emit a game event that says "Haruken!"

Keep in mind that the end goal for something like this is to combine a diverse range of input events into a single stream some tech is guaranteed to handle correctly (Quake had a good take on this).
> 2 votes

# Answer
I remember looking through the code base of ChucK http://chuck.cs.princeton.edu/ and noticing that the whole program uses just one thread. ChucK is an interesting example because it fakes concurrency using one thread in a "strongly-timed" model (that's my best explanation ;) ). However, there are threads for different event sources (MIDI events, Open Sound Control events, or socket messages) and these queue the events for processing by the main loop.

So...I'd pick option 2.1. which seems the same as option 3.
> 1 votes

# Answer
Adding threads to the system creates bugs at worst and inefficiency at best (due to the necessary synchronisation) unless you have a clear example of the parallelism helping, so I wouldn't use it in this case. Note that your option 2.1 has left out the synchronisation aspect - you're ok on Windows since PostMessage is synchronised, but this is something you need to check on a per-API basis.

I wouldn't choose to route several subsystems into another via custom messages because this could require significant rewriting should you change that subsystem - eg. port from Win32 to SDL or whatever.

So, I usually go with polling where the subsystems make it possible and efficient. eg. It's rarely a problem to poll your network library, because either there is data ready to read or there is not - you're not going to slow down your program by checking for it if the library is well made.
> 1 votes

# Answer
If the event loop is cleanly written, there is no reason that a primary thread cannot have two event loops. Windows, for example, has PeekMessage. First you process all Windows messages, then you move on and process all whatever messages. As long as you're not blocking on a call to receive a message, then there's no reason that you can't call two message querying functions in a single loop instead of one.
> 1 votes

---
Tags: architecture, multithreading, events
---


# Question
Title: Best practices for implementing collectible virtual item "packs"?
I'm in the process of building a game in which virtual items can be obtained either by in-game play (defeating enemies, gaining levels), or by purchasing "packs" via microtransactions.

Looking at an existing example like Duels.com's item packs, it looks like a lot of thought went into their implementation, including:

* Setting clear player expectations as to what can be obtained in the pack
* Limiting pack supply to increase demand and control inflation

Are there other considerations that should be taken into account? For example, should the contents of the packs be pre-generated to guarantee the advertised drop rates, or is each drop rate just a random chance, and you could end up with higher or lower supply?

# Answer
There's two important considerations for the game economy.

1) When items are not able to be traded between players.

If the pack items aren't able to be traded/gifted/etc between players then don't worry about supply and demand. Just let people spend what they would like and be clear about what you can get from the pack. Mafia wars sets a great precedent here and because the supply really doesn't matter, you can just have the items be totally randomly dropped.

2) When items are able to be traded between players.

That's when things get tricky. In order to have a functioning game economy, items must not just flow into the game but they must also leave the game. So you need to make sure that there must be a way that the items players buy in the packs, if they match the functionality of game items, are either used up over time or they can be lost on death. The particular mechanics depend on your game but you absolutely have to balance items leaving vs items entering the game.

Then once you have the inflow and outflow of items balanced you can decide the specifics of whether you want the items to be totally random or balanced beforehand. In a large enough volume you'll get almost entirely the same result.

In this situation I personally would set it up such that a pack gives you similar items to a certain amount of repetitions of whatever you do in game to get the items. So you can kill 50 X-dragon that gives you a 50% chance of 10 of Y-dragonhide per kill then you can go kill 50 dragons in game to get 250 dragonhide, or you can buy a pack of 250 dragonhide. That way you're not completely alienating the players who prefer to "work" for their items.

That can be further balanced by simply allowing people to buy only the kills that could have happened, but nobody was online to kill the dragon(s). So if the dragons take 5 minutes to kill and respawn after 10 minutes, then you know that only 96 dragons can be killed per day. If there's only 50 dragons that are killed that day, then you can put 46 dragon kills up for sale.

I don't know of any games that have implemented any systems like this, simply because making items that can be traded between players purchasable tends to really piss off everybody who plays for "free".
> 5 votes

# Answer
To add to Kort Pleco's wonderful answer:

* Are items permanent or consumable (or both)? For example, many free-to-play games offer microtransaction-purchasable items that do something like "double your experience for the next 24 hours". If players are going to be getting items but then using them, inflation and availability are less of an issue.
* Bulk rates. Do players get extra stuff for buying a lot of item packs at once? For example, maybe buying a single pack has a 10% chance of holding a "super-rare" item; maybe if you buy a box of 10 packs, you guarantee the player at least one super-rare.
* Generally you don't have to worry about whether drop rates / random distribution will conform exactly to expectations or not; the laws of probability dictate that the more times you do something random, the closer your overall distribution conforms to the expected value. So if you're afraid of randomly generating too many of Item X and not enough of Item Y, enough item drops will fix that over time.
* HOWEVER: absolutely do some statistical tests on your item generation code to make sure you are actually generating things according to the probability curve you thought. A software bug here will absolutely be noticed. (I actually did see some production code in a card game once where the shuffling algorithm was not done correctly, so certain cards tended to get shuffled to the top more often than others, so I'm not kidding about this.)
* If players can trade/gift items to one another, there are a LOT of additional considerations. Are you okay with players trading their stuff for cash, i.e. Player 1 sells their stuff through Paypal to Player 2, and all you see on your server is an "item gift"? If not, what steps can you take to stop it, and how much time are you willing to spend cracking down on this? If so, what will you do when a player inevitably rips off or scams another player for money or items - will you actually reverse the trade, or will you leave your players twisting in the wind... and if you DO reverse the trade in the case of scams, keep in mind that'll cause scamming to proliferate because your players will think of you as a safety net. Or do you force all transactions to happen through your servers, including cash - and if so, are there additional legal issues since you're now effectively acting as a bank or payment processing service in addition to a game service (let alone any potential charges of "gambling" since players can spend or make money on your game that has random elements to it)?
> 2 votes

# Answer
I'd suggest you to completely separate "things that are created in-game" from "things you can buy from outside the game".

If you do, you raise the value of both the items bought (because they can't be obtained just farming) *and* the value of the farmable items (because they can't just be bought); this way you don't alienate any player.

Then, regardless of how these items are obtained, they can be traded (of course you have to pay attention to all the economy problems).

You are right about the importance of player expectations for the pack contents, about what I suggest:

* there might be variations on quantity, but small variations (such as 3-5 of this, and 6-9 of that)
* there shouldn't be anything very rare, or some people will buy a lot of packs without getting it, become angry, and not buy any more packs again
> 1 votes

# Answer
I been playing LOTRO for 3 months now. There are tons of items in that game. However, equips (weapons, armor) and other very cool items are bound to your character, so like Kort Pleco said before, there is no trading for those items. So, the game is very balanced, because if I have a superb item, there is no way that item could be sold when I dont need it anymore, and sold again, and again... You get a nice item (crafting it, looting it, buying it from the market) but is just for you, and when you dont need it anymore, the only thing you can do with is destroy it. The binding system isnt new, but I think its very useful.
> 0 votes

---
Tags: online, microtransactions
---


# Question
Title: Visualization tools for physical simulations
I'm interested in starting some physics simulations and I'm getting hung up on the visualization side of things. I have lots of resources for reading how to implement the simulation itself but I'd rather not learn two things at once - the simulation part and a new complex visualization API.

Are there any high-level visualization tools that are language independent? I understand that I'll have to learn some new code for visualization but I'd like to start at a high level, OpenGL is my long-term goal and not my prototype goal.

# Answer
> 0 votes
While not language independent, I found that pygame was a simple solution that contained most of the functionality I needed. Python in its most basic form is fairly easy to use (or learn) and hooking some basic python up to some visuals on a screen is done very easily with pygame.

# Answer
> 3 votes
Everybody mentions polygonal renderers. If your visualisation is going to be volumetric (smoke, fluids) or vector or something else you should consider VTK - Visualization Toolkit

# Answer
> 2 votes
If you don't have a lot of preexiting code you might want to consider Unity.

Some benefits:

* Probably the easiest "drop in a primitive shape in an editor and attach some functionality to it" engine I know of.
* Has the ability to allow you to recompile code at run time for tweaking purposes (this breaks if you do certain things, but assuming you don't design yourself into a corner and rely on something that has known issues this could be very useful)
* Can write scripts in either C#, "Unityscript" (which is a variant of Javascript), or Boo (which is a lot like Python), so while it isn't language independent at all, you could probably find a language you're comfortable with.
* Can use .NET DLLs, so ostensibly you could write some underlying code in F# or maybe even C++/CLI
* Super cross platform.
* Don't have to know any graphics code, and everything is very visual in the editor

# Answer
> 0 votes
Havok and PhysX both come with Visual Debuggers. They're relatively simple to use in your code.

As far as I know, I haven't seen any generic visualizers, simply because it's impossible to know how you're designing and implementing your physics classes, what integrators you're using, what units you're using, etc, etc.

Havok and PhysX are both free to use now, so I'd probably recommended using them.

---
Tags: simulations, visualization
---


# Question
Title: Game networking topology - dealing with host leaving
I am working on a P2P game in Flash and I'm wondering what network topology would be most robust for dealing with people randomly joining/leaving. I was thinking the first user to join could be the host, but if the host leaves the whole session would be killed. I am looking for a way to deal with this with no (or little) disruption.

# Answer
If you're using a model where there's a "host", you pretty much have star topology, however you dress it up. Recovery from loss of the central node in that model requires that all the nodes be able to find each other in that event (which makes it sound like mesh topology but it isn't), and either all of them have sufficient state to be able to take over the host role or they can reconstruct that state between them. Then you elect a new host by whatever method you like (I suggest lowest average ping to the rest of the nodes).

You can potentially do that with no disruption if the host leaves "nicely"; you start the host-role transfer process when they hit Quit and let them leave when it's done. If they leave by network interruption, force-quit, power loss, etc. there will be disruption.

If you do actual mesh topology, where each node has its own full state model and communicates about changes made to that out to everybody it's connected to, then you avoid the host role and the vulnerability that comes with it. The fun part then is conflict resolution -- working out what happens when two nodes try to propagate changes that contradict each other.
> 8 votes

---
Tags: flash, networking, multiplayer, peer-to-peer
---


title: Spawning bullets on command in Box2D

text:
# Question
Title: Spawning bullets on command in Box2D
I'm making a simple bullet hell game but I can't figure out how to get my character to shoot. Lets say I have bulletBody and shipBody, how would I continually spawn bulletBodies using the shipBody coordinates. I've tried a function that uses an array of b2bodies and just assigns them the bodydef and fixture but that causes the game to crash. C++ sample code would be best but any help is appreciated.

EDIT: It looks like any reference to my b2World in a function will cause the game to crash. How do I declare the bodies without using a b2World as an argument in the function.

# Answer
> 2 votes
b2World, b2Body, etc, cannot be copied. You must pass them by pointer or reference:

```
void process(b2World world);  // this is bad.
void process(b2World *world); // this is fine.
void process(b2World &world); // this is probably best.

```

Likewise, b2Bodys must be generated from b2World::CreateBody, and cannot be copied, so must be passed by pointer or reference:

```
std::vector<b2Body *> bodies;
b2World world(...);
...
b2BodyDef dfn = ...;
bodies.push_back(world.CreateBody(&dfn));

```

It sounds like you might be doing:

```
std::vector<b2Body> bodies;
bodies.push_back(*world.CreateBody(&dfn));

```

Which *will not work*. The b2World instance owns the body.

The Box2D manual goes into detail, with code examples for most simple tasks.

# Answer
> 0 votes
> but I can't figure out how to get my character to shoot

Well, lets see, i did something like this the first time i did a shooter game... You can do a bullet class with int X, int Y, bool active... then you can do an array of bullet. Then, when the player shoots, you set the bullet\[0\] X and Y at the same position of the sprite, the gun, whatever, and put bool active = true... when you update the state of the game, you search the bullet array, and if active, you modify X and or Y. At your draw phase, you search the bullet array again, and if activr, you draw it at bullet.X, bullet.Y. Also, at update stage, you check for collisions or check if the bullet is still inside the screen, so events are trigged like kill the guy and reset the bullet (active=false)

---
Tags: box2d
---


# Question
Title: Handling cameras in a large scale game engine
What is the correct, or most elegant, way to manage cameras in large game engines? Or should I ask, how does everybody else do it?

The methods I can think of are:

Binding cameras straight to the engine; if someone needs to render something, they bind their own camera to the graphics engine which is in use until another camera is bound.

A camera stack; a small task can push its own camera onto the stack, and pop it off at the end to return to the "main" camera.

Attaching a camera to a shader; Every shader has exactly one camera bound to it, and when the shader is used, that camera is set by the engine when the shader is in use. This allows me to implement a bunch of optimizations on the engine side.

Are there other ways to do it?

# Answer
Real-Time Cameras by Mark Haigh-Hutchinson covers just about everything there is to know about cameras. (Sorry I can't give a more direct reference to the issues you ask about, but my copy is across an ocean right now, I think.)
> 2 votes

---
Tags: 3d, camera
---


# Question
Title: Resources on expected behaviour when manipulating 3D objects with the mouse
In my animation editor, I have a 3D gizmo that sits on the origin of a bone; the user drags the mesh around to rotate the bone.

I've found that translating the 2D movements of the mouse into sensible 3D transforms is not near as simple as i'd hoped.

For example what is intuitively 'up' or 'down'? How should the magnitude of rotations change with respect to dX/dY? How to implement this? What happens when the gizmo changes position or orientation with respect to the camera? ect.

So far with trial and error i've written something (very) simple that works 70% of the time. I could probably continue to hack at it until I made something that works 99% of the time, but there must be someone who needed the same thing, and spent the time coming up with a much more elegant solution.

Does anyone know of one?

# Answer
You could constrain rotation to just the 3 axes that align with the gizmo's vectors.

Then add a drop down box to allow the gizmo to line up with either world, local, view, etc.

This is the way 3ds max does it.
> 1 votes

# Answer
Download a bunch of demos of 3D-editors, like 3ds max, Milkshape3D, Blender, ZBrush .... Follow a tutorial for every of the modelers that teaches you how to construct something out of primitive objects. The reason is that the chance to have to move objects around freely in 3D space is higher when working with primitive objects than, say, when manipulating vertices.

Figure out, which software's approach you liked the most and copy as if there was no tomorrow.
> 0 votes

---
Tags: 3d, algorithm, gui, movement, interface
---


title: My first animation - Using SDL.NET C#

text:
# Question
Title: My first animation - Using SDL.NET C#
I'm trying to animate a player object in my 2D grid when the user clicks somewhere in the screen.

I got the following 4 variables:

1. oX (Current player position X)
2. oY (Current player position Y)
3. dX (Destination X)
4. dY (Destination Y)

How can I make sure the player moves in a straight line to the new XY coordinates. The way I'm doing it now is really awfull and causes the player to first move along x axis, and finally in y axis.

Can someone give me some guidance with the involved math cause I'm really not sure on how to accomplish this.

Thank you for your time. Kind regards, Mark

Update: It's working now but whats the right way to check if the current positions are equal to the target position?

```
    private static void MovePlayer(double x2, double y2, int duration)
{
    double hX = x2 - m_PlayerPosition.X;
    double hY = y2 - m_PlayerPosition.Y;

    double Length = Math.Sqrt(Math.Pow(hX, 2) + Math.Pow(hY, 2));
    hX = hX / Length;
    hY = hY / Length;

    while (m_PlayerPosition.X != Convert.ToInt32(x2) || m_PlayerPosition.Y != Convert.ToInt32(y2))
    {
        m_PlayerPosition.X += Convert.ToInt32(hX * 1);
        m_PlayerPosition.Y += Convert.ToInt32(hY * 1);

        UpdatePlayerLocation();
    }
}

```

# Answer
> 2 votes
You will want to look into vector maths for this. The basic way you would handle this is as follows:

You'd want two variables as your "heading", this will tell you the direction you want to be heading in.

Let's call them hX and hY.

hX = dX - oX
hY = dY - oY

You should probably normalize these values (meaning, the length of the vector is equal to 1). You do that by performing the following:

Length = sqrt( hX^2 + hY^2 )
hX = hX / Length
hY = hY / Length

Now you can use a speed multiplier to determine how quickly you want your agent to move to the destination position.

currentX += hX * SPEED
currentY += hY * SPEED

That should be everything really. To make this a LOT easier, it might be worth looking into incorporating a maths library with SDL so that you can use vectors and vector operations.

EDIT FOR UPDATED QUESTION:
The way you have your while loop at the moment will lock up your entire game until the player has arrived at the position.

A better way is to have a standard game loop with an Update() function like so:

```
public class Game
{
    // Other implementations left out
    public void Update()
    {
        UpdatePlayer()
    }
};

```

In your UpdatePlayer() function you can call MovePlayer() and within MovePlayer() since the Length variable is always updated every time you call the function, all you have to do is update MovePlayer() to do something like this:

```
private static void MovePlayer(double x2, double y2, int duration)
{
    double hX = x2 - m_PlayerPosition.X;
    double hY = y2 - m_PlayerPosition.Y;

    double Length = Math.Sqrt(Math.Pow(hX, 2) + Math.Pow(hY, 2));

    if( Length < 0.1f )    // Less-than rather than Length == 0.0 to handle floating point errors
        return;

    hX = hX / Length;
    hY = hY / Length;

    m_PlayerPosition.X += Convert.ToInt32(hX * 1);
    m_PlayerPosition.Y += Convert.ToInt32(hY * 1);

    UpdatePlayerLocation();
}

```

---
Tags: c#, animation, sdl
---


title: View matrix in opengl

text:
# Question
Title: View matrix in opengl
Sorry for my clumsy question. But I don't know where I am wrong at creating view matrix.

I have the following code:

```
 createMatrix(vec4f(xAxis.x, xAxis.y, xAxis.z, dot(xAxis,eye)),
 vec4f(  yAxis.x_, yAxis.y_, yAxis.z_, dot(yAxis,eye)),
 vec4f(-zAxis.x_, -zAxis.y_, -zAxis.z_, -dot(zAxis,eye)),
 vec4f(0, 0, 0, 1)); //column1, column2,...

```

I have tried to transpose it, but with no success. I have also tried to use gluLookAt(...) with success. At the reference page, I watched the remarks about the to-be-created matrix, and it seems the same as mine. Where I am wrong?

# Answer
> 9 votes
In openGl matrices are transposed in memory. So transpose the matrix is OK. But your code doesn't look correct.

So you are in OpenGl. OpenGl uses right handed coordinate system. And for RH is lookat function defined like this:

```
zaxis = normal(cameraPosition - cameraTarget)
xaxis = normal(cross(cameraUpVector, zaxis))
yaxis = cross(zaxis, xaxis)

 xaxis.x           yaxis.x           zaxis.x          0
 xaxis.y           yaxis.y           zaxis.y          0
 xaxis.z           yaxis.z           zaxis.z          0
-dot(xaxis, cameraPosition)  -dot(yaxis, cameraPosition)  -dot(zaxis, cameraPosition)  1

```

Especialy take care about `zaxis = normal(cameraPosition - cameraTarget)` because it is the only difference between RH and LH system.

**Save it transposed and that's it**

# Answer
> 2 votes
I don't know what is wrong with your code, but it looks different to mine. Here's what I've been using in my projects for the past few years.

```
    return new float4x4(
        Xax.X, Yax.X, Zax.X, 0,
        Xax.Y, Yax.Y, Zax.Y, 0,
        Xax.Z, Yax.Z, Zax.Z, 0,
        -float3.Dot(pos, Xax), -float3.Dot(pos, Yax), -float3.Dot(pos, Zax), 1
    );

```

I hope this helps somewhat.

---
Tags: opengl, matrix, linear-algebra
---


# Question
Title: Computing a normal matrix in conjunction with gluLookAt
I have a hand-rolled camera class that converts yaw, pitch, and roll angles into a forward, side, and up vector suitable for calling gluLookAt. Using this camera class I can modify the model-view matrix to move about the 3D world just fine.

However, I am having trouble when using this camera class (and associated model-view matrix) when trying to perform directional lighting in my vertex shader.

The problem is that the light direction, (0, 1, 0) for example, is relative to where the 'camera is looking' and not the actual world coordinates. (Or is this eye coordinates vs. model coordinates?) I would like the light direction to be unaffected by the camera's viewing direction.

For example, when the camera is looking down the Z axis the ground is lit correctly. However, if I point the camera straight at the ground, then it goes dark. This is (I think) because the light direction is parallel with the camera's 'up' vector which is perpendicular with the ground's normal vector.

I tried computing the normal matrix without taking the camera's model view into account, but then none of my objects were rotated correctly.

Sorry if this sounds vague. I suspect there is a straight forward answer, but I'm not 100% clear on how the normal matrix should be used for transforming vertex normals in my vertex shader.

For reference, here is pseudo code for my rendering loop:

```
pMatrix = new Matrix();
pMatrix = makePerspective(...)

mvMatrix = new Matrix()
camera.apply(mvMatrix);  // Calls gluLookAt

// Move the object into position.
mvMatrix.translatev(position);
mvMatrix.rotatef(rotation.x, 1, 0, 0);
mvMatrix.rotatef(rotation.y, 0, 1, 0);
mvMatrix.rotatef(rotation.z, 0, 0, 1);

var nMatrix = new Matrix();
nMatrix.set(mvMatrix.get().getInverse().getTranspose());

// Set vertex shader uniforms.
gl.uniformMatrix4fv(shaderProgram.pMatrixUniform,
        false, new Float32Array(pMatrix.getFlattened()));
gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform,
        false, new Float32Array(mvMatrix.getFlattened()));
gl.uniformMatrix4fv(shaderProgram.nMatrixUniform,
        false, new Float32Array(nMatrix.getFlattened()));

// ...

gl.drawElements(gl.TRIANGLES, this.vertexIndexBuffer.numItems,
        gl.UNSIGNED_SHORT, 0);

```

And the corresponding vertex shader:

```
// Attributes
attribute vec3 aVertexPosition;
attribute vec4 aVertexColor;
attribute vec3 aVertexNormal;

// Uniforms
uniform mat4 uMVMatrix;
uniform mat4 uNMatrix;
uniform mat4 uPMatrix;

// Varyings
varying vec4 vColor;

// Constants
const vec3 LIGHT_DIRECTION = vec3(0, 1, 0);  // Opposite direction of photons.
const vec4 AMBIENT_COLOR   = vec4 (0.2,   0.2,   0.2, 1.0);

float ComputeLighting() {
    vec4 transformedNormal = vec4(aVertexNormal.xyz, 1.0);
    transformedNormal = uNMatrix * transformedNormal;
    float base = dot(normalize(transformedNormal.xyz),
                     normalize(LIGHT_DIRECTION));
    return max(base, 0.0);
}

void main(void) {
    gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);

    float lightWeight = ComputeLighting();
    vColor = vec4(aVertexColor.xyz * lightWeight, 1.0) + AMBIENT_COLOR;
}

```

Note that I am using WebGL, so if the anser is use `glFixThisProblem(...)` any pointers on how to re-implement that on WebGL if missing would be appreciated.

## Update - Solution

With the help of folks below, I managed to get this working. There were a few things wrong about the above code:

1. The vertex shader normal should be `vec4(aVertexNormal.xyz, 0.0)` to negate the impact of rotation. This wasn't a problem in this example, but is good to keep in mind when getting to positional lighting.
2. The order of rotation/translation was wrong for the object. **Rotation always happens about the origin.** So if you want to rotate an object in place, you need to translate/rotate/translate-other-way and then translate it into its final position.
3. Once the proper model-view matrix has been constructed, clone it to act as the normal matrix. (Inverting and transposing as required.) Then multiply by the gluLookAt matrix. However, because you have already translated/rotated the object you need to multiply model-view matrix by the camera matrix with the camera on the left and the model-view matrix on the right.

If the above explanations don't help, here is the corrected code:

```
// Rotate the object about its position.
mvMatrix.translatef(this.position.x, this.position.y, this.position.z);
mvMatrix.rotatef(this.rotation.x, 1, 0, 0);
mvMatrix.rotatef(this.rotation.y, 0, 1, 0);
mvMatrix.rotatef(this.rotation.z, 0, 0, 1);
mvMatrix.translatef(-this.position.x, -this.position.y, -this.position.z);

// Now move it into place.
mvMatrix.translatev(this.position);

// Create a normal matrix based off the current model-view.
// For information on deriving the .getInverse().getTranspose() see:
// http://www.lighthouse3d.com/opengl/glsl/index.php?normalmatrix
var nMatrix = new Matrix();
nMatrix.set(mvMatrix.get().getInverse().getTranspose());

var cameraMatrix = camera.getCameraMatrix();
mvMatrix.multiplyRight(cameraMatrix);

```

# Answer
> 2 votes
It looks like you're applying the translation part of your modelview matrix to the normals?

You don't want to do that - normals should only be rotated. (You're already removing any scale that may exist in the matrix by doing an inverse transpose, but the translation is still there)

Changing the first line of ComputeLighting() to this may fix it:

```
 vec4 transformedNormal = vec4(aVertexNormal.xyz, 0.0);

```

(Setting the 4th element of the vector to 0 will cause it to add the translation component multiplied by 0, cancelling it out. You should probably use vec3s instead for normals, though. And/or set a normal matrix with the translation removed)

---
Tags: opengl, opengl-es
---


# Question
Title: Starting from Scratch - Is it a Mistake if I re-invent the wheel?
Usually whenever I want to start a game, I will think to have a good basic architecture for rendering and better game loop from scratch. I usually don't want to use existing engines. The reason behind it is that I want to implement it on my own to learn stuff.

But lot of blogs and devs say it's not a good option to go for re-inventing the wheel.

Am I missing something?

# Answer
No it's not a bad thing at all. Learning and the ability to learn is absolutely fundamental to being a good programmer.

**BUT**
The important thing when building something from scratch is to finish it to completion. It doesn't matter how hacky and unoptimized it is, if you complete it there's a sense of satisfaction like no other. It will all give you valuable experience and you can always make the code more elegant or perform better later on when you've got something functional. At the end of the day, the only things separating awesome programmers and mediocre ones are experience and practice.

Of course when you've got something done and want to create further games, there's no reason to reuse your old codebase.

If you're looking to start a career in game development, or any kind of development really, experience will take you very, very far. But if you're looking to churn out games quickly and easily (relatively easily, compared to writing your own stuff) use an existing engine.

To be honest with you, a combination of experience using your own code AND using a variety of different libraries and engines will make you a far better coder.
> 15 votes

# Answer
```
i want to implement it on my own to learn stuff.

```

That's probably the most important thing. If your goal is to learn, writing your own rendering and game loop engines from scratch is fine, and a perfectly good learning experience. If your goal is to make a finished game quickly and easily, then use an existing framework.
> 36 votes

# Answer
Reinventing the wheel teaches you how wheels work.
> 10 votes

# Answer
Depends on what you're after. If you want to learn, reinvent as many wheels you feel like. I know people who have written their own JVMs or PNG loaders for the heck of it.

Most blogs probably give advice on how to get to the stuff that get you paid quickly, but I don't know if it's a good long-term strategy. If you don't know what you're playing with, how do you know if it's a good choice? What will you do *when* you hit issues, go whining on forums, or can you figure it out yourself?
> 5 votes

# Answer
There is a lot of discouragement about this phrase in the general programing community but I think we all know that many of us love nothing more than reinventing the wheel and finding a way to make it spin a little better, faster and cooler.

New technologies are coming out all the time which need people to reinvent the wheel. OpenCL and other GPU computing languages are a good example.

You could use a framework that did include this year's new capabilities but making it on your own, if you really do the research and make improvements on what's already out there,.. you can really trek some new ground in performance and utility.

Once you have invented a few wheels to get you rolling, you know your stuff pretty well as a strong bonus!

Plus it's damn good fun.
> 4 votes

# Answer
And there are those who claim they are more productive precisely because they re-invent the wheel.

Case in point: Eskil Steenberg, creator of World of Love (excellent video where he talks about his game, his engine and *awesome* tools, and his philosophy: http://vimeo.com/18423305 )
> 1 votes

# Answer
If it is your first time, even it is just for learning, it is still better to use some kind of engine because you will learn what the engine can provide for you.

"The wheel" using in the metaphor is the concept, not the implementation. Even you will not re-invent the wheel, you still need to choose whether you will buy one or you will make one by your own. Hence, creating your own engine is not even re-inventing the wheel, it's just you want to create your own wheel for some purpose, which might be for learning, for low cost, for small size or any specific usage or requirements.
> 1 votes

# Answer
The thing is, what takes a lot of time when doing a game is the actual content and asset creation and testing - not generally writing code. That's likely why it's easy to skip that part and use an existing engine to be able to spend more time on content, game design and higher level bugs.

I think, doing stuff from scratch to learn, will generate a good feel for the work behind existing engines and improve the ability to select one later on if needed.

For fun and for learning, do whatever you fancy. If I had to write content pipeline classes from scratch, handling all the annoying details and edge cases of the file system and asset loaders I would go insane - as long as I have learned enough to have a really good grasp for how to do it, I tend to avoid doing it if someone's already done it well (though true, a lot of frameworks and engines won't fit into my own idea of "good" which would be cause to rewrite something). If I don't know how to do it, I really like doing it to completion at least once, just to grasp the finer details of whatever it is - like Ray Dey already stated.
> 0 votes

# Answer
It's only a mistake if you don't have the time to learn. If you've got the time, go for it. If you don't, then don't do it.
> 0 votes

---
Tags: architecture
---


# Question
Title: FrameBuffer Render to texture not working all the way
I am learning to use Frame Buffer Objects. For this purpose, I chose to render a triangle to a texture and then map that to a quad.

When I render the triangle, I clear the color to something blue. So, when I render the texture on the quad from fbo, it only renders everything blue, but doesn't show up the triangle. I can't seem to figure out why this is happening. Can someone please help me out with this ?

I'll post the rendering code here, since `glCheckFramebufferStatus` doesn't complain when I setup the FBO. I've pasted the setup code at the end. Here is my rendering code:

```
void FrameBufferObject::Render(unsigned int elapsedGameTime)
{
    glBindFramebuffer(GL_FRAMEBUFFER, m_FBO);
    glClearColor(0.0, 0.6, 0.5, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // adjust viewport and projection matrices to texture dimensions
    glPushAttrib(GL_VIEWPORT_BIT);
    glViewport(0,0, m_FBOWidth, m_FBOHeight);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, m_FBOWidth, 0, m_FBOHeight, 1.0, 100.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    DrawTriangle();

    glPopAttrib();
    // setting FrameBuffer back to window-specified Framebuffer
    glBindFramebuffer(GL_FRAMEBUFFER, 0);       //unbind

    // back to normal viewport and projection matrix
    //glViewport(0, 0, 1280, 768);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45.0, 1.33, 1.0, 1000.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    render(elapsedGameTime);
}

```

---

```
void FrameBufferObject::DrawTriangle()
{
    glPushMatrix();

    glBegin(GL_TRIANGLES);
        glColor3f(1, 0, 0);

        glVertex2d(0, 0);
        glVertex2d(m_FBOWidth, 0);
        glVertex2d(m_FBOWidth, m_FBOHeight);

    glEnd();

    glPopMatrix();
}

```

---

```
void FrameBufferObject::render(unsigned int elapsedTime)
{
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, m_TextureID);

    glPushMatrix();

        glTranslated(0, 0, -20);

    glBegin(GL_QUADS);
        glColor4f(1, 1, 1, 1);

        glTexCoord2f(1, 1);  glVertex3f(1,1,1);
        glTexCoord2f(0, 1);  glVertex3f(-1,1,1);
        glTexCoord2f(0, 0);  glVertex3f(-1,-1,1);
        glTexCoord2f(1, 0);  glVertex3f(1,-1,1);

    glEnd();
    glPopMatrix();

    glBindTexture(GL_TEXTURE_2D, 0);
    glDisable(GL_TEXTURE_2D);

}

```

---

```
void FrameBufferObject::Initialize()
{
    // Generate FBO
    glGenFramebuffers(1, &m_FBO);
    glBindFramebuffer(GL_FRAMEBUFFER, m_FBO);

    // Add depth buffer as a renderbuffer to fbo
    // create depth buffer id

    glGenRenderbuffers(1, &m_DepthBuffer);
    glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer);

    // allocate space to render buffer for depth buffer
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_FBOWidth, m_FBOHeight);

    // attaching renderBuffer to FBO
    // attach depth buffer to FBO at depth_attachment
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_DepthBuffer);

    // Adding a texture to fbo
    // Create a texture
    glGenTextures(1, &m_TextureID);
    glBindTexture(GL_TEXTURE_2D, m_TextureID);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_FBOWidth, m_FBOHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); // onlly allocating space
    glBindTexture(GL_TEXTURE_2D, 0);

    // attach texture to FBO
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_TextureID, 0);

    // Check FBO Status
    if( glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
        std::cout << "\n Error:: FrameBufferObject::Initialize() :: FBO loading not complete \n";

    // switch back to window system Framebuffer
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

```

Thanks!

# Answer
Everything was fine. The triangle I was rendering for the FBO was getting clipped which is why I was not seeing anything. A translate Z of -20 is all it took to get the triangle rendering properly.

A (obvious) thing I learnt: When the user FBO is not working properly, render it to the normal framebuffer and see if what you expect to show up in the user FBO, actually shows up there. If not, you have a problem in the way you are rendering to the user FBO.

Hope it helps someone.
> 4 votes

# Answer
There doesn't seem to anything inherently wrong to your code. It might be in your initialization, but you haven't posted that.

That you have a blue rectangle on the screen means your FBO is working right, your problem is in the rendering of the triangle.

Try turning backface culling into frontface culling before rendering:

```
glCullFace(GL_FRONT);

```

Alternatively, just copy a triangle from a NeHe tutorial and see if that works.

```
glBegin(GL_TRIANGLES);                      // Drawing Using Triangles
    glVertex3f( 0.0f, 1.0f, 0.0f);              // Top
    glVertex3f(-1.0f,-1.0f, 0.0f);              // Bottom Left
    glVertex3f( 1.0f,-1.0f, 0.0f);              // Bottom Right
glEnd();                            // Finished Drawing The Triangle

```

EDIT: Second stab at solving this problem. Maybe the FBO isn't initialized properly?

My own version of the FBO init code:

```
RenderTarget::RenderTarget( unsigned int a_Width, unsigned int a_Height, int a_Colors/* = 1*/, bool a_Depth/* = true*/)
{
    m_Width = a_Width;
    m_Height = a_Height;
    m_Ratio = (float)m_Width / (float)m_Height;

    // this function returns the width and height if a system doesn't have
    // non-power of two texture support
    GetTextureSizes(&m_TexWidth, m_Width, &m_TexHeight, m_Height);

    m_TextureColors = a_Colors;
    m_TextureTotal = a_Colors;
    if (a_Depth) { m_TextureTotal++; }

    m_Texture = new GLuint[m_TextureTotal];
    glGenTextures(m_TextureTotal, m_Texture);
    m_TexDepth = NULL;

    glGenFramebuffersEXT(1, &m_Target);
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_Target);

    glEnable(GL_TEXTURE_2D);

    int i = 0;
    for (; i < a_Colors; i++)
    {
        glBindTexture(GL_TEXTURE_2D, m_Texture[i]);
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
            glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_TexWidth, m_TexHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + i, GL_TEXTURE_2D, m_Texture[i], 0);
    }
    if (a_Depth)
    {
        m_TexDepth = m_Texture[i];

        glBindTexture(GL_TEXTURE_2D, m_TexDepth);

        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, m_TexWidth, m_TexHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);

        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, m_TexDepth, 0);
    }
    glBindTexture(GL_TEXTURE_2D, 0);
    glDisable(GL_TEXTURE_2D);

    GLenum status;

    status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
    if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
    {
        int i = 0;
    }
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}

```

As you can see, I attach a depth texture, not a depth render target.
> 2 votes

---
Tags: opengl, rendering
---


# Question
Title: Formula for replicating glTexGen in OpenGL ES 2.0 GLSL
I also posted this on the main StackExchange, but this seems like a better place, but for give me for the double post if it shows up twice.

I have been trying for several hours to implement a GLSL replacement for glTexGen with GL\_OBJECT\_LINEAR. For OpenGL ES 2.0. In Ogl GLSL there is the gl\_TextureMatrix that makes this easier, but thats not available on OpenGL ES 2.0 / OpenGL ES Shader Language 1.0

Several sites have mentioned that this should be "easy" to do in a GLSL vert shader. But I just can not get it to work.

My hunch is that I'm not setting the planes up correctly, or I'm missing something in my understanding.

I've pored over the web. But most sites are talking about projected textures, I'm just looking to create UV's based on planar projection. The models are being built in Maya, have 50k polygons and the modeler is using planer mapping, but Maya will not export the UV's. So I'm trying to figure this out.

I've looked at the glTexGen manpage information:

```
g = p1xo + p2yo + p3zo + p4wo

```

What is g? Is g the value of s in the texture2d call?

I've looked at the site:

Mathematics of glTexGen

Another size explains the same function:

```
coord = P1*X + P2*Y + P3*Z + P4*W

```

I don't get how coord (a UV vec2 in my mind) is equal to the dot product (a scalar value)? Same problem I had before with "g".

What do I set the plane to be? In my opengl c++ 3.0 code, I set it to \[0, 0, 1, 0\] (basically unit z) and glTexGen works great.

I'm still missing something.

My vert shader looks basically like this: WVPMatrix = World View Project Matrix. POSITION is the model vertex position.

```
varying vec4 kOutBaseTCoord;
void main()
{
    gl_Position = WVPMatrix * vec4(POSITION, 1.0);

    vec4 sPlane = vec4(1.0, 0.0, 0.0, 0.0);
    vec4 tPlane = vec4(0.0, 1.0, 0.0, 0.0);
    vec4 rPlane = vec4(0.0, 0.0, 0.0, 0.0);
    vec4 qPlane = vec4(0.0, 0.0, 0.0, 0.0);

    kOutBaseTCoord.s = dot(vec4(POSITION, 1.0), sPlane);
    kOutBaseTCoord.t = dot(vec4(POSITION, 1.0), tPlane);
    //kOutBaseTCoord.r = dot(vec4(POSITION, 1.0), rPlane);
    //kOutBaseTCoord.q = dot(vec4(POSITION, 1.0), qPlane);
}

```

The frag shader

```
precision mediump float;
uniform sampler2D BaseSampler;
varying mediump vec4 kOutBaseTCoord;
void main()
{

    //gl_FragColor = vec4(kOutBaseTCoord.st, 0.0, 1.0);
    gl_FragColor = texture2D(BaseSampler, kOutBaseTCoord.st);
}

```

I've tried texture2DProj in frag shader

Here are some of the other links I've looked up

TexGen not working with GLSL, with fixed pipeline is ok

# Answer
The scalar product is a special case of the more general matrix multiplication. In the case of

```
coord = P1*X + P2*Y + P3*Z + P4*W

```

imagine that P1 to P4 are actually vectors the same size as your texture coordinates. You can also think of P1 to P4 as columns of your object-coordinates to texture-coordinates matrix. In your case, where you want 2D coordinates, it'd be a 2x4 matrix. The columns of this matrix are what you would ordinarily submit as the planes when using `glTexGen`. The first 3 elements in each row are the direction of the respective texture axis. The length of this direction is inversely proportional to the stretch of the texture in that direction (I.e. the longer the direction, the more greater the texture coordinates and the texture will be smaller and repeat more often, if you use `GL_REPEAT`). You need to pick those direction orthogonally to your plane's normal! The last component in each row is used to move the texture around on that plane.

I'm not entirely sure that this explanation is what you're looking for, but I hope it helps.
> 0 votes

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


title: Physic engine for snooker/billard game

text:
# Question
Title: Physic engine for snooker/billard game
> **Possible Duplicate:**
> Is there an algorithm for a pool game?

I think most billard/snooker games have a lot of problems with their physic engines. They are far away from realistic and you can't really enjoy the game (especially when snooker is your hobby :) )

So I want to try to make an own physic engine (and own snooker game). I think the physic engine is the most important part of such a game. So my question is:

Do anybody know an open physic enginge I can start with? Is there any literature about such physic problems?

# Answer
There are several open source physics engines out there. Box2D is a really popular 2D physics-engine. Bullet is a popular 3D physics-engine.

I think these engines are pretty good. My guess is that the lack of realism is mostly due to a poor setup. If you plug in good values into these engines, you'll get a good simulation. Writing such an engine from scratch is going to be a huge task... but here's a question just about that. Maybe you should also consider extending an existing engine instead of writing a new one? That's the point of open source, isn't it?
> 1 votes

---
Tags: physics-engine, billiards
---


# Question
Title: What kind of data structure should I use for a resource container?
I am curious what kind of container would be the best choice for a resource container. BTree, binary search tree or something else? What like is the priority of the operations over it? So best inserting performance or best searching performance or between them?

Are there any open source implementation over the net?

# Answer
So, let's look first at your likely usage pattern.

* First, you want to be able to insert and remove in constant time. You don't want to be troubled by the number of other resources loaded.
* Second, once a resource has been loaded and queried, you can assume that whoever needs it has access to it (via smart pointer or somesuch); so, you don't have to worry about repeated banging on the manager.
* Third, you probably don't care what the order of the things in memory is.

This sounds like a perfect place to use a HashMap or something similar, mapping resource names to allocated resources.

That's the frontend, in-memory part of things. The backend on-disk solution is something else. I'd suggest using a flat pile of files, or something like PhysicsFS if you want features like a Quake-style .pak (really .zip) archive system.

Note that for some things, like textures, you want to have a way of handling losing the hardware-specific storage; for example, if a graphics card evicts your memory due to alt-tabbing or something weird you want to be able to reload it transparently. In that case, you probably will need to maintain some extra data instead of just a reference to the resource in memory.
> 4 votes

---
Tags: architecture, data-structure, assets
---


# Question
Title: What is a good alternative to Unified Shader for Shadows?
Most shadow systems I have seen use a unified shader system for shadowing techniques, resulting in an uber shader for the projects.

What alternatives do you find work well or is the unified shader the best approach?

# Answer
> 2 votes
I'm assuming your question is about shadow map-based techniques.

Generally choosing uber shaders is a higher-level decision than shadows, so shadows usually follow whatever method engine uses for rendering.

For example, you might choose using deferred rendering which requires far less permutations than traditional approach, then applying shadows will be added once to the deferred light shader and rendering shadomwap will be essentially the same path that generates G-Buffers.

Another thing I think I heard people considered is to just generate shadowmaps on SPUs without any shaders.

So decide on your method for rendering the scene and use it for shadows as well.

# Answer
> 2 votes
From what I see, you have three alternatives to uber-shaders:

1. Hand-code every shader. Obviously, this is easy if you just have a few shaders and similar lighting conditions everywhere (which might actually be the case on embedded devices). However, it quickly becomes unmanageable with even a few inputs (number of lights, shadows, different materials).
2. Deferred rendering. Effectively splits up the complexity of uber-shaders into several rendering passes. It's very nice design-wise but the memory and bandwidth requirements are high. Variations include "Light pre-pass" rendering, which does just the lighting in separate passed and gives you complete lighting information in your final compositing shader (which makes this very flexible!).
3. A shader "build-system". It'll assemble shader-permutations from smaller modular shader-fragments. The whole idea is very similar to uber-shaders, but the more modular design can make it possible to get away with a lot less permutations (since not all options in the uber-shader are orthogonal to each other). It's a pain to build such a system, and there are quite a few pitfalls - but if you get it right, it is quite a powerful tool to have if you don't want something deferred.

In the end, it depends on the specifics of your project. The bigger the project gets, the more I would steer away from hand-coded shaders or uber-shaders and pick something more modular like light pre-pass or a shader build-system. The trend is definitely going towards deferred rendering systems though.

---
Tags: graphics, shaders
---


title: Tools for images in a game

text:
# Question
Title: Tools for images in a game
Are there any tutorials , tools for creating background images, other images for an android game or iphone game?

# Answer
If you just want a good graphics program that is free, try out Paint.NET (Will require Windows or Mono) or GIMP.
> 2 votes

---
Tags: iphone, android
---


title: Restoring projection matrix

text:
# Question
Title: Restoring projection matrix
I am learning to use FBOs and one of the things that I need to do when rendering something onto user defined FBO, I have to setup the projection, modelview and viewport for it. Once I am done rendering to the FBO, I need to restore these matrices. I found:

```
glPushAttrib(GL_VIEWPORT_BIT);
glPopAttrib();

```

to restore the viewport to its old state. Is there a way to restore the projection and modelview matrix to whatever it was earlier ?

Tech: C++/OpenGL

Thanks!

# Answer
There are depricated functions `glPushMatrix` and `glPopMatrix`. I'm not sure if you have them in your version of opengl.

You can also very easily use function `glGetFloatv`. Example

```
//save matrix
glGetFloatv(GL_PROJECTION_MATRIX, &floatArray[0]);
//set matrix back
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(floatArray);

```
> 2 votes

---
Tags: opengl, matrix, projection
---


# Question
Title: Understanding DeviceContext and Shaders in Direct3D/SlimDX
I've been working through this tutorial about drawing triangles with SlimDX, and while it works, I've been trying to structure my program differently than in the tutorial.

The tutorial just has everything in the main method, I'm trying to separate components into their own classes. But I'm not sure where certain components belong: namely, contexts and shaders.

The tutorial (as it's just rendering one triangle) has one device, one swapchain, one device context and one set of shaders. intuition says that there is only one device/swapchain for one game, but with contexts I don't know.

I made a `Triangle` class and put the vertex stuff in there. Should it also create a context? Should it load its own shaders? Or should I pass some global context and shaders to the triangle class when it is constructed? Or pass the shaders and construct a new context?

I'm just getting started with 3D programming, so in addition to answering this question, if anyone knows of a tutorial or article or something about the larger-scale structure of a game, I'd be interested in seeing that as well.

# Answer
> 2 votes
You usually need one and only one device context for your application.

Generally this would live in some sort of 'Renderer' or 'Graphics' class, which would often be a singleton. This would handle initialisation/shutdown, and resetting the device on, for example, window resizing or fullscreen-windowed switches.

You really don't want a Triangle class with a Render() method and a lot of other stuff - which seems to be the direction you may be heading in? (I made this mistake with my first naive attempts at 3D rendering many years back, this really isn't good for performance!).

What you want is a 'Mesh' class that can contain an entire 3D object (hundreds/thousands of triangles) in a single vertex buffer, and draw it in as few DrawPrimitive calls as possible.

# Answer
> 1 votes
Contexts are for threading. If you're not having fun with with multithreading, just use the Immediate context. Shaders are typically, you have one set of shaders for an application, and they can be re-used for different objects. You should not have contexts *or* shaders per object.

---
Tags: c#, directx11, slimdx
---


# Question
Title: How can I create a lighting effect like this?
This is the most beautiful 2d lighting I have ever seen, and I'd like to perform lighting like this too. How do I do it?

**I don't care about the physics or how the particles are simulated** \- I only want to know about the lighting.

Here are some videos for reference:

Or you could download Polluted Planet 2 here.

# Answer
> 6 votes
It is usually called bloom, and is done by adding a blurred version of the image on top of the original. This combined with a high dynamic range can give some nice effects.

You will probably want to threshold the image before blurring, so that only really bright parts will bloom.

Outline of algorithm:

1. Render scene to texture (preferable HDR)
2. Threshold to a new texture: out = rgb\_to\_gray(pixel) \> threshold ? pixel : black
3. Blur thresholded image, or generate the whole mip chain to get glow over the whole screen
4. Add images together and do some HDR scaling to get in output range (usually RGB8)

# Answer
> 0 votes
Lots of particles with additive blending could achieve a similar effect.

# Answer
> 0 votes
Fluid Dynamics + Additive Blending + Bloom?

---
Tags: xna, lighting, hlsl
---


# Question
Title: Why do I get these errors in VS when I use OGRE_NEW?
I am trying to get more experienced with Ogre 3D and I am following the basic tutorials on the website. All the code samples compile just fine.

The first time I encountered an "error" was in Basic Tutorial 3.

The code line where Visual Studio says something is not right is

```
mTerrainGroup = OGRE_NEW Ogre::TerrainGroup(mSceneMgr, Ogre::Terrain::ALIGN_X_Z, 513, 12000.0f);

```

Visual Studio compiles this line but it shows an ugly red line beneath it and on mouse hover it says

> `#define OGRE_NEW new (__FILE__, __LINE__, __FUNCTION__) Error: no instance of overloaded 'operator new' matches the argument list" or if I mouse hover over Ogre::TerrainGlobalOptions() it says "Error: expected a type specifier`

I searched on Google but couldn't find my answer. I got about a year C++ experience but that was mainly with the WinSock libary.

Thanks in advance.

# Answer
**OGRE\_NEW** is just an overload of the operator **new**. Try to replace **OGRE\_NEW** by the normal operator **new**. If it compiles, there is a problem in the declaration of OGRE\_NEW. Otherwise, just find the problem and uses again the OGRE\_NEW operator.

Ps: if you use OGRE\_NEW, you need to use OGRE\_DELETE to remove your allocated object.
> 3 votes

---
Tags: c++, ogre
---


# Question
Title: iPhone 3GS - can't ever seem to hold 60fps with CADisplayLink
So I've switched from `NSTimer` to `CADisplayLink` and I'm still seeing unexpected variation in my frame counter - it fluctuates between 59-60fps, even when I'm not rendering much.

Has anyone else seen this? Is this an expected variation in iOS? Or should I look more closely at my game loop?

# Answer
> 6 votes
From my experience this is normal behavior. The measured time can change slightly and if 59.99 FPS are calculated and you output that with just 2 digits, it's going to show 59.

Don't worry about fluctuations of one frame.

---
Tags: iphone, game-loop
---


# Question
Title: How to organize timeline in a Flash project?
I am starting a new Flash game and I was wondering if there is a better way to organize the timeline of the project. In my previous games I define a keyframe for each possible status of the game (loading, sponsor, intro, menu, gameplay, etc...). This method works but has some problems... For instance, it is not easy to implement transitions between the different screens in the game.

How do you do this? Do you know of some better way?

# Answer
The most flexible way is to skip the keyframes altogether and implement your states (and transitions) in code. You could have a basic `GameState` class that inherits from `MovieClip` and can therefore be applied to MovieClips in your Library.

This wikipedia article might help you understand the concept of a State-Machine. Also have a look at the following question: Game State 'Stack'?
> 4 votes

---
Tags: flash
---


# Question
Title: Legal and IP considerations with publishers and playable prototypes
I'm almost ready to send a playable prototype of a game to a publisher. I've never worked with publishers. What legal or intellectual property issues should I consider at this stage (if any)?

In this specific case the publisher is well known... perhaps this makes a difference. Also the game is for a mobile platform.

# Answer
> 1 votes
Check out some of the books in the answer to Legal Resources?, specifically Business and Legal Primer for Game Development.

---
Tags: legal, mobile, publishing, intellectual-property
---


# Question
Title: Can it be considered that a frame-dependent crosshair is a flaw?
I still play counter strike 1.6/CSS these days, and as you know, when shots are fired, the crosshair expands.

When the frame rate drops, this crosshair animation is also affected by the frame rate.

Can it be considered like a programming/design flaw or is it like so for anti-cheat reasons ?

# Answer
> 2 votes
Anything you don't like *can* be considered a flaw. Who's to decide what is and what isn't?

As it happens, pretty much all your graphics are frame-dependent. You can't draw something on the screen in between frames, by definition. The only possible way around that is to use some sort of hardware overlay system but I don't know how well supported they are these days.

# Answer
> 2 votes
The crosshair animation is only a general indicator. All the physics takes place on the game server and thus is totally independent of the client's frame rate.

---
Tags: game-design, anti-cheat, frame-rate
---


# Question
Title: Problem with Ogre::Camera lookAt function when target is directly below
I am trying to make a class which controls a camera. It's pretty basic right now, it looks like this:

```
class HoveringCameraController
{
public:

   void init(Ogre::Camera & camera, AnimatedBody & target, Ogre::Real height);
   void update(Ogre::Real time_delta);
private:
   Ogre::Camera * camera_;
   AnimatedBody * target_;
   Ogre::Real height_;
};

```

HoveringCameraController.cpp

```
void HoveringCameraController::init(Ogre::Camera & camera, AnimatedBody & target, Ogre::Real height)
{
   camera_ = &camera;
   target_ = ⌖
   height_ = height;

   update(0.0);
}

void HoveringCameraController::update(Ogre::Real time_delta)
{
   auto position = target_->getPosition();
   position.y += height_;
   camera_->setPosition(position);
   camera_->lookAt(target_->getPosition());
}

```

AnimatedBody is just a class that encapsulates an entity, it's animations and a scene node. The getPosition function is simply forwarded to it's scene node.

What I want(for now) is for the camera to simply follow the AnimatedBody overhead at the distance given(the height parameter), and look down at it. It follows the object around, but it doesn't look straight down, it's tilted quite a bit in the positive Z direction. Does anybody have any idea why it would do that?

If I change this line:

```
position.y += height_;

```

to this:

```
position.x += height_;

```

or this:

```
position.z += height_;

```

it does exactly what I would expect. It follows the object from the side or front, and looks directly at it.

# Answer
> 2 votes
I found a simple solution to my problem using quaternions.

```
const Ogre::Real sqrt_one_half = 0.7071067811865475244; // Square root of 1/2
camera_->setOrientation(Ogre::Quaternion(sqrt_one_half,-sqrt_one_half,0.0,0.0));

```

Also, why the hell am I setting the rotation every update? I should just do it once in the init function, and then only modify the position in the update function. Here's my updated code, if anyone is interested:

```
void HoveringCameraController::init(Ogre::Camera & camera, AnimatedBody & target, Ogre::Real height)
{
    camera_ = &camera;
    target_ = ⌖
    height_ = height;

    auto p = target_->getPosition();
    p.y += height_;
    camera_->setPosition(p);

    const Ogre::Real sqrt_one_half = 0.7071067811865475244; // Square root of 1/2
    camera_->setOrientation(Ogre::Quaternion(sqrt_one_half,-sqrt_one_half,0.0,0.0));
}

void HoveringCameraController::update(Ogre::Real time_delta)
{
    auto p = target_->getPosition();
    p.y += height_;
    camera_->setPosition(p);
}

```

# Answer
> 6 votes
I believe you are feeling the effects of Gimbal lock. 3D camera implementations typically do not allow for looking directly up or down because of this (because then the forward and up vectors would be parallel). I know from experience that OpenGL can do strange things, and my simple implementation of a camera doesn't allow for less than a 0.1-degree angle up or down.

If you can modify the camera's "up" vector to be something other than (0,0,1), then you should do so when you want to set its forward vector to (0,0,1) (i.e. when you want to look up). The forward and up vectors cannot be the same, though.

Other alternatives include making sure the 'up' vector is orthogonal to the 'forward' vector at all times, or using quaternions. I don't know how these options apply to the Ogre3D engine, sorry.

---
Tags: c++, ogre
---


# Question
Title: Tile-based 2D collision detection problems
I'm trying to follow this tutorial http://www.tonypa.pri.ee/tbw/tut05.html to implement real-time collisions in a tile-based world.

I find the center coordinates of my entities thanks to these properties:

```
public float CenterX
{
    get { return X + Width / 2f; }
    set { X = value - Width / 2f; }
}
public float CenterY
{
    get { return Y + Height / 2f; }
    set { Y = value - Height / 2f; }
}

```

Then in my update method, in the player class, which is called every frame, I have this code:

```
public override void Update()
{
    base.Update();

    int downY = (int)Math.Floor((CenterY + Height / 2f - 1) / 16f);
    int upY = (int)Math.Floor((CenterY - Height / 2f) / 16f);
    int leftX =     (int)Math.Floor((CenterX + Speed * NextX - Width / 2f) / 16f);
    int rightX = (int)Math.Floor((CenterX + Speed * NextX + Width / 2f - 1) / 16f);

    bool upleft = Game.CurrentMap[leftX, upY] != 1;
    bool downleft = Game.CurrentMap[leftX, downY] != 1;
    bool upright = Game.CurrentMap[rightX, upY] != 1;
    bool downright = Game.CurrentMap[rightX, downY] != 1;

    if(NextX == 1)
    {
        if (upright && downright)
           CenterX += Speed;
        else
           CenterX = (Game.GetCellX(CenterX) + 1)*16 - Width / 2f;
    }
 }

```

downY, upY, leftX and rightX should respectively find the lowest Y position, the highest Y position, the leftmost X position and the rightmost X position. I add + Speed * NextX because in the tutorial the getMyCorners function is called with these parameters:

```
getMyCorners (ob.x+ob.speed*dirx, ob.y, ob);

```

The GetCellX and GetCellY methods:

```
public int GetCellX(float mX)
{
    return (int)Math.Floor(mX / SGame.Camera.TileSize);
}
public int GetCellY(float mY)
{
    return (int)Math.Floor(mY / SGame.Camera.TileSize);
}

```

The problem is that the player "flickers" while hitting a wall, and the corner detection doesn't even work correctly since it can overlap walls that only hit one of the corners. I do not understand what is wrong. In the tutorial the ob.x and ob.y fields should be the same as my CenterX and CenterY properties, and the ob.width and ob.height should be the same as Width / 2f and Height / 2f. However it still doesn't work.

Thanks for your help.

# Answer
> 1 votes
A couple of suggestions, although I'm not sure they will fix the problem as I don't have full code to run and debug.

In this code:

```
if(NextX == 1)
{
    if (upright && downright)
       CenterX += Speed;
    else
       CenterX = (Game.GetCellX(CenterX) + 1)*16 - Width / 2f;
}

```

the else statement is moving the object even though the object should not be moving.
I guess you are trying to make the object flush against the wall but maybe the calculation is incorrect.
If you comment out the else statement, does the object still flicker?

The calculation does look a bit suspicious as it subtracts (Width / 2f) and then the CenterX set operator does the same subtraction again.

Another thing I'd like to point, just to help the clarity of the code, is that you made the properties for CenterX calculate the value back and forth, but the code is still littered with the same calculation over and over again.
This might well be part of the problem. Either way, I'd suggest making a few more properties and settling on one standard for all of them. For example, make the Center be the property stored and calculate the others from it:

```
public float CenterX
{
    get { return X; }
    set { X; }
}

public float LeftX
{
    get { return CenterX - Width / 2f; }
    set { CenterX = value + Width / 2f; }
}

public float RightX
{
    get { return CenterX + Width / 2f; }
    set { CenterX = value - Width / 2f; }
}

```

---
Tags: 2d, c#, collision-detection, tiles
---