# Question
Title: Spawning units in a world made by Perlin noise?
There's some issues that I've come across in my Perlin noise-based game. Take a look at the attached screenshot below.

The white areas you see are walls, and the black areas are walkable. The triangle in the middle is the player.

I've implemented physics in this game by drawing it onto a texture (white or black pixels), and then getting that from the CPU.

However, now I stand with a different problem at hand. I want units (or creeps, whatever you call them) to spawn constantly, at the edge of the screen. The point here is that in the final game, there will be a "fog of war" that doesn't allow the player to see that far anyway.

I figured that I could just scan the pixels at the edge of the screen and see if their physics texture is black, and then spawn stuff randomly there. However, if you take a second look at the screenshot, there is (in the upper-left corner) an example of where I wouldn't want the creeps to spawn (since they wouldn't be able to reach the player from there).

Is it possible to somehow have the GPU determine these spawn-spots for me, or some different way? I thought about making vectors between the proposed point at the edge of the screen and the player, and then following it every 10 voxels, and see if a wall collides, before spawning a unit there.

However, the above proposed solution may be too CPU intensive.

Any suggestions on this matter?

**Note 1** For the units spawned, I do not want to be using any form of pathfinding to avoid wall collisions as these units run towards the player. Therefore, the units must spawn at the edge of the screen, at a location where walking in a straight line towards the player would **not** collide with any walls.

# Answer
There's a pretty useful algorithm for this job, much more efficient than the flood algorithm in this situation (its complexity is runtime is proportional to the boundary size rather than the flooded area): it's the marching squares algorithm. The concept is simple: start off the players location (screen midpoint), choose a direction and walk until you find a wall. When you collide with the wall, you start the algorithm: you choose an orientation (up or down) and start marching over the boundary of this area, highlighting the pixels. This give you the inner boundary for the allowed area. Afterwards, you simply check whether the candidate points for spawning units lie on this boundary.

This is the principle you should follow for running the boundary:

http://en.wikipedia.org/wiki/File:Marchsquares.png (meh I can't post pics yet)

Wikipedia description (although it has alot more complexity because it's used with other applications in mind):

http://en.wikipedia.org/wiki/Marching\_squares
> 3 votes

# Answer
Make a flood fill from the player's position; every area "flooded" is then a valid play area, and all others are walls.

EDIT: As to the "reachable in a straight line" additional requirement, keep in mind that in a *discrete space*, you have to define this a bit further. For example, all of the paths above could be a valid "straight line" in such an environment, and I've seen all of them used in a game at some point or another:

In particular, most of those *aren't commutative* \- which means just because you can reach B from A in a "straight line" doesn't mean you can also reach A from B; neither is the opposite necessarily true.

In addition, there's the question on how do you handle diagonal movement if one or both of the "side" points is blocking.
> 10 votes

# Answer
How about just letting the spawns happen? I don't see any particular problem in that.
> 1 votes

# Answer
if it's important for you to only mark points with a valid straight line to the player you can use an algorithm like the following (it's a c++ code), it consumes more than than normal floodfill. there may be some minor bugs (I'll be glad if anyone corrects them) since i didn't test the code myself but you'll get the idea.

```
void straightlineFill(Point startPoint, Texture target)
{
    queue<Point> pointQueue;
    for (int dx = -1;dx <=1;dx ++)
            for(int dy = -1;dy <=1;dy++)
                if(dx != 0 && dy != 0)
                    pointQueue.push(point(startPoint.x + dx, startPoint.y + dy));
    while (!pointQueue.empty())
    {
        point front = pointQueue.front();
        pointQueue.pop();
        if (target.pixelAt(front) == COLOR_SPAWNABLE||
            target.pixelAt(front) == COLOR_WALL||
            target.pixelAt(front) == COLOR_NOT_SPAWNABLE)
                continue;
        taraget.setPixelAt(front, colorFilled);
        for (int dx = -1;dx <=1;dx ++)
            for(int dy = -1;dy <=1;dy++)
                if(dx != 0 && dy != 0)
                    pointQueue.push(point(front.x + dx, front.y + dy));
        // up until now was the normal floodfill code
        // and here is the part that will do the real straight line checking

        // lineDX & lineDY will keep how much the line we are checking is skewed
        int lineDX = front.x - startPoint.x;
        int lineDY = front.y - startPoint.y;

        // step will show us how much we have to travel to reach each point of line
        point step;
        if (abs(lineDX) < abs(lineDY))
        {
            if (lineDX < 0)
                step = point(-1,0);
            if (lineDX == 0)
                if (lineDY < 0)
                    step = point(0,-1);
                else
                    step = point(0,1);
            if (lineDX > 0)
                step = point(1,0);
        }

        if (abs(lineDX) < abs(lineDY))
        {
            if (lineDY < 0)
                step = point(0,-1);
            if (lineDY == 0)
                if (lineDX < 0)
                    step = point(-1,0);
                else
                    step = point(1,0);
            if (lineDY > 0)
                step = point(0,1);
        }

        // moved will keep how much we have traveled so far, it's just some value that will speed up calculations and doesn't have any mathematical value
        point moved = 0;

        // spawnable will keep if the current pixel is a valid spawnpaint

        bool spawnable = true;

        // now we will travel on the straight line from player position to the edges of the map and check if whole line is valid spawn points or not.

        while (target.isInside(front))
        {
            front = front + step;
            moved = moved + point(step.x * lineDX, step.y * lineDY);
            if (step.x != 0 && moved.x < moved.y)
            {
                moved.x = moved.x - lineDY * sign(lineDY);
                front.y = front.y + sign(lineDY);
            }
            if (step.y != 0 && moved.y < moved.x)
            {
                moved.y = moved.y - lineDX * sign(lineDX);
                front.x = front.x + sign(lineDX);
            }

            if (target.getPixelAt(front) == COLOR_WALL)
                spawnable = false;

            if (spawnable)
            {
                target.setPixelAt(front,COLOR_SPAWNABLE);
                for (int dx = -1;dx <=1;dx ++)
                    for(int dy = -1;dy <=1;dy++)
                        if(dx != 0 && dy != 0)
                            pointQueue.push(point(front.x + dx, front.y + dy));
            }
            else
            {
                target.setPixelAt(front,COLOR_NOT_SPAWNABLE);
            }
        }
    }
}

```
> 1 votes

# Answer
You can fill the map with colors that represents convex areas..., this way you can spawn your unit if lies in the same area. Or you can search easier for reachable areas.

This is static data so you can precalc it.

you had to fill the image finding points where there is a change from convave to convex, visually it's seems easy to find, you have two situations:

1. Horizontal: Where orange to blue changes.
2. Vertical: Where red changes ot green and orange.
> 1 votes

# Answer
Here is something that I actually used in my own game (2d simplex noise generated world, almost exactly like yours)- Rays. Start at the player, determine a orientation (random if you want), and go along that line until you hit something (edge of screen OR asteroid). If you hit the edge of the screen (and not a asteroid/white blob), then you know there is a straight, open line from the edge of the screen to the player. Then spawn a monster at the point you hit. If you hit an asteroid, re-do the test.
> 1 votes

# Answer
Another (non-GPU) solution you can use is path-finding. Before drawing the map, path-find from each potential spawn-point at each edge of the map and see if there's a path to the center. A\* path-finding is pretty OK on cost/performance, but you can do this before the game starts if that's an issue.

Any spawn point that doesn't have a path can be put on an exclusion list; or vice-versa (any point with a path can be put on an inclusion list).
> 0 votes

---
Tags: xna, path-finding, hlsl, gpgpu
---


# Question
Title: Advice of feasibility of final year project
Final year student from an IT college in Ireland. I'm not really sure if this is the right place to post but It seems that graphics programming is very closely related to games and the people here would have the most insight.

So just an introduction to myself and the problem. Basically Im in my final year of my degree and rather than do a thesis we do a final year project that has to be crisp.

My primary language is Java and I've used it many times in the past. It is not a language I would say I love but it is easily my strongest. I've also used Ruby on rails for an internship i got this summer and I have a good grounding on the web side of things. I've also done some very basic c++ (what i would consider basic). My c++ skills basically comes down to different tutorials on things that other languages are based on. E.g heres a lab sheet on containers, pointers, operator overloading or something from the STL. It was more a module to develop our analytical thinking than experience with c++. C++ was just the medium for learning.

My opinion on the language? C++ is an amazingly diverse one size fits all language and its no surprise its around this long. My skills in it are basic at best and could use a mountain of polish. No experience in advanced memory management or any UI frameworks.

And now to the project. Every year the final year students pick a project of choice and if it has some interesting functionality and satisfies a certain difficulty level then its approved. This year however they have gone a different approach due to some very lazy approaches from students in the past. Fair enough I thought.

Well I got my project assigned today. Sure enough I was expecting a project based on my strengths, some sort of db, maybe restful services or a cloud App since those are the buzz words these days.

So the sheet was being passed throughout the lecture hall with the list, every few seconds i would notice someone look to me and snicker or look horrified.

I'm sure by this point you've guessed the project. Your just that smart.

A blood flow physics simulator from a human organ based on nvidia's Cuda....

My jaw literally hit the floor and I said WTF aloud. Not my brightest moment. So we've gone from students making lazy decisions to lecturers just crapping out projects handing us a fork and saying eat it...... but i digress.

If I wasn't up to the task of this then why would I be here asking this question?

The reason is as shocked as I am about this. I don't like to lose. I have my own queries on how appealing this project would be to someone looking to hire me as there doesn't seem to be a lot of jobs going for organ blood flow coders. This is something I will be discussing with my lecturer in depth first but if anyone has any comments on that side of things then I'm happy to hear them.

The main point of the question is the feasibility of getting a decent working project out of this though. I could do 2-3 weeks of research and still not come up with any conclusive results on whether this project is the right way to go.

There is no finite answer to this question, just any experienced advice on what route to pick and what resources to go for.

By this I mean I've always heard that graphics programming is hard. So for someone with basic c++ skills and an OK level of discrete mathematics, is it feasible to complete this project spec or is it the equivalent of shooting myself in the legs and stuggling to crawl past the finish line?

---

Assuming the answer isn't 'go blast your lecturer for giving you this project'

What resources should i seek out to make this not just a passable project but one that'll be demo-able and I can stand proud beside.

What advice can you give to someone like me that you wish someone had told you?

Absolutely any opinion of debate on this topic is appreciated as I'm fairly lost on what to do.

Thanks for reading my rant and I'll finish up here. Look, I'm good at Java but its not the best thing in the world. I'm OK at C++ but its one language I would really like to explore and make my primary language. (assuming there are jobs for grads in this area)

This project will most likely define the career I take and the language that I base my first decade of programming on. This is important to me so please do not dismiss it as another student who likes games and wants to code them. I'm a hungry young developer and intend to stay that way.

# Answer
> 3 votes
Presumably there is a reason *you* got that assignment. If your lecturer thinks you will grow a new pair of limbs by being shot in the legs, perhaps that's why he did it. The best projects for learning, IMO, are the hard projects. No pain, no gain. That sounds like by far one of the coolest projects out of any that were probably handed out -- even games -- because that's some pretty hardcore tech you'll be dealing with it.

Take it on the jaw, and start learning now (not tomorrow). Find the right online sources for learning and support, and get some good books.

Out of the numerous fields I've touched on as a professional developer (not just games), computational geometry, graphics and physics are some of the most interesting by far.

In my final year of uni, there were two game projects: our project (myself and a partner), and another (a group of three). Although visually not nearly as impressive as the other project, ours took top marks for the year. Why? Because we wrote it from the ground up, engine included, whereas they used a prebuilt engine. That was a long time ago, and the landscape of game development has changed enormously, but it's a lesson in the benefits of taking the hard road.

# Answer
> 3 votes
> Would experience coding a `A blood flow physics simulator from a human
>  organ based on nvidia's Cuda` would be worthwhile industry experience.

Yes.

It may not be the blood flow simulation that gets you `experience` as such, but the implementation of the application to a worthwhile standard. I imagine its to that effect you are graded on the project aswell.

> There is no finite answer to this question, just any experienced advice on what route to pick and what resources to go for.

This is a Q&A site, perhaps you wanted chat or forums.

> This project will most likely define the career I take and the language that I base my first decade of programming on.

It shouldn't, only the experience you get in developing the project should.

*P.S*

This *may* be more suited for the Programmers stack exchange, its relevance to Game Development is only the use of the GPU...

# Answer
> 0 votes
You can always go 2D instead of 3D to make things easier.

Cuda is C like so that could be a nice experience too, don't give up ;-)

\[edit\] you can surely dig up an example of something likewise too (check out the Gpu Gems books, (a fast search gave me this link:) Gpu gems 1, gpu gems 2 and specially gpu gems 3)

# Answer
> 0 votes
This thesis (from a friend) on Particle Tracking on a GPU should give you a few basic insights on what is necessary when doing GPU work. This was a MSc Engineering final work.

OpenFOAM is often used for blood flow simulations, see GPU-based simulation of 3D blood ﬂow in abdominal aorta using OpenFOAM.

Remember to cite your sources if you use these as a base!

---
Tags: c++, graphics, nvidia
---


title: Quaternion understanding

text:
# Question
Title: Quaternion understanding
I have some understanding problem concerning quaternions.

In order to have my world object rotate in the correct way, I need to invert their quaternion rotation while refreshing the object world matrix.

I create the object rotation with this code:

```
Rotation = Quaternion.RotationMatrix(Matrix.LookAtRH(Position, Position + new Vector3(_moveDirection.X, 0, _moveDirection.Y), Vector3.Up));

```

and refresh the object World matrix like this:

```
Object.World = Matrix.RotationQuaternion(Rotation) * Matrix.Translation(Position);

```

This is not working; it makes the object rotate in the opposite way compared to what it should!

The is the way that makes my object rotate correctly:

```
Object.World = Matrix.RotationQuaternion(Quaternion.invert(Rotation)) * Matrix.Translation(Position);

```

Why do I have to invert the object rotation?

# Answer
> 3 votes
```
Is there a straight forward way to create a quaternion from Position + Target vector

```

Yes, you will also need the up-vector though. look at my answer here

# Answer
> 2 votes
take a look to my answer about use of quaternions to rotate objects. You can find a way to compute the quaternion based rotation matrix after the \[edit\] section

---
Tags: rotation, quaternion
---


# Question
Title: XNA - Getting HLSL pixel of current render target?
I'm setting a render target in XNA using the following lines of code:

```
        Game.GraphicsDevice.SetRenderTarget(physicsTexture);
        Game.GraphicsDevice.Clear(Color.White);

        noiseEffect.CurrentTechnique.Passes[0].Apply();

        DrawQuad();

        Game.GraphicsDevice.SetRenderTarget(null);

        physicsTexture.GetData<Color>(physicsBuffer);

```

Now, physicsTexture is a RenderTarget2D. This texture already has some of its pixels colored by the CPU before it gets set as the render target.

So when my pass in the HLSL pixel shader runs, my question is: Can I get the current pixel color of a given texture coordinate using tex2D or something similar on the render target, before drawing a new pixel at that area?

# Answer
> 6 votes
Unfortunately no. You cannot read from the current render target in a shader. You have two basic options:

1. If the operation you would do with the read fragment color is simple enough that you can achieve it using blend state operations, you can use those.
2. You can pass the color data you need into shader via some other resource, for example, a texture containing a copy of the framebuffer prior to execution of the render pass that you're currently in, which can be read as a normal texture.

---
Tags: xna, hlsl, fragment-shader
---


# Question
Title: How to find which side of a collider has been hit from hit.normal?
In Unity3D, I can get the normal of the surface with which the collider collides using `hit.normal`, but is there a way to find which side has been hit with what is provided by Unity3D?

One solution is to see the orientation of the normal, and should work well for static objects but what about dynamic and moving objects whose orientation changes?

# Answer
> 2 votes
Try the following: Translate the hit.normal into the local space of your collider (via InverseTransformDirection), then compare the sign of the vector coordinates to the local directions.

---
Tags: unity, collision-detection
---


# Question
Title: How do I export an animated scene with a rigged character and dds textures to blender from 3DSMAX 7?
Which format should I use, which settings? Which plugin or script?

# Answer
This might get you started.

http://www.katsbits.com/tools/
> 1 votes

---
Tags: blender, 3dsmax
---


title: How did they do it: Trine 2.5d terrain?

text:
# Question
Title: How did they do it: Trine 2.5d terrain?
How did they make the terrain in trine? I think they took a polygon approach. It doesn't seem that they used a heightmap because it is in all three vectors, or a voxel method because it doesn't have overhangs and cliffs. If it is polygon-based (I assume it is), how in the world would you texture the whole thing?

Notice how it's not very symmetrical and has lots of depth:

# Answer
> 3 votes
They use the same models again and again in Trine. They use a lot of batched rendering. Because of their unique camera angle, a lot of the meshes get culled with frustum culling.

The levels are hand-made by artist. They are just very good at re-using the same models over and over again.

# Answer
> 7 votes
It looks like any regular 3D model. The only thing that's "2.5D" about it is the fixed camera and play space.

# Answer
> 0 votes
The terrain is built as separate meshes by the artist, and possibly have a separate level designer to place the meshes for making the levels. They are just so well-modeled to give the impression that it's one continuous terrain.

In some respects it's really a 2D puzzle action game, making the design and programming of the game logic easier than fully 3D games. The level designer is restricted to just placing the objects along a 2D plane.

---
Tags: procedural-generation, terrain, terrain-rendering
---


title: Weird white outline around model

text:
# Question
Title: Weird white outline around model
I'm working on a game in XNA 4 and I recently switched to a deferred shading implementation following this guide. A strange white outline is showing up on my models now and I'm not sure whats causing this. I thought maybe it was a lack of precision on the normal render target or the depth render target but increasing them to 64 bits (Rgba64) instead of 32 (Color) didn't help. I also thought it might be some problem with the specular calculation so I tried setting the specular to 0 but that didn't help either. Debugging the pixel in PIX shows the diffuse value is being calculated as nearly white for that pixel. Any ideas? I included a picture of the problem below, it's easier to see it at full size.

Pixel Shader:

```
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    input.ScreenPosition.xy /= input.ScreenPosition.w;

    float2 texCoord = 0.5f * (float2(input.ScreenPosition.x, -input.ScreenPosition.y) + 1) - halfPixel;

    float4 normalData = tex2D(normalSampler, texCoord);

    //Transform normal back into [-1, 1] range
    float3 normal = normalize(2.0f * normalData.xyz - 1.0f);

    float specularPower = normalData.a;
    float specularHardness = tex2D(colorSampler, texCoord).a * 255;
    float depthVal = tex2D(depthSampler, texCoord).r;

    //Compute screen-space position
    float4 position = float4(input.ScreenPosition.xy, depthVal, 1.0f);

    //Transform to world space
    position = mul(position, InvertViewProjection);
    position /= position.w;

    //Surface-to-light vector
    float3 lightVector = lightPosition - position;

    float3 projectedTexCoords = position - lightPosition;
    projectedTexCoords = mul(projectedTexCoords, float3x3(
                            float3(-1, 0, 0),
                            float3(0, 1, 0),
                            float3(0, 0, 1)));

    float distanceToLight = length(lightVector) / lightRadius;
    float shadow = ShadowContribution(projectedTexCoords, distanceToLight);

    float attenuation = saturate(1.0f - distanceToLight);

    lightVector = normalize(lightVector);

    //Compute diffuse light
    float normalDotLight = max(0, dot(normal, lightVector));
    float3 diffuseLight = normalDotLight * Color.rgb;

    float3 reflectionVector = normalize(reflect(-lightVector, normal));
    float3 directionToCamera = normalize(cameraPosition - position);
    float specularLight = specularPower * pow(saturate(dot(reflectionVector, directionToCamera)), specularHardness);

    return shadow * attenuation * lightIntensity * float4(diffuseLight.rgb, specularLight);
}

```

**Edit**: Sorry about the JPG, stackexchange's uploader did that on its own. Roy T: I did actually reference your XNA4 conversion of the tutorial for the parts that changed from XNA3. Since I didn't make any big changes to the code I thought maybe this bug existed in the original but was just impossible to see with so many lights all moving around, so I removed all but one light and the bug showed up again (look near the lizard's elbow)

Here are the GBuffer contents for my scene:

Color Buffer: Depth Buffer: Normal Buffer: Final Render:

**Edit2**:

I'm starting to suspect the problem is CombineFinal.fx when it samples the color map. This is the computation for a properly colored pixel right next to a white pixel:

```
diffuseColor        : (0.435, 0.447, 0.412)
diffuseLight        : (1.000, 1.000, 0.902)
light               : (1.000, 1.000, 0.902, 0.000)
PixelShaderFunction : (0.435, 0.447, 0.371, 1.000)
specularLight       : 0.000

```

And this is the output from an improperly colored white pixel directly next to it:

```
diffuseColor        : (0.824, 0.792, 0.741)
diffuseLight        : (1.000, 1.000, 0.902)
light               : (1.000, 1.000, 0.902, 0.000)
PixelShaderFunction : (0.824, 0.792, 0.669, 1.000)
specularLight       : 0.000

```

The diffuseColor is the only difference, and this color is taken directly from the color map. Perhaps there is a slight error in the computation of the texture coordinate to sample from?

Lighting Pass:

# Answer
> 4 votes
I had this white outline or "halo" around my models too, when I started on my own deferred renderer. The problem was that the texture offset value for overlaying the render targets was not setup correctly. Some textures needed to be set to +0.5 pixels for the offset instead of -0.5 pixels.

It was only after tweaking values of some of the texture offsets that the outlines were gone. Most likely it's in one of the lighting shaders.

Edit: by the way I also learned from Catalin Zima's tutorial which is a branch off of your example, so it should work.

# Answer
> 0 votes
I'm not sure exactly what's going on, but a couple of things to double-check:

1. Make sure you've got texture filtering turned off when sampling the G-buffers - no bilinear or anisotropic or anything.
2. I see you're adding a half-pixel offset to the texture coordinates; double-check that that's right. I'm not familiar enough with XNA to know what the right offset should be, but you should be able to check it by writing a shader that samples one of the G-buffers and just outputs the sample. Then flip back and forth between this and displaying the G-buffer directly on-screen. If you've got the correct offset, you should see no differences, not even a single pixel.

---
Tags: xna, hlsl
---


title: shadowing billboards

text:
# Question
Title: shadowing billboards
I have a lot of billboarded 3D spheres (they have a heightmap so work properly with depth and penetration; although each is made of just a quad (with slight distortion), they look and feel and are true 3D spheres): http://www.youtube.com/watch?v=88idbFlvQV0

The choice of using billboards is for throughput on low-end hardware.

How can I effectively cast shadows from these? It occurs to me that using proper shadow-volumes will take a lot of fill-rate and complexity. I am fill-rate sensitive.

I was wondering if there is any way to billboard the shadows cast by my billboards?

# Answer
Yes, it's very possible. And should suit your needs for speed well, as this used to be common practice amongst older games.

A very good reference is the old tome by André LaMothe: Tricks of the 3D Game Programming Gurus (Chapter 14).

The basic jist of it is to simply project a shadow version of your billboard onto the floor. A more advanced version for arbitrary Meshes can be found Here
> 5 votes

# Answer
It sounds like your billboarded spheres are outputting depth when you draw them into the main view, so you could use shadow mapping and just draw them into the shadow map exactly the same way.
> 3 votes

# Answer
Do you have access to programmable shaders? If you do, setting a depth map to project sphere shadows would work easily.

What you need to do is set an alpha mask texture (if you're not using one already) for the billboards and in the shader if the alpha value from the texture is less than 1, tell the shader to *discard* the pixel/fragment. That way the pixels don't get counted towards the rendering of the depth map and they will show up clearly as circles instead of squares when you don't check for alpha.
> 3 votes

---
Tags: opengl, glsl, shadows, billboarding
---


# Question
Title: 2d very large tile based game, zoom and pan considerations
what's a sensible way of implementing zoom and panning for my game?

each tile is very large, 100,000 x 100,000 pixels, with some objects possibly being only a single pixel at maximum zoom (small objects in a vast vast space).

I want to be able to zoom out so the view encompasses the entire chunk/tile, possibly two chunks if objects are near the border, I also want to replace the image used for the objects with an icon past a certain level of zoom.

I'd like to have this drawn on a jpanel in an applet with a swing based ui. graphically I was aiming to keep it simple and just use graphics2d functions. should I be looking at using LWJGL or is this overkill.

I realise these sorts of questions get asked a lot, but I'm concerned there are special considerations for having such large tiles.

Thanks

# Answer
> 1 votes
Tiles are a way to stretch large or repeatable data from a massive file onto a display. The only reason to use tiles is to increase that efficiency.

**Solution A:**

Make your original tiles far smaller, and use a simple tile only to outside screen boundaries system. Although I have a fairly good idea what you're trying to do, and this won't work.

**Solution B:**

Every X interpolation. Let's assume we have enough memory to store **4** notice I didn't say **2**, when the user is in a corner of one tile, you will need to render **4** tiles. (1) the tile the user is in then the (3) possible tiles that could be moved to in one screen.

Now let's pretend we are maximum possible zoom on one tile, we are so close that one pixel on the tile = one pixel on the screen.

```
int ScreenPositionX = -1;
int ScreenPositionY = -1;
for(int X = TopLeftPixel.X; X < BottomRightPixel.X; X++)
{
     ScreenPositionX++;

     for(int Y = TopLeftPixel.Y; Y < BottomRightPixel.Y; Y++)
     {
          ScreenPositionY++;
          PutPixelOnScreen[ScreenPositionX, ScreenPositionY] = GetPixelFromMemory[X, Y]
     }
}

```

So we keep track of which pixel we are putting on screen (blitting) and the location we are at in the texture. We start the **for** loops at the top left pixel of the texture to be drawn, and we iterate through to the last (bottomright) pixel of the texture to be drawn.

But once the user zooms out to a ratio of say 10 pixels on the tile = 1 pixel on the screen, we need to handle what should and shouldn't be drawn. The easiest method is to simply skip pixels: (assuming you can find the topLeft and bottomRight * scale pixels)

```
int ScreenPositionX = -1;
int ScreenPositionY = -1;
int SkipTen = 10;        //This is our scale value, 10 on texture = 1 on screen
for(int X = TopLeftPixel.X; X < BottomRightPixel.X; X += SkipTen)
{
     ScreenPositionX++;
     for(int Y = TopLeftPixel.Y; Y < BottomRightPixel.Y; Y += SkipTen)
     {
          ScreenPositionY++;
          PutPixelOnScreen[ScreenPositionX, ScreenPositionY] = GetPixelFromMemory[X, Y]
     }
}

```

That's the simplest way, and has little overhead. You complicate things more if some pixels should be represented always over others. Say in a 10 pixel space you have one black pixel, the rest white. You could choose of the 10 pixels which has the highest count and represent the pixel as that color, but then we lose our black pixel. So we can instead check if there is a black pixel in those 10, to always draw black. You can complicate things more by converting this into a symbol on screen after a certain zoom ratio has been reached. Keep in mind this kind of a realtime system starts to slow down quite quickly if you throw in averaging, weighted systems for every pixel to be drawn. Ideally the textures should be prerendered to depth, or if this is a gargantuan system like google maps, you could render on demand and save renders.

Also sorry this isn't in java, it's not my language, but the concepts are all there. I can clear up anything just comment questions.

# Answer
> 1 votes
You could use the same algorithm as the one used by Google Maps or Giga pixel, ie : have different resolution of your image, and only load the image corresponding at both your position and zoom level.

so for example when you're at maximum zoom, you display a detailed 512x512 image, and whent you zoom out, blend with another 512x512 image with a different view.

---
Tags: java, tiles
---


title: Pros & Cons on different game engines

text:
# Question
Title: Pros & Cons on different game engines
I've been working with the XNA-Framework(only in 2D) for over a year now. Now I want to try and start a bigger 3D-project. But somehow I have difficulties to decide which engine/Framework I should use. So far I gathered three possible Frameworks, I want to list here:

1. XNA with the OX-engine: I already have some experience with XNA and the Ox-engine seems to be the best possible open source engine I could use here.
2. OGRE-engine: Always wanted to get a little deeper into C++ and the engine seems to be well documented.
3. Cryengine/Sandbox 2 or higher: Well this one also needs C++ knowledge, seems to be user friendly and lets face it one of the most powerful engines out there.

My goals are to start learning 3D-programming and to realize first 3D projects by taking baby steps.

So the question is what engine would you guys recommend? Is there any other stuff I have overseen? as mentioned before getting a little more into C++ would be great to but it is not a "must have" as I alredy worked with C/C#. Most important to me would be that I could lear stuff that I can use later on for example in other Frameworks. This is important to me because I want to get deep into one thing I will be doing for a long time.

Thanks in advance!

# Answer
> 2 votes
It really depends on what you want to do. Is it a game? Then use an engine like Unity. If you want to learn 3D programming and math from the ground, writing your own tech demos could work. Remember that engines are tools, nothing more, nothing less.

The DirectX vs OpenGL doesn't matter, pick one, learn it and you will easily change to the other. If you want to learn one of these start your own demo project from scratch, but don't expect being able to finish a game with it. If you just want to learn the graphics programming part of it, using any tool that supports writing shader code directly will work. Like Unity support Cg.

Note also that Cryengine is only just released. It doesn't have a large community or documentation yet. Unreal, while maybe more limited, does give you that.

# Answer
> 1 votes
For starting, begin with free version of Unity3d, and start learning DirectX 11 or OpenGL in parallel.

# Answer
> 0 votes
You could use Unity3D, you can write your script in C#.

I haven't seen the Ox-engine before, but it seems that the last source checkin was over a year ago. I wonder if the project is still active..

---
Tags: c++, graphics-programming
---


title: Issue With Image Rendereing

text:
# Question
Title: Issue With Image Rendereing
I'm pretty New to the XNA Side of things,

I have built in PhotoShop a Set of frame by Frame images side by side to go through an animation class to display them frame by frame.

With this my images will not show up properly, they look more like a film reel.

Were could I Ggt good information on images for animation for XNA?

# Answer
Take a look at Sprite Sheet Sample at App Hub.
> 3 votes

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


# Question
Title: Blurring point light variance shadow map
I've been working on implementing variance shadow mapping for my game. I was able to get a spot light working with variance shadow mapping with a gaussian blur applied to the shadow map to reduce the aliasing. Now I'm trying to implement point lights but I'm not sure how to adapt the gaussian blur to work with the the shadow map when its stored in a cube map. I've searched around for a while but I can't seem to find any examples that use point lights. Can anyone help me out here?

# Answer
> 2 votes
There is an example of how to do variance shadow mapping with point lights, but it uses dual paraboloid mapping instead of cube mapping. The tutorial with the example is shown here.

If you're willing to deal with a bit less detail than cube maps, DP variance shadow mapping is easier to code, and requires two textures instead of six saving you some memory. You also only have one seam to hide.

Point lights are usually the hardest kind of lights to apply shadow mapping to (and consume more memory), which is why many games do not use them so often.

# Answer
> 1 votes
When I've implemented this before, I just blurred each cube face individually, using a standard 2D Gaussian blur. You can potentially introduce seams at cube edges, because the blur doesn't go across them, but in my experience this was hardly ever noticable. YMMV, of course.

You could probably even do a blur across cube edges by writing a blur shader that would take its input in the form of a cubemap, and distribute samples around a 3D vector, sampling a cone of directions. That sounds tricky and slow, though, so I'd try just blurring each face individually first.

---
Tags: xna, xna-4.0, shadow-mapping
---


# Question
Title: Simple scripting language for "one-liner"-type scripts?
Can you recommend a scripting language which allows me to easily parse "one-liner" types of scripts (they're just commands, really)?

For example, a C/C++ function which simply sets the value of a 2-dimensional vector (position, for example):

```
void SetVector(Vector2 &vector, float x, float y)
{
    vector.x = x;
    vector.y = y;
}

```

And in the scripting language, the entire script should be able to just be one line long. For example, this would be a script to set the components of vector "a" to 123.0f and 456.0f (x and y) (syntax of the language doesn't really matter, just as an example):

```
set_vector a 123,456

```

I'd use these short scripts to do simple things like change the position of objects during runtime (for debugging or other purposes), create simple config files for all kinds of entities which would go like:

bomb.script:

```
set_damage 1000
set_range 250
set_texture Data/Sprites/bomb.png

```

etc.

From a superficial glance, Lua, AngelScript etc. seem to be a little bit bloated for my simple needs (Although I must admit I haven't put tons of time into those two). Can you recommend something better?

# Answer
As far as simple, "one-liner" scripts are concerned, Lua is a perfectly legitimate choice. Function binding is easy, even with the native API (though there are plenty of helpers for this). It's syntax is pretty easy to learn. Oh, and the runtime is *tiny*, if that sort of thing matters to you. You won't even have to include its standard libraries, so it'll be even smaller than the compiled static library.

Lua also makes a good data-description language, much like JSON or XML.

Also, don't cut yourself short in terms of room to grow. Right now, you may only want "configuration scripts." But you'd be surprised how easily you might want logic to start creeping into those configurations. Maybe you spawn certain entities based on game state. Or change the texture of something based on game state. Whatever.

Lua can handle all of these kinds of things quite readily.

It is much easier to have too much power and not use it, than it is to have less power and then suddenly need more. Lua's power will be there if you use it, and if you don't, then you won't care. It'll still be quick and simple.
> 9 votes

# Answer
I think ChaiScript would have been an even more simpler to integrate than Lua for your case. It uses a syntax more similar to C++ so it depends.
> 0 votes

---
Tags: c++, scripting
---


# Question
Title: What are the specific mathematics, physics, AI and general concepts a programmer should know in order to develop a game engine?
Being a programmer of web and DB centered applications, I have knowledge in data structures such as lists, trees, graphs, etc. I honestly use very little of these data structure algorithms in my coding, except for sorting things in plain arrays, as I worked almost entirely with client-oriented frameworks where all the core functionality was built-in. I know C, PHP, Java, HTML, PL/SQL and MySQL. I am currently learning Python.

I want start with game development. I have seen other questions regarding suggestions, tips and approaches to game development for beginners. I understand these point, and am clear with the answers. A few days after posting, I read the article Write Games, Not Engines, and realized I should implement a game before I create a game engine. Still, I have questions.

My aim is to

* Improve my core level programming skills, including using data structure algorithms, mathematics and physics concepts.
* Implement a good game engine, to indulge myself in core level coding.
* To pave my way into the A.I. research field.

What are the specific mathematics, physics, AI and general concepts a programmer should know in order to develop a game engine?

# Answer
**Data Structures:** It is certainly a valid question. However, while some Data Structures are useful for any sort of Game (like the ones you've already mentioned, Lists, Trees...), there are others that are very specific. For Example, Octrees can be very useful in 3D Programming, but in a pure 2D environment you will probably not be needing those.

**Algorithms**: The same rule of thumb applies. Example, in a pure 2D environment, Collision detection works very very differently than in 3D.

**Important Mathematical Areas:** *THE* Most important Area for a Engine Dev to be familiar with is Linear Algebra and more advanced Algebra Topics (Quaternions). Quite simple really, if you're comfortable with Linear Algebra (and I mean beyond simple Matrix multiplication), your off to a good start.

Next ist Geometry, which connects well to Linear Algebra in Engine Dev anyways, and probably doesn't need a mention anyways.

Further, it never hurts to have a solid understanding of Basic Calculus. This comes in Handy when dealing with the Physics Engine or more advanced Shading Topics.

Other Topics of Interest should be: Combinatorics, Statistics

**Physics:** It's not mandatory, IF you are intending to make simple games. Doesn't hurt, but you will get by fine with high-school physics in this case.

If you're thinking of writing a physics Engine, or implementing an existing Architecture, then yes, it's mandatory. But fear not, there are many Physics Books written specifically for Game-Devs. Just keep in mind, read these BEFORE you start coding a game with physics. If your game should have physics, these Engines will tie in deeply into your core architecture.

**AI:** To be entirely honest, if AI is your main Interest, I wouldn't bother with writing an entire Engine. AI is alot more fun to do when you have an existing Architecture to play with. Writing an Engine will be a pain, and will be quite a while until you are able to implement fun AI Algorithms.

*What Type of Game do you wish to be developing?* Perhaps I can elaborate more on these Points with this information.
> 11 votes

# Answer
While it may be valid to ask which data structures are most used in game development, it's way more valid to ask which data structures are used for specific problems. I can easily state that hash tables are super common in games, but that wouldn't tell you anything useful in terms of when and where to use (and not to use!) a hash table in your own code. :)

In terms of math, you need to have a very strong grasp of linear algebra (vectors, matrices, linear systems solving, etc.), a very strong grasp of trigonometry, and at least a basic understanding of calculus (simple derivatives and integration). Any introductory college-level linear algebra course should set you on the right path, if not teach you about all you need to know to start working with common 3D graphics principles. I also link a book below which you may find quite helpful.

For physics, you're in for a ride. Physics can be broken into two different categories: collision detection and collision response. You absolutely must know the math behind collision detection, as that math is more or less identical to what you need to do graphics (especially for building the trees and maps you need for occlusion), and you're going to use that stuff for a lot of your game logic as well.

Collision response can vary from "simple" to ridiculous levels of intricacy, and even the simple stuff can be non-intuitive at first. I would highly, highly recommend that you leave that stuff to an existing library like Bullet, Havok, PhysX, or so on (or Box2D if you're working on 2D gameplay) until and unless you're comfortable with your existing math and algorithm knowledge and decide you want to learn how physics engines work. I would then recommend you build a very simple 2D physics engine as your first attempt. 3D physics engines are insanely complex beasts, and are (arguably) by far the most complicated and difficult part of game programming, which is why physics engines are the most commonly licensed third-party tech used in games. You just don't see very many games that aren't using Havok or PhysX in the professional world, despite how many games have from-scratch home-grown graphics engines and core engine code. Even companies that do nothing but build game engines typically license a physics engine, e.g. Unreal just uses PhysX rather than including its own physics engine.

I would recommend the following books to get you started. The first is an introductory level book on the basic math you need to know as a 3D game programmer:

http://www.amazon.com/Mathematics-Programming-Computer-Graphics-Third/dp/1435458869

The second is a book detected to collision detection algorithms (not collision response!) which will help with both your graphics coding and your physics coding:

http://www.amazon.com/Real-Time-Collision-Detection-Interactive-Technology/dp/1558607323
> 1 votes

---
Tags: software-engineering
---


# Question
Title: How to convert pixel coordinates to GL coordinates in 2D space?
I know that if you want to display a sprite on screen (in 2D) you can use glOrtho and essentially make 1 gl unit equal to 1 pixel, so when I plot out the vertices for say a 128x128 image (on a quad), I can define the vertices as -64/64, -64-64, etc and then when I map my texture coords to that quad, the image is displayed at a 1:1 ratio.

However, lets say I wanted to not use glOrtho and wanted to have a perspective view, so I can combine 2D sprites with 3D models and whatnot? I'm at a loss on how to convert/set up the coordinates for the planes/quads I want to draw images to, in a way that will match the resolution of the image. That is, define coordinates or convert them in such a way so that when a 2D sprite is right at the near plane, that sprite is mapped as 128x128 pixels on the screen.

# Answer
You can calculate the size of the screen at the near plane by using a little trigonometry:

```
screen_width_in_world = 2.0 * tan(0.5 * horizontal_fov) * near_clip_distance
screen_height_in_world = 2.0 * tan(0.5 * vertical_fov) * near_clip_distance

```

That's the size in world coordinate units of the "window" on the near plane that represents the screen. If you multiply those by 128 / screen\_width\_in\_pixels or 128 / screen\_height\_in\_pixels, you'll get the appropriate world space width and height for your sprite, to make it 128x128 at the near plane (and proportionally smaller as it gets further away). This assumes the sprite is screen-facing.
> 2 votes

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


title: python for game development

text:
# Question
Title: python for game development
> **Possible Duplicate:**
> Famous games written in Python

Is python any good for game development? Can I have some examples of great indie python games.

So I can have an idea what it's capable of?

I'm looking for games which are on a realistic scale for one person.

thanks.

# Answer
http://wiki.python.org/moin/PythonGames

The go-to resource for python games.
> 1 votes

---
Tags: python, pygame
---


# Question
Title: XNA HLSL - what happens if I grab a pixel outside a texture?
I'm using the tex2D function of HLSL, and I am wondering what will happen if I try to grab a pixel from a pixel coordinate outside of my texture (as an example 1.1). Will it clamp? Will it repeat the texture and grab something else? Will it return transparent?

# Answer
> 13 votes
Depends on how the texture is defined I suppose - I haven't used XNA, but textures (or texture stages) generally have options on whether to wrap, mirror or clamp.

In OpenGL, the wrap type is defined on the texture object, on DirectX it's set in texture stages. Both have their good and bad sides.

Common wrap types include:

* Clamp to edge - repeats the bordermost texel when reading outside the texture

http://personal.inet.fi/koti/sol/edge.png

* Clamp to border - any uv coordinates outside the rectange return a separately set border color (probably OpenGL specific)

http://personal.inet.fi/koti/sol/border.png

* Mirror - the borders act as mirrors for the uv coordinates, creating a "pingpong" effect

http://personal.inet.fi/koti/sol/mirror.png

* Wrap or Repeat - the texture repeats from the opposite edge

http://personal.inet.fi/koti/sol/repeat.png

---
Tags: xna, hlsl
---


# Question
Title: How can I set up a Pong-style game using the physics system in Unity?
I've just been using Unity and chose to learn it by making a Pong game which sounded simple enough as a "hello world" type of game. My goal was to try and encompass enough of the built in engine without needing to write scripts but I ran into a few problems.

Here is my setup so far:

**Paddle** Game Object:

* Box Collider
* RigidBody (Set as Kinematic)

**Ball** Game Object:

* Sphere Collider\<
* RigidBody (not kinematic)

**Wall** Game Object:

* Box or Plane Collider

I've set my material on my Ball to 'Bouncy' and I get a pretty good bouncing ball (given a starting force).

I've also added the following script to the Paddles:

```
void OnCollisionEnter(Collision collision)
{
    BallRidigBody.AddForce(rigidbody.velocity);
}

```

Here are some of my problems:

1. **Collision:** I was trying to figure out why my kinematic objects wouldn't collide before stumbling upon the collision matrix. I was wondering what are good approaches to enable kinematic collisions for my setup;
2. **Forces:** I'm confused how `ApplyForce` should be used. Even if I pick `ForceMode.Impulse`, is that a constant force? I'm a bit stuck on how to get proper bouncing off the walls and paddle. Since I've already applied a starting force, should my wall apply force on an `onCollisionEnter` method or change the velocity?

# Answer
> 3 votes
For problem 1, you can't, as the matrix shows. You have to make them non-kinematic and set their position using forces or rigidbody.MovePosition. Expect very high velocities to result.

For problem 2, you need not apply any forces. Pong uses perfectly elastic collisions, which you can get by settng the PhysicMaterial to be frictionless and have bounciness of 1.0. If you do apply forces for non-Pong reasons, the different modes merely avoid having mass factor into the calculation.

I understand that you're just using Pong as a learning exercise, but it uses such unrealistic physics that you're likely to have to struggle *against* the physics engine to get anything like Pong.

---
Tags: collision-detection, unity
---


# Question
Title: Best cross-platform solution for building 3D toolsets?
I am looking to develop an in-browser game in Unity3D, but I would like to write my builder tools for my project on a more powerful platform.

The assets I am building for the game are not traditional 3D models, so I'll probably be creating my own format. I was thinking about writing something in Blender or Maya, but that is a lot of overhead for what I want to do.

A Unity3D desktop app was also a possibility, but at the end of the day I decided I wanted to build it outside of the game engine.

Since the Unity3D app is going to be cross platform, I would like the tool to be as well.

Saying that, does anyone know of a 3D library/platform that will run well on Windows and OS X?

# Answer
A Unity3D desktop app would be the logical choice, despite your decision not to, the reasoning of which is unclear.
> 1 votes

---
Tags: 3d, unity, tools
---


# Question
Title: Make Love2D load resource from inside the .love file
I've just made my first (very simple, ugly) game in Love2D. The game works fine when run directly off my hard drive. However, when I package it up as a `.love` file, I get the following message:

> Error: Could not open file resources/stormclouds.bmp. Does not exist.
> stack traceback:
> \[C\]: ?
> \[C\]: in function 'newImage'
> \[string "main.lua"\]:46: in function 'load'
> \[string "boot.lua"\]:304: in function \<\[string "boot.lua"\]:302\>
> \[C\]: in function 'xpcall'

The "resources" folder does exist within my directory structure (resources/stormclouds.bmp), and the game runs fine when its not packaged up.

The line of code responsible for this is:

```
bg = love.graphics.newImage("resources/stormclouds.bmp")

```

How can I make this line work for my packaged file?

# Answer
The .love files are actually renamed .zip files. These zip files contain directory structures, so if your code refers to, say, "foo/bar.dat", your zip file has to have a "foo" directory with the "bar.dat" contained within.

See http://love2d.org/wiki/Game\_Distribution for details.
> 1 votes

---
Tags: filesystem, love2d
---


# Question
Title: How does a game without loading times work?
We're talking about an expansive game that is not divided in levels or checkpoints. A 3D adventure, for example.

# Answer
Simple answer: the game is divided into chunks, while you move around chunks are constantly being loaded behind your back before you can see them and thrown away when you leave the area. To every simple answer is a complex solution that weighs innumerable trade-offs in implementation... but you get the idea.

For games where you think you can see tens or hundreds of miles away, everything out there is fake. The real far stuff is just a bitmap, the medium range is a very light mesh. The real stuff gets loaded in and placed on top of the fake stuff before you get to it.

When chunks get unloaded they save the state of any objects or puzzles in progress so that when you come back they reset themselves to where you last saw them.

All this bypasses your main question so here's the real answer: there is always a loading time when you first start up the game but either you don't recognize it because it "always takes time to start up a game" and you expect that or it's hidden behind loading cinematics or happens while you play around in the GUI.
> 45 votes

# Answer
Previous answer pretty much nails it all. Also worth mentioning is Dungeon Siege I.

Here's a paper from one of the developer which actually goes over some of the architecture needed to make it work and common pitfalls:

http://www.floatingorigin.com/mirror/continuous-world.htm

I'd say it's a must read if you actually want to implement something like that.
> 12 votes

---
Tags: loading, memory-efficiency
---


# Question
Title: Best Platform/Engine for turn based Client/Server Android game
I'm currently designing a turn based game for tablets. Initially for Android with porting to iOS later considered in design.

I'm having trouble narrowing down the available technologies to even know where to spend my research time. I am hoping that if I explain what I am trying to achieve someone may be able to suggest a platform and/or engine.

I've looked into some of the open source Engines ( http://www.cuteandroid.com/ten-open-source-android-2d-or-3d-game-engine-for-android-developers ) and some appear to handle much of what I might require - although with a higher focus on graphics than i need. Mages looks interesting although development appears to have ceased.

If I could somehow leverage GoogleApps that would be excellent.

Here is what I am trying to achieve:

PvP turn based strategy game over internet - minimal animation and bandwidth required Players match up online using MetaGame system MatchID created on Resolution Server and Game starts Clients have 30 second countdown to select MoveString Clients sends small secure timestamped and MatchIDed MoveString to Resolution server Resolution server looks up Move String for each player, Resolves and Updates Players status in MatchID on Server Resolution server updates Client Views Repeat until victory conditions met - MatchID Closed, Rewards earned in MetaGame

There will also need to be a full social and account system and metagame backend - but this could be running on separate system(s)

Tablet in Offline mode would be catalog browsing and perhaps single player AI - bum I'm focusing on the Resolution Server at this point

I'm not even certain if I would be looking at an Android App or a WebApp at this stage! I want a custom GUI so I guess an app - but maybe as I have little animation a WebApp might also work. Probably some combination of both.

There will be very small overhead in data between client server - essentially a small text string every 30 seconds sent to the Resolution server which looks up the Effect and applies it to the Opponents string and determines some results to apply to the match. The client view is updated minimally with the results (only 5 in game Integers tracked) - perhaps triggering small animations/popups on the client to show the end result. e.g Explosion.

If you have suggestions for a good technology or platform to best achieving the Resolution Server I'd love to hear.

Also if you have experience with open source Engines - and could narrow down which (if any ) might be most suitable that would be a big help.

Thanks in advance

# Answer
Game Engine for Google Web Toolkit
> 1 votes

# Answer
> Also if you have experience with open source Engines - and could narrow down which (if any ) might be most suitable that would be a big help.

I currently work with libGDX, an engine which abstracts the difference of android and PC, so you can test and develop with the PC. Testing with the emulator of android is not recommended, since it is very slow and would therefore slow down development. This is also the main reason why I do not recommend AndEngine.

You said you need a little animation. Even for this "little" you should use OpenGL ES (which is used by libGDX too ;) ). A GUI is basically nothing except image rendering and click/tap resolving, so writing your own little framework should outperform the pain which may be linked with adjusting the default android GUI to your needs.

Since it is Java, you can't simply put the game on the iOS market. I know a game (Legends of Yore) by Kevin Glass (cokeandcode.com) which is ported to iOS **and** written in Java, but I don't know how he has achieved this.

A last word on the server: I am not a professional there, but if you only need to request and push a state every 30 seconds, I would just make a very simple server or even just an URL backed with some PHP (simple, but slow), Java (fast, but complicated and not always available), C, Go (If you want to have simplicity and speed, but not very developed yet) or whatever.
> 0 votes

# Answer
Have a look at http://www.airplaysdk.com/ It lets you write native C++ for several platforms at the same time.
> -1 votes

---
Tags: android, client-server, google-app-engine
---


title: How is software rendering done?

text:
# Question
Title: How is software rendering done?
I would like to explore realtime software based rasterization. I know everything is going towards the GPU these days but there are a few games where it still makes sense to use a software renderer.

For example: Voxeltron

> Voxatron is an arena shooter that takes place in a world made of voxels (little cubes, kind of). Everything in the game is displayed in a virtual 128x128x64 voxel display, including the menus and player inventory. If you look closely, you can sometimes see the inventory (score/life/ammo) casting a shadow on some of the objects on the ground.
>
> I've been working on voxel rendering and modeling tools for a long time now, with the ultimate goal of making a large explorey adventure game. About half a year ago it fused with work I was doing on arena shooters for Conflux, and this is the result.
>
> It's quite a simple game at heart -- mostly just Robotron set in a 3d destructible world with goofy creatures. I'm unsure how major the implications of destructibility will be for gameplay, but it sure is fun to blast away pieces of wall. I've also added an experimental wall-building pickup you can use to construct barriers to hide from scary monsters.
>
> The game takes place in a small set of arenas. Some of them feature rooms with set action pieces, somewhere between Knightlore and Smash TV. This is some of the original adventure based design sneaking back in, and an excuse to create thematic environments.
>
> Features:
>
> * **Custom software rendering with soft shadows.**
> * Built-in sound and music synthesizer (also used to make the trailer music).
> * Playback & post game recording.

# Answer
> 11 votes
I am going to assume you already know some basic linear algebra, the kind involved in: 3d projections, camera setup, transforming vertices into world position, etc... If you don't, there are plenty of great places to learn from. Here are two that I like:

Game Engine Architecture

* Brief coverage of basic linear algebra but does cover everything you need to know. The book is worth having for many other reasons too.

Real-time Rendering

* A little bit more detailed coverage but again sticks to only what you might need to know. Again, I recommend this one for the topics covered in the rest of the chapters.

---

Once you know about how to represent and handle 3d objects you are ready to look at how to draw them to the screen. Typically this is done with a scan line triangle rasterization technique. It is actually a pretty simple concept. You draw one row of one triangle at a time while interpolating color and uv texture coordinates. This process is continued for all triangles on the screen. You could even implement a depth buffer to handle out of order rendering.

This is covered in more detail in these articles:

Tutorial - Introduction to Software-based Rendering: Triangle Rasterization

Software Rendering School: Part I

---

And just for fun, check out the following article:

Quake 2 Source Code Review 3/4 (Software Renderer)

# Answer
> 5 votes
This is a pretty broad topic. There are two basic parts to it, though: the actual theory of the graphics transformation and rasterization pipeline, and the actual implementation bits that let you blast pixels on the to screen however you choose. On top of that, there is also optimization (particularly of the latter bit).

The first part is fortunately the same as the theory used for the graphics pipeline as exposed by modern hardware and APIs. If you know this already, you're set. If you don't, I recommend a good book. This one is pretty good.

There are a lot of options for the second part. They depend heavily on your OS and toolchain choices. If you're using C or C++, on Windows, you can simply plot pixels directly to a GDI bitmap (`SetPixel` is simple, but painfully, useless slow -- `CreateDIBSection` gives you a chunk of raw bytes you can manipulate at a much faster rate).

You can also acquire a DirectDraw surface and write to that, or write to a Direct3D or OpenGL texture. In these latter cases you'll still be using hardware, but as long as you do all the composition of the final image on the CPU yourself and just use the hardware APIs to copy the results to the screen, it still counts. On modern PCs you can't get access to the raw VRAM or anything directly anyhow.

If you'd like to know more, you should probably create more specific questions. I or others would be happy to answer them.

# Answer
> 0 votes
Okay I'm going to approach this question from the very basics; anything beyond that is way to broad for a simple QA; you need to buy a book on the subject.

The most fundamental difference between rendering in software and using a GPU comes down to plotting pixels. That is, when doing software rendering you are ultimately responsible for plotting every damn pixel, whereas with a GPU the plotting of pixels is largely automated by the hardware and you just "massage" the pixel pipeline using shaders.

For example, think about what you as a programmer have to do in order to display a 3D triangle on the screen. With a GPU, you pretty much just tell the hardware what the X,Y,Z coordinates of the vertices are and then the videocard fills in all the pixels on the screen that comprise the image of a triangle. You might use a shader to tell the GPU to change the color of every pixel based on a texture or something, but ultimately it still comes down to the GPU automatically filling in all the pixels for you.

Doing software rendering, you'd have to calculate which pixels on the screen to fill in, and then do the blitting to actually fill in those pixels. That is, you'd be doing the matrix math to transform from the coordinate space of the 3D scene to the view space, then projecting points from the view space onto the screen, etc.

---
Tags: software-rendering
---


# Question
Title: XNA C#: How can I prevent blurring when drawing from a RenderTarget2D?
I'm making a game and I want the end graphics to look chunky and pixellated, so I'm drawing from the spritebatch onto a RenderTarget2D which is 1/4th the size of the actual backbuffer, and then drawing from that to the backbuffer.

At first the sprites were blurred by antialiasing and I read that using SamplerState.PointWrap in the spritebatch Begin call would ease this a bit so I made that change. Everything seemed better, however the final on-screen image is still blurry and I think this is because of how it draws from the rendertarget2D to the backbuffer.

The image here is a comparison \- On the left is how the output looks now and the right is how I want it to look.

# Answer
Since you already mentioned Point filtering yourself... Make sure you don't draw at fractional positions, also don't scale or rotate. See if that helps. Also try to save your render target to a imagefile to see where the blur effect occurs during the rendering. At last make sure you set PointClamp / PointWarp everywhere. In the last renderstep where the rt gets drawn to the backbuffer this might be important too.
> 2 votes

# Answer
When you render your RenderTarget2D onto the actual backbuffer, make sure you have your TextureFilter set to `TextureFilter.Point`.
> 2 votes

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


title: Rendering Trailing Effect Using Opengl

text:
# Question
Title: Rendering Trailing Effect Using Opengl
I have to develop a game for my Graphics Course. I came across this video on the net.

http://www.youtube.com/user/stanfordcs248

I want to know how are the hazy/smoky effects which trails along with the cube is rendered using OpenGL and c++?

# Answer
> 1 votes
What you're seeing is post-process effects. Basically they first render the scene into a framebuffer object (FBO), then take that as a source texture and perform various operations on it. Among other things they talk about bloom effects etc, which are done in the same manner.

# Answer
> 1 votes
The smoky trailing effects are likely implemented with a particle system.

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


# Question
Title: How detect which OpenGL texture formats are natively supported?
For example, how detect if my videocard doesn’t support "bgr8" and convert it to another format, such as "rgba8" in software mode.

UPDATE: Sorry for the confusion. This question more about situation when I set *internalFormat* in *glTexImage2D* to something like "bgra8" but videodriver internally convert data to another format, like "rgba8".

# Answer
Your question seems to confuse certain concepts, so let's take things from the top. This is the definition of the function `glTexImage2D`:

```
void glTexImage2D( GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, void *data );

```

There are two things that you might call "texture formats". The first is the `internalformat` parameter. This is the *real* format of the image as OpenGL stores it. The `format` parameter describes part of the format of the pixel data you are providing with the `data` parameter.

To put it another way, `format` and `type` define what *your* data looks like. `internalformat` is how you're telling OpenGL to *store* your data. Let us call `format` and `type` the "pixel transfer format", while `internalformat` will be the "image format".

The image format of a texture can *never* be "bgr8". There is no GL\_BGR8 image format enumerator. There *is* a GL\_BGR enum, but that is for the pixel transfer format, not the image format.

Or to put it another way, your pixel data that you give OpenGL can be stored in BGR order. But the OpenGL implementation decides on its own how to actually store that pixel data. Maybe it stores it in little-endian order. Maybe it stores it big-endian. Maybe it just arbitrarily rearranges the bytes. You don't know, and OpenGL does not provide a way to find out.

~~There is no way to tell if a particular set of pixel transfer format parameters matches how the OpenGL implementation will store them given the image format.~~

There ***is a way*** to tell now. And by "now", I mean in OpenGL 4.3 and/or ARB\_internalformat\_query2. Coming to a graphics card near you:

```
GLenum format, type;
glGetInternalformativ(texture_target, GL_RGBA8, GL_TEXTURE_IMAGE_FORMAT, 1, &format);
glGetInternalformativ(texture_target, GL_RGBA8, GL_TEXTURE_IMAGE_TYPE, 1, &type);

```

`format` and `type` now have the implementation's preferred `format` and `type` for using `glTex(Sub)Image` calls to `GL_RGBA8` images. There are separate `format` and `type` queries for `glReadPixels` downloads.

There are other queries you can make.

If you don't have access to these, you can use some general rules of thumb that most hardware will adhere to:

* will store pixel data for 8-bit-per-channel data in BGRA order. So if you want to match the format with your pixel data, so as to more quickly upload texture data, you want to use `GL_BGRA` for the `format`, and `GL_UNSIGNED_INT_8888` or `GL_UNSIGNED_BYTE` for the `type`.
* will not actually store 24-bit colors as 24-bits. It will always pad them out to 32-bits; the alpha will just be ignored when it reads the data. So if you want to match formats, always use `GL_BGRA` `format` with `GL_RGB8` image formats, even if you have to put dummy data in the alpha component.
> 12 votes

# Answer
Generally most hardware doesn't suport 3-component texture formats so in this specific example you can make a reasonably safe assumption that it's converted. A 3-component OpenGL texture is actually 4-component in hardware but with the alpha component ignored/set to 255/whatever.

https://www.khronos.org/opengl/wiki/Common\_Mistakes#Texture\_upload\_and\_pixel\_reads (That "common mistakes" page is a goldmine - bookmark it now!)

For a more general case, glTexSubImage2D performance can give you a good indication of whether or not the upload must go through a software conversion path. You'd go about this during program startup - just create an empty texture (via glTexImage2D with NULL data), then issue a bunch of glTexSubImage2D calls, each followed by a glFinish to ensure it completes. Ignore the first one because caches/states/etc are being setup for it, and time the rest of them. Repeat this for a few different formats and pick the fastest.

Another alternative - seeing as you've tagged this question "Windows" - is to create a D3D device at startup (just after you've created your window but before you init OpenGL) then use D3D to check for format support. While OpenGL allows for software conversion to a valid internal format, D3D doesn't - if it's not supported by the hardware you can't do it. Then destroy D3D and bring up OpenGL. (This technique can also be used for querying other stuff that OpenGL doesn't let you query directly).

It's actually a useful rule of thumb to cross-check what you're doing in OpenGL with the D3D documentation. If D3D can't do something then it can be a good indication that the something in question is not supported in hardware. Not always true, but a useful starting place.
> 7 votes

---
Tags: opengl, textures, windows
---


# Question
Title: Best (Most Popular?) Image Format For Texturing
Okay, so I am using C++ with OpenGL, and I am going to create a loader to load in textures for my 3D game. (But the textures are 2D). I want the option of transparency, even if I decide not to use it. I need decent quality, although it doesn't have to be top notch. What do you guys suggest for format (PNG, TGA, etc.). Also, maybe make it something that is easy to create a loader for (I'm not going to use an already created one.). And also, if you have any links/tips to help out with the loader, that would be appreciated.

# Answer
I don't understand why you wouldn't want to use an off-the-shelf loader. PNG, for example, is a good choice for a format but is complex to write a general purpose loader for (and probably not worth the effort of writing one that only loads the specific subset of PNG formats you care about).

Given that somewhat unusual requirement, TGA is probably your best bet. TGA 2.0 has an alpha channel and is relatively simple compared to PNG.
> 15 votes

# Answer
Image texture format is a performance choice too. I recommend you to use compressed textures as much as possible. On mobile platforms, it can improve greatly performance (40% or even more), memory usage and time loading.

Consider a texture 1024\*1024:

* RGB or RGBA (16bits): 2Mo (.5s to load on SGS)
* RGBA (32bits): 4Mo (1s to load on SGS)
* PVRT (4bpp): 512ko (.125s to load on SGS)
* ETC1 + Alpha: 1.5Mo (.4s to load on SGS)

In our games, we have assets (textures) in many formats:

* DDS format for DXTC textures (Desktop platforms: OS X, Linux, Windows & Tegra)
* DDS format for ATC textures (Andreno GPUs)
* PVR format for PVRT format (PowerVR GPUs)
* PKM format for ETC1 texture (All OGLES 2.0 devices compatibles)

At Last, we use raw format for compatibility but that's for compatibility or GUI elements

* PNG format for raw texture. It is for RGBA 16, 24 or 32bits textures (we use a MIT licensed loader). It is uncompressed textures.

ETC1 textures have no alpha channel so we use a special shader with two textures (rgb texture and alpha texture). Compressed format are very easy to load (100 or 200 loc).

On desktop, DXTC (S3TC) is present on many cards. So, you shoud use it.

**Compressed Textures**

*Pro*

* Texture fillrate improved
* Texture loading (4x or more)
* Easy to load

*Con*

* Not supported on all platforms
* artefacts
> 10 votes

# Answer
Textures are collections of one or more images. This means that a texture *could* be represented by a TGA or PNG, but neither format is capable of representing all possible features of textures. Why?

Because each one can only hold a *single* image. There are no mipmaps. There are no 3D textures possible. No array textures. No cubemaps. Each of those files is just a single 2D image. They can be part of a texture, but unless you're not using mipmapping (and I strongly advise against not using mipmaps unless you have specific needs), a single image file in these formats cannot be a texture.

They are fine image formats, but they make poor *texture* formats.

DDS is the front-runner of texture formats because it actually supports things textures needs. It supports mipmaps and cubemaps. It supports 3D textures. DDSv10 support array textures. You can package a single texture within a DDS in a way that you couldn't with PNG or TGA.

DDS supports uncompressed and compressed texture data. So long as the compressed texture format is one of the DXT/BC texture formats.

PKM is useful for packaging ETC1-compressed images, but like with PNG, it doesn't support actual texture features.

PVR files seem to be the mobile equivalent of DDS (though why they couldn't just use DDS's, I don't know). They support various compression techniques, but they lack advanced DDSv10 features like array textures, as well as 3D texture support.

So DDS wins in terms of comprehensive texture support.
> 9 votes

# Answer
The Khronos Group recommend KTX file format for storing textures for OpenGL and OpenGL ES applications. You can use libktx for working with this format.

Features:

* Instantiate an OpenGL texture from a KTX file
* Decompress an ETC1 compressed texture image when the hardware does not have ETC1 support.
* Construct a hash table of key-value pairs from the KTX file as the texture is loaded
* Write a KTX file from a array of source images and an optional hash table of key-value pairs.
* Construct and populate a hash table of key-value pairs.
> 5 votes

# Answer
There are a number of considerations here:

1. How fast you can get the texture off disk and into system memory.
2. How fast you can get the texture from system memory to the GPU (via glTexImage2D in your case).
3. How much disk space and video RAM storage is in your budget.
4. Performance and quality.

TGA is a good choice because in the 24 and 32 bit uncompressed cases you can read the data in one single fread/whatever and send the result directly through glTexImage2D without further processing. It's a bad choice because it can have the largest file size and if disk I/O is a bottleneck then your reads will be slow.

PNG is a good choice because it preserves quality of images with a reasonably small file size. It's a bad choice because PNGs can be slow to decompress - if that's your bottleneck then - well, you know.

JPG is a good choice because it generally has the smallest file size and will come off disk really fast (doubly good if you need to send the file over a network). It's a bad choice because of intermediate software decompression steps and quality loss (although you can tune the quality settings to mitigate this). No alpha channel either.

DDS (or other compressed formats) are good choices because of the smaller file size and the ability to include a prebuilt mipmap chain. If it's a format that's natively supported in hardware (and DDS is natively supported on most consumer PC hardware - has been for a long time too) you get the same benefit as TGA - one fread, a bit of poking in the header to figure out some image properties, then send the data straight through without intermediate steps. Compressed textures will also make your program run faster and use less video RAM. They're bad choices because they use lossy compression (which can sometimes be really noticeable) and may not be supported on all hardware.

If it was me I'd build support for all 4 of these formats (TGA and DDS are quite trivial to write loaders for, with JPG and PNG I'd use an image library) so that content creators can choose the most suitable format on a per-texture basis.
> 4 votes

# Answer
It seems like DDS (DirectDraw Surface) is the most popular choice for textures at the moment. Is has different pixel formats, transparency, and compression. It is supported in OpenGL through the GL\_ARB\_texture\_compression extension.

For example, there is an OpenGL loader here.
> 3 votes

# Answer
And of course you can always go with the old 32 bits BMP which is really easy to load (especially if the size is a power of 2 (actually, a multiple of 8 bytes IIRC)).

Otherwise it seems weird that you want only one format, jpg is really cool for nice real-world hi res textures (jpeg does marvels with diskspace and (down)load-times), png for transparency and the occasionnal 32bits BMP for controle-textures (easy to create from a script or a 'quick and dirty' tool).
> 0 votes

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


# Question
Title: Have a simple enemy detecting he touch a wall to make him stop/turn around
I am doing a very simple scene with a cube sliding on the "ground". Once the cube reach a wall, he is blocked.

I want to detect the wall to make the cube go in the other direction. I used OnCollisionEnter but it is triggered at the scene start as my cube touch the ground.

I could make a difference between grounds and wall, but my game will make the whole scene rotate, and floor will become wall and wall floor.

I wanted to add "physics whatever object" to allow a left/right detection but i cannot add collider or rigidbody to my cube.

How can i have a cube knowing when he touch a wall without having a false positive with the ground ?

# Answer
> I could make a difference between grounds and wall, but my game will make the whole scene rotate, and floor will become wall and wall floor.

Why couldn't you just tag the two sets of walls (horizontal and vertical), and then do tag check in `OnCollisionEnter` for horizontal or vertical as a wall check compared to the rotation of the world? So, for example, if the world is rotated by 90 degrees, you "hit a wall" when you collide with something that was marked as horizontal.
> 5 votes

# Answer
Look at the contact normals, ContactPoint.normal. These are vectors perpendicular to the contact surfaces, so if you hit a wall the normal will be mostly horizontal and if you hit the floor the normal will be mostly vertical (unless the geometry of your walls and floors is especially gnarly).

A collision may have multiple contact points (Collision.contacts); averaging/summing their normals would probably work well.

You might also try comparing the average of the points of contact (ContactPoint.point) with the center position of your cube. That might well be more robust.

(I haven't tried actually doing this in Unity.)
> 1 votes

# Answer
Instead of using 'just' a cube, you could use a prefab with a cube, and add some empty gameObjects with triggers or colliders to check collsions on different positions.
> 0 votes

# Answer
It's likely you're always going to get a collision with the floor; if you're using gravity, your cube is essentially going to be almost constantly hitting the floor in addition to any other objects it hits. The trick is in determining if there are additional collisions that involve a wall.

Without knowing much about your specific implementation, here's what I'd suggest: In `OnCollisionEnter`, check every `ContactPoint`'s normal to see if it's perpendicular to the floor. For now, I'll assume that your cube rotates to have its `Forward` vector parallel to the ground on which it's moving (resulting in its `Up` vector pointing away from the ground). If that's wrong, let me know how you have it set up and I'll try to edit the answer to fit. My code is in C#, if you're using JavaScript, there will obviously be some differences. In your cube's collision code, you'll want something like this:

```
void OnCollisionEnter(Collision other) {
    bool hitWall = false;
    foreach(ContactPoint cp in other.contacts) {
        float dot = Vector3.Dot(cp.normal, transform.up);
        if(dot < 1.0f && dot > -1.0f) {
            hitWall = true;
            break;  //No need to keep checking once you've found a wall
        }
    }

    if(hitWall) {
        //At least one collision was not with the floor (or ceiling)
        //Handle wall collisions here
    }
}

```

If you still get false positives, consider using a numbers closer to zero than 1.0 and -1.0 (like 0.9 and -0.9) for a little less precision in determining a collision with a non-wall.
> 0 votes

---
Tags: collision-detection, unity
---


# Question
Title: encircling and counting number of objects in a grid
There is a square grid in which there are empty and filled blocks. A number of contiguous blocks form an object. My bot can find out the status of it's neighbouring 8 blocks (whether they are filled or not). It can move to a neighbouring position if there is no filled block over there.

I have 2 questions

First one :

My code works for the case when there are no tight spaces (i.e., when objects have at least 2 empty blocks between them). But, in the case when there can be a single space between 2 blocks, since my bot has no way of knowing if the neighbouring filled blocks belong to the same or different objects, it fails to encircle the object.

Is there a way to get around this problem?

The other question :

What would be the best search strategy for this? I've been thinking of assigning rewards to neighbouring spaces on the basis of how many unvisited spaces it will allow me to visit if I visit that neigbouring space, but a much simpler strategy seems to be : keep going right till you hit the wall, the go up and keep going left, then up and right .... Is there a catch to this approach?

# Answer
An easy way to encircle an object is to just 'stick your left hand out' and walk forwards, keeping your hand on the object.

So, for your bot, you need to keep track of its direction, then if the tile to the left (relative to its current direction) is free then turn left and move forward. If its not free, and ahead is free then move forwards, and if ahead isn't free then turn right.
> 1 votes

# Answer
Maybe just use pathfinding. A\* is a good and easy algorithm for that.
> 0 votes

---
Tags: ai, bot
---


# Question
Title: How does Trine's lighting look so spectacular?
Is there some kind of "special" lighting in this scene? I notice that the sun seems to "pop".

# Answer
It uses a bloom shader. That's a post-processing effect that makes bright areas of the rendering appear to glow.
> 20 votes

---
Tags: lighting, shadows
---


title: Do players like holiday events?

text:
# Question
Title: Do players like holiday events?
I remember back when I played runescape, they always had these really interactive holiday events. And players would be squirming all around trying to find where it was. After you would complete it (it was like a mini-quest), you would be rewarded with some kind of item. I thought it was really cool, but if you missed the event you'd be pooped out. And now days, I play simpler games, such as parallel kingdom, and they just have boring items that you can buy for holidays.

Is it worth making holiday events, or could you get by without them?

# Answer
Holiday events can be made as an incentive to get "fun" stuff, but as mentioned don't make them game-breaking qualities. Then players can get bragging rights over others who missed out on the promotion. It also lets people know that the creators are still putting in their effort to keep supporting the game.

Also, Animal Crossing is a good offline example. It uses the Gamecube's system clock to keep the town in time each year, so you can see a Christmas celerbration or New Years countdown. And I believe that in some mornings, some of the townsfolk even go out for a morning jog!
> 5 votes

# Answer
Looking at Team Fortress 2, yes, players do. Holiday events are good, they bring old and new players to your game. But make them really funny - not just a little item set or a 10% deal. And if you add holiday items, don't make them overpowered and game-obstructing. It's your choice make holiday events or not, but I recommend you to make them to increase lifetime and popularity of your game.
> 5 votes

---
Tags: game-design, user-experience
---


# Question
Title: What use does the unary & operator have in this piece of C++ code?
In an example for a little game framework (that does work), there are the lines:

```
ID3D10Device* device;
ID3D10Buffer* pBuffer;

```

followed by the line

```
 device()->CreateBuffer(&bd, NULL, &pBuffer());

```

The third argument requires a pointer, so why do you need to put an ampersand before pBuffer? an ampersand gets a memory address right? But pBuffer is already a pointer so what does the ampersand do to it?

# Answer
As described in the ID3D10Device::CreateBuffer page, this function simply requires a pointer to a pointer which is used to contain the output of the function.

```
HRESULT CreateBuffer(
  [in]   const D3D10_BUFFER_DESC *pDesc,
  [in]   const D3D10_SUBRESOURCE_DATA *pInitialData,
  [out]  ID3D10Buffer **ppBuffer
);

```

As always in C/C++, adding an & simply returns the address of the variable. In this case, the address of the pointer.
> 9 votes

# Answer
The & is also used as a reference operator. It returns the address of the variable it's referencing too. If you had a function that took the pointer directly as a parameter, then the function will be working directly with the pointer (useful for pointer arithmetic).

Pointer pointers to resources are quite common in the D3D APIs. You usually don't want to access them directly as it's not of any benefit.
> 1 votes

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


title: Examples of faking 3D

text:
# Question
Title: Examples of faking 3D
Does anyone know of any good examples of 3D being faked in 2D (not necessarily code, but games I could look up)? The player has the perspective that they are going 'into' the screen and things are coming out at them. At the moment, I'm simply scaling the 2D enemies to give the illusion that they're coming closer, but it still feels quite flat. Are there any tips on how to give it more of a 3D illusion without actually using a 3D engine?

**Edit**: Just came across the term 'Mode7' and this video which shows pretty much what I'm trying to figure out. (especially the games at 0:13 and 1:03). What's a good way of implementing something like this?

# Answer
One of my favorite classic arcade games also happened to do fake 3D: Space Harrier

In that video you can see a few tricks they used, but one of the most effective visual effects is so seamless that you might not even notice it happening: when the player (or importantly the camera) moves, they use parallax to give objects in the scene a feeling of depth.

That is, closer objects move side to side faster than distant objects. The classic example of parallax is looking out the window of a moving car: nearby stuff like street signs whip by in a blur, trees further away move more slowly, while distant things like mountains barely appear to be moving.

In addition, objects don't scale linearly as they get closer. That is, objects only scale a little while far away and scale up faster when close; scaling linearly would be if they scale up at the same rate the entire time. You say you're already scaling your objects as they get closer, but you may be scaling them linearly and that looks flat.

ADDITION: Afterburner is another classic arcade game that used a lot of the same graphics tricks.
> 14 votes

# Answer
Most of these games use the famous "Mode 7" tricks. It is just a rotozoom. This operation was done by coprocessor on console so it was very fast on these hardwares. Real 3d operations were too costly. But with actual hardware, it is easier to simulate with real 3D.

A rotozoom is a rotation and a zoom on a sprite. Look this explanation or this SDL implementation.

Search on google "MODE-7 floormap" to find samples and code.

F-Zero Mode 7 was one of the first game to use it on snes.
> 6 votes

# Answer
I found a fantastic review of these techniques, with examples and explanations, several years back. Your question prompted me to search for it again: Lou's Pseudo 3d Page. He used to have a working Outrun engine but removed it for some reason (the Wayback Machine if your friend here)

To further answer your question, here is a list of the games from his page:

* Street Fighter II (arcade) (the "raster effects" on the dojo floor)
* Outrun (arcade)
* Space Harrier (arcade)
* Super Hang-on (arcade)
* Enduro (Atari 2600)
* Pole Position (arcade, Atari 2600)
* Road Rash (3DO)
* Power Drift (arcade)
* Racin' Force (arcade)
* Hydra (arcade)
* Outrunners (arcade)
* Turbo (arcade)
* Spy Hunter II (arcade)
* Pitstop II (Commodore 64)
* Enduro Racer (arcade)
* Lotus (Commodore Amiga)
* Test Drive II (Commodore Amiga?)
* Speed Buggy

Again, not my list—all credit should go to Louis Gorenfeld for his awesome research.
> 5 votes

# Answer
All 3d games are fake 3d :P I'm joking, I know what you mean by 'fake 3d'..

Well, the 8/16bit has several examples of a very common technique of presenting the background in layers moving with different velocities, to mimic parallax. It was also very common to see.. actually, it's easier to just look at any racing game made for those consoles than explaining, which I believe is what you're trying to do.

I'm seeing some new stuff in the same spirit coming up in the flash scenario. Take a look at Missile Game 3d.

I don't know what path you're willing to take to achieve this effect, but it seems you're suggesting that you have started some programming and have access to graphics (an API, maybe?). So it's just a matter of finding the right parameters for movement across the screen and scale as a function of time. I don't think you're going to find specific equations for that, as it'll probably be highly dependent on your game's specific situation (the usual speed, racing, airplanes, tunnels etc) The trial and error you're already doing is your best bet, for finding the functions scale and trajectory on the screen in relation to time.
> 4 votes

# Answer
Jazz Jackrabbit and the old Sonic games had those Bonus Worlds that were pseudo 3d.
> 3 votes

---
Tags: 2d, 3d, graphic-effects, perspective
---


# Question
Title: How are physical model programmed in simulation games?
Being a Gran Turismo fan, I'm wondering what are the algorithms used to compute realistic behavior for friction, aerodynamism, velocity, curves etc.

Also, are there sophisticated ways to simulate fluid mechanics in flight simulation which are trivial enough for an amateur project ?

If I wanted to build a flight simulator, neglecting the parameters which have the littlest effect (temperature, pressure, humidity, friction of the air on the wings, gravitational center of the plane, etc), are there some kind of physical formulae or programming models I should know about ?

Or does physics engine feature such kind of simulation dedicated calculation ?

# Answer
> 10 votes
Physics has spent hundreds of years coming up with equations to model the real world; any college physics textbook is going to walk you through the basic mathematical solutions to everything you listed - even the stuff you want to ignore.

Sometimes, for efficiency or simplicity or stability, computer simulations ignore many of the factors. Sometimes they are short-circuited - we simulate gravity with a universal force, not by actually having a mass with the size of the earth; we simulate electricity at the level of current and resistance, not individual electrons in the wires. Sometimes we approximate because the closed-form of the integral is too expensive to compute; in this case, piecewise integration does well, as e.g. RK integration, common for Newtonian physics engines, but it'll solve any ordinary differential equation you want to give it.

Most of what you have named are degenerate cases of the Navier-Stokes equations:

> They may be used to model the weather, ocean currents, water flow in a pipe, air flow around a wing, and motion of stars inside a galaxy. The Navier–Stokes equations in their full and simplified forms help with the design of aircraft and cars, the study of blood flow, the design of power stations, the analysis of pollution, and many other things.

# Answer
> 1 votes
Normally, you build a flight model (simulator) on top of a physics engine. But you can certainly experiment without a full featured physics engine.

To simulate physics in a game, you need to work with 3D vectors. Just take the equations of projectile motion you learned in school, and apply them each time step (frame). Treat your vehicle like a point object.

Here are some simple examples,

* friction - subtract a small value (0.01) from your velocity each frame until it hits zero.
* air drag - multiply your velocity by 0.97 each frame
* acceleration - vel = vel + accel * timestep
* velocity - x = x + vel * timestep

Note that position (x), velocity, and acceleration are all 3D vectors. Also, to apply steering to your air vehicle, you probably want to apply a 3D force vector each frame just like gravity (0,0,-9.8) is applied.

And lastly, you'll need a way to visualize your 3D motion each frame so that you can see if you like what you are doing. I recommend opengl. Take a peek at the samples that come with physx.

Later on, you can worry about vector fields to simulate complex forces, apply numerical integration methods to reduce error, and use a full blown physics engine to handle collisions and contact points.

---
Tags: physics, simulations
---


# Question
Title: Is it easy to switch from Chipmunk to Box2D?
Currently I'm doing some prototyping with physics in Python and I later plan to port the code over to C++.

Box2D has some features that I really like so I'd rather use that library instead. The problem is that the Python port of Box2D is pretty tedious to install and I'm lazy, :D while the Chipmunk port is very easy to install.

Is it hard for me to switch libraries later on when I port the code to C++? (Will I have to do big architectural changes?)

# Answer
> 5 votes
Physics is not like art or graphics or sound; it is a core part of your game. It is part of what makes people want to play your game.

If Box2D has "features that I really like" and Chipmunk does not have those features, then you cannot develop your game under Chipmunk. Unless those features in question are fluff or otherwise superfluous. If they are important to gameplay (constraints, rigid body dynamics, etc), then you will need to have them in your prototype before you can consider your prototype complete.

> The problem is that the Python port of Box2D is pretty tedious to install and I'm lazy

If you truly are, as you say, "lazy", then perhaps game development is not the hobby for you. Game development requires work and effort. If taking a couple of hours to compile and install a Python module for a library is too much for you, then what are you going to do when you hit a *real* problem? When you can't figure out how to make the various objects interact correctly? When your AI seems to be doing the wrong thing and you can't figure out why?

That's no excuse for a difficult install process. But if you need this library, then you should be willing to expend some effort to getting access to it.

---
Tags: box2d, porting, chipmunk
---