title: Upload vertex data for particles

text:
# Question
Title: Upload vertex data for particles
I am kind of beginner with opengl.

I am using point sprites (currently without any texturing) for my particles. I seem to fail to get them uploaded to the GPU memory correctly. I have readed lots of tutorials on VBOs and VAOs and I can not locate the reason why the particles seems to be wrong.

The problem is, that some of the particles are behaving correctly, but others dont. They have random colors even if every one of them should be white and they are not in correct point in space. Also when a particle dies and the size of the array gets decreased, all particles warp in another location.

Here is my particle GPU data struct:

```
[StructLayout(LayoutKind.Sequential)]
public struct GPUParticle
{
    public Vector4 Position;
    public Vector4 Color;

    public static int SizeInBytes = Vector4.SizeInBytes * 2;
}

```

Here is the VAO, VBO and EBO initialization:

```
GL.GenBuffers(1, out Vbo);
GL.GenBuffers(1, out Ebo);
GL.GenVertexArrays(1, out Vao);

// Bind the VAO as current
GL.BindVertexArray(Vao);

// Bind the VBO to the VAO
GL.BindBuffer(BufferTarget.ArrayBuffer, Vbo);

// Describe the VAO data

GL.EnableVertexAttribArray(0);
GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 0, 0);

GL.EnableVertexAttribArray(1);
GL.VertexAttribPointer(1, 4, VertexAttribPointerType.Float, false, 0, Vector4.SizeInBytes);

// Bind the EBO to the VAO
GL.BindBuffer(BufferTarget.ElementArrayBuffer, Ebo);

// Unbind the VAO
GL.BindVertexArray(0);

```

And here is the uploading which I do on every frame:

```
// Bind the buffer and send the data to the GPU
GL.BindBuffer(BufferTarget.ArrayBuffer, Vbo);

// Invalidate old data
GL.BufferData (BufferTarget.ArrayBuffer, new IntPtr(Count * GPUParticle.SizeInBytes), IntPtr.Zero, BufferUsageHint.StreamDraw);

// Upload new data
GL.BufferData (BufferTarget.ArrayBuffer, new IntPtr(buffer.Length * GPUParticle.SizeInBytes), buffer, BufferUsageHint.StreamDraw);

// Unbind
GL.BindBuffer(BufferTarget.ArrayBuffer, 0);

//Console.WriteLine ("Uploaded array buffer. Count: {0}", buffer.Length);

// Update index buffer only if there are more elements in the buffer than there has ever been
// Generate index buffer for EBO
indices = new uint[buffer.Length];

// This is really stupid. Perhaps we really do not need any indices?
for(ushort i=0; i < buffer.Length; i++)
{
    indices [i] = i;
}

// Bind the EBO for uploading
GL.BindBuffer(BufferTarget.ElementArrayBuffer, Ebo);

// Invalidate old data
GL.BufferData (BufferTarget.ElementArrayBuffer, new IntPtr(Count * sizeof(uint)), IntPtr.Zero, BufferUsageHint.DynamicDraw);

// Upload new data
GL.BufferData (BufferTarget.ElementArrayBuffer, new IntPtr(buffer.Length * sizeof(uint)), indices, BufferUsageHint.DynamicDraw);

// Unbind EBO
GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);

// Save the particle count for drawing and zeroing the buffer
Count = buffer.Length;

```

Here are the shaders:

```
#version 330 core
// VERTEX SHADER
layout(location = 0) in vec4 vertex;
layout(location = 1) in vec4 color;

uniform mat4 mP;
uniform mat4 mV;

out vec4 fragColor;
out vec4 pos; // For debugging

void main(){
    fragColor = color;
    pos = vertex;
    gl_Position = mP * mV * vec4(vertex.xyz, 1.0);
}

#version 330 core
// FRAGMENT SHADER
in vec4 fragColor;
in vec4 pos;

layout(location = 0) out vec4 color;

void main(){
    color = fragColor;
    //color = vec4(1,1,1,1);
    //color = pos;
}

```

I have simplified the code a bit, but this is basically what I do. I am unable to spot what I am doing wrong.

The most weird thing is, that when in vertex shader I swap the color to be used as vertex and vertex to be used as color, the motion of the particles gets corrected, but the colors are still going haywire.

Any suggestions? I am out of ideas myself. Is the VAO initialization / uploading code correct?

# Answer
> 0 votes
To answer my own question, the problem was on this line:

```
GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 0, 0);

```

While it should have been:

```
GL.VertexAttribPointer(0, 4, VertexAttribPointerType.Float, false, 0, 0);

```

Works like a charm now. And I can facepalm `:)`

---
Tags: opengl, opentk
---


# Question
Title: Can you move items made in the Skyrim Creation Kit on PC to the Xbox version?
I'm a pretty technically illiterate gamer but after several annoying glitches I finally went out and got the PC version of Skyrim. After a little bit of practice I got the hang of transferring my Xbox 360 saves to the PC and vice versa. I've really been enjoying using the console commands and lately after fixing the crashes associated with the DLC have begun to explore the Creation Kit.

I've created several items with custom weight, value, armor rating and multiple custom enchantments. I'd really like to use them on the Xbox, and I know some people will just say to play it on the PC but I just don't enjoy using the keyboard compared to my controller and flat screen TV.

I haven't changed the mesh, design or texture of any of the items just their names and enchantments. Considering Bethesda said they used the Creation Kit to make the game I don't think my custom items are anything the Xbox can't handle. To me it seems like just a matter of getting them over there... Can I do that?

If you know of a video that will show how, that would be awesome. It should be mentioned I'm not willing to do anything to void my Xbox's warranty.

# Answer
You can't. The Xbox is a closed console without any support for user created content. The situation won't likely change, and even if it did, you'd need a hacked console, which would certainly void your warranty.
> 4 votes

---
Tags: modding, xbox, skyrim-modding
---


# Question
Title: Getting wrong value for middle of screen
My mouse is able to move the camera and rotate it around my model. If the mouse is in the middle of the screen, the camera should not move.

The red circle is where my mouse has to be at in order for the camera to stay still. If I put the cursor in the middle of the screen, it rotates the camera which shouldn't happen.

```
    Point screenCenter;
    float scrollRate = 1.0f;
    MouseState previousMouse;
    bool moveMode = false;

    #region MOUSE
        screenCenter.X = this.Window.ClientBounds.Width / 2;
        screenCenter.Y = this.Window.ClientBounds.Height / 2;

        this.IsMouseVisible = true;

        previousMouse = Mouse.GetState();
        Mouse.SetPosition(screenCenter.X, screenCenter.Y);
        #endregion MOUSE

    if (this.IsActive)
        {
            MouseState mouse = Mouse.GetState();

            if (moveMode)
            {
                Vector3 temp = player.playerWorld.Translation;
                player.playerWorld.Translation = Vector3.Zero;
                player.playerWorld *= Matrix.CreateRotationY(MathHelper.ToRadians(mouse.X - screenCenter.X) / 75);
                player.playerWorld.Translation = temp;

                cam.up -= MathHelper.ToRadians(mouse.Y - screenCenter.Y) / 25;
            }

            if (mouse.RightButton == ButtonState.Pressed)
            {
                if (graphics.GraphicsDevice.Viewport.Bounds.Contains(new Point(mouse.X, mouse.Y)))
                {
                    moveMode = true;
                }
            }
            else
            {
                if (moveMode)
                {
                    moveMode = false;
                }
            }

            if (mouse.ScrollWheelValue - previousMouse.ScrollWheelValue != 0)
            {
                float wheelChange = mouse.ScrollWheelValue - previousMouse.ScrollWheelValue;

                cam.up += 0.7f;
                cam.backward += 0.7f;
            }
            previousMouse = mouse;
        }

```

Why could this be happening? the screen is 650X1000. ScreenCenter x and y are the correct values.

Now that I play with it more, it seems each time the game starts, the mouse is set to a different position. The mouse should automatically be set to the middle of the screen each time the game starts, but it ends up anywhere but the middle.

Any idea of what could be happening here?

# Answer
Here's your problem:

```
cam.up -= MathHelper.ToRadians(mouse.Y - screenCenter.Y) / 25;

```

You are setting the mouse to the center of the screen, but you are moving the screen in relation to the bottom corner of the screen, instead of the middle. Try changing it to:

```
cam.up -= MathHelper.ToRadians(mouse.Y - (screenCenter.Y / 2.0f)) / 25.0f;

```
> 2 votes

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


# Question
Title: Is creating vertex/index buffer optimized this way?
I have some vertices in an array from which I create a vertex buffer. Let's say I have vertices:

```
v1, v2, v3, v4

```

I use indices:

```
0, 1, 2, 3

```

Is there any performance impact if I change the indices to

```
1, 3, 0, 2

```

(to have another geometry)? I just wonder whether the directx will iterate through vertices jumping to different addresses in a memory to get vertices (not linearly) or maybe the directx is able to recreate the vertex buffer (before it is sent to the graphics card) to suit the indices like this (it could then iterate it linearly):

```
v2, v4, v1, v3

```

(beacuse it is obvious that is is better to iterate through data put linearly in a memory)?

Is the question understandable?

# Answer
> 6 votes
The order can impact performance, but not in a simple triangle vertex reordering like you're talking about. The order of the vertices doesn't matter much in terms of access and jumping around; any performance degradation from non-linear vertex access is more than made up for in other ways when using properly ordered indices.

DirectX/OpenGL will not reorder your vertex buffer to match the index buffer. It can't, really; the index buffer could reference the same vertex more than once (that's the primary point of an index buffer). The GPU is also designed to assume you'll have non-linear vertex accesses; that's pretty standard.

You should be aware of the "vertex cache," though you don't at all need to think about it much for most indie/hobby scale projects. Basically there is a small cache of processed vertices that the GPU keeps around. This is important when any vertices are shared, which is very common for 3D models but is rarer in 2D sprite games and most cube/voxel engines (few or no shared vertices, in which case indices may not even be all that useful).

If two triangles use the same index, the GPU wants to avoid running the vertex shader twice for that vertex. However, the cache has limited space. If you use vertex 3, then 0, 1, and 2, then use 3 again, that vertex will be in the vertex cache and the GPU as no need to rerun the vertex shader for it. Hoerver, if you reference vertex 3, then 1000 other vertices, then reference vertex 3 again, the GPU will probably be forced to rerun the vertex shader (the existence and size of this cache is a hardware optimization, not part of any spec).

Therefor, keeping reused vertex indices in your index buffer relatively close together to the extent possible means less time will be spent rerunning vertex shaders. There are libraries for this so you shouldn't need to worry about how to do this and for your game it almost certainly won't make a measurable difference anyway (it starts to matter for very large games with very complex/detailed meshes though).

There is also an effect where it can be faster to process certain vertices (or triangles, more accurately) first dependent on where they are in the mesh. Triangles inside of "inner concave" features (say, an armpit) are more likely to be occluded, so it's more efficient overall to draw the other triangles first so early-Z kicks in (and even with Z-prepass, such ordering means writing to the depth buffer less). Again, there are libraries for this, and it's probably not something you'll need to worry about unless you're making the next CryTek or 3DS Max. For a MineCraft-like engine, I would only recommend building vertices top-down since you'll often be seeing only the surface of the world; maybe there's some ordering optimizations to faces inside caves you can figure out, but it probably won't matter in the slightest.

If you're unsure if you need to worry about an optimization, just test and profile and see if it's a real problem affecting work or platform support. If you're unsure if a change is a pessimization, again, profile and see. Even if it is, use the profile to see if it's one that even matters for your specific game and target hardware (if you lose 2 FPS but were already running at 400, and the change brings some other benefit, why waste time caring about the FPS loss now?).

Short version: no, reordering your indices to better handle triangle strips is not going to affect performance in any meaningful way.

# Answer
> 1 votes
The purpose of indexing is to make meshes more compact in memory. It does not matter in what order the indices are. If you use indexing, it will always be the same speed with the same amount of indices. It wouldn't make sense (at least while speed is in concern, and it always is) for the graphics driver to look through the indices and determine if they are in order or not.

# Answer
> 1 votes
I'd put the vertex order linear in memory.

If your vertex size is *not* a clean multiple of 32 bytes or so, then having the order be linear can enable the vertex fetch unit on your GPU to actually pre-fetch some of the next vertex at the same time as the current one. Of course, you'll need to get a nice high vertex count in order to get meaningful figures from any profiling run, but that can prove to be a small but significant performance boost.

The purpose of indexing, by the way, is not *just* to reduce memory requirements - I guess people have become conditioned to thinking that reducing memory usage is everything. Indexing serves two *additional* purposes, which will give you much *greater* performance than reducing memory:

* It enables your hardware's vertex cache to actually work, so your hardware can determine if it's already shaded a vertex and just pull the result from the cache instead of having to shade it again.
* It allows for concatenation of multiple primitives which improves draw call batching (by reducing draw call counts) with much less overhead than using degenerate triangles.

For these, whether the vertices are accessed in linear order doesn't matter so much; for the first a more cache-friendly order is what you need, for the second it doesn't actually matter at all.

---
Tags: directx, performance
---


# Question
Title: Do I need to update my DirectX SDK in order to fix a crash with D3D10_CREATE_DEVICE_DEBUG?
I am currently using the DirectX June 2010 SDK. Everything was working fine with my installation until recently. Unfortunately I'm not sure what changed or when, but now when I create a device with `D3D10CreateDevice1()`, it always crashes with a memory error if the device is created with the `D3D10_CREATE_DEVICE_DEBUG` flag. Even reverting to old code which used to work causes this error.

Additionally, `PIX` always crashes every time I use it with my game.

I did some searching and found a lead that I may need to update my SDK installation. This page also indicates that I need to "install the updated SDK Debug Layers".

How do I do this? I have no idea how to install the "Debug Layers"...

Additionally, is it a mistake for me to be using the June 2010 SDK? Apparently DirectX is now included with the Windows 8 SDK, which I haven't been using because I've no interest in Windows 8 development. Is this foolish? Is there any downside to me using the Windows 8 SDK just for Windows 7 DirectX development using Visual Studio 2010?

# Answer
As Chuck Walbourn's blog post that you linked says, a recent Windows update (KB 2670838) broke the debug layer. To get it working again (other than by uninstalling that update) you have to switch to the Win8 SDK version of the Direct3D headers and libraries. The June 2010 SDK is effectively deprecated at this point.

This doesn't mean you have to be running Win8; you can use the Win8 SDK just fine on Win7. If you install Visual Studio 2012 it'll come with the Win8 SDK built in. If you're using VS 2010 or earlier, you have to install the Win8 SDK separately, and presumably you have to manually add the paths to VS.

I'm pretty sure "install the updated SDK Debug Layers" just means install the Win8 SDK.

Unfortunately, PIX is gone for good. There is no way to get it working again for D3D10/11 after this Windows update (it still works for D3D9). The replacement for PIX is VS 2012's built-in Graphics Debugger feature, but there is nothing equivalent in VS 2010 or earlier. So if you use D3D10/11, this update basically forces you to either switch to VS 2012 or go without any form of graphics debugging.
> 2 votes

---
Tags: directx
---


# Question
Title: Cocos3D: weird line between adjuscent 3d planes
I have created a textured plane in blender of size 2×2 and I am using that as a tile. This is the screenshot of what I have done in blender. Nothing special, the default plane on origin, I just added a texture.

I exported this plane to iPhone as POD file. And using below code, I created my tile map.

```
//getting the tile
CC3MeshNode * greenSlate  = (CC3MeshNode*)[self getNodeNamed:@"GreenSlate"];

CC3Vector greenSize       = [self returnSizeOfNode:greenSlate];

//This one printed as 2.0, 0.0, 2.0 .
NSLog(@"greenSlate : %f  %f %f", greenSize.x, greenSize.y, greenSize.z);

float xOffset           =   -3;
float zOffset           =   -3;

for (int column = 0; column < 3; column++) {
    for (int row = 0; row < 3; row++) {
        CC3MeshNode * mesh  =   nil;

        float xStart        =   xOffset;
        float zStart        =   zOffset;

        mesh            =   [greenSlate copy];

        xStart          =   xOffset + column * greenSize.x;
        zStart          =   zOffset + row * greenSize.z;

        mesh.location   =   cc3v(xStart , 0  , zStart);
        mesh.visible    =   YES;

        //add to scene
        [self addChild:mesh];
    }
}

```

And when I run on simulator, I am getting this.

The tiles are at correct position, but there is a black line between each tile. How can I remove these lines?

# Answer
Okay I solved it. The issue was pretty basic, and I guess basics is what I haven't learn about openGL.

I was using a texture of dimension 200 x 200, but openGL requires textures to be the power of 2 to avoid rounding artifacts. So I **changed my texture to 256 x 256, and voila the black lines went away**.

One other thing causing this weird lines is explained here.
> 0 votes

# Answer
Guess this is a rounding issue. Have you tried rounding your vertex coordinates?
> 1 votes

---
Tags: tiles, blender, tilemap, cocos3d
---


title: Camera scrolling and game boundaries

text:
# Question
Title: Camera scrolling and game boundaries
I am making a platformer game in JBox2D and LWJGL that has a scrolling camera, but I have hit a wall with the boundaries of the camera.

Essentially what I have right now is a Box2D world that is being draw on the screen, a viewport being moved by `gluLookAt` and several boundaries specified by Box2D edges that also help keep the player from moving out of bounds. It looks a bit like this:

What I'd like to do is "push" the camera when ever it comes in contact with the edge, but otherwise be centered on the player.

I've tried a couple of methods for this, such as finding the min and max width and height, and simply doing an easy box hit test, and moving the screen accordingly, but that has it's limitations, such as if the world is not in a rectangular shape e.g.

Another method I've tried is doing something where I raytrace from one vertex to another of each edge, and if it comes into contact with the screen, I "push" the screen out of the way, but that hasn't quite worked either

```
    Fixture fixture = boundary.getFixtureList();
    Vec2 point = null;
    boolean hit = false;
    fixtureLoop:
    for(int i = 0; i < boundary.m_fixtureCount; i++)
    {
        EdgeShape edge = (EdgeShape)fixture.getShape();
        Vec2 origin = new Vec2(edge.m_vertex1.x*Main.OPENGL_SCALE, edge.m_vertex1.y*Main.OPENGL_SCALE);
        Vec2 direction = new Vec2(edge.m_vertex2.x*Main.OPENGL_SCALE, edge.m_vertex2.y*Main.OPENGL_SCALE).sub(origin);
        for(float t = 0; t < 1.0f; t += 0.001f) //Raytrace loop
        {
            point = origin.add(direction.mul(t));
            //See if point is within screen bounds
            if(point.x > screenX-Main.WIDTH/2 && point.x < screenX+Main.WIDTH/2 && point.y > screenY-Main.HEIGHT/2 && point.y < screenY+Main.HEIGHT/2)
            {
                hit = true;
            }
        }
            //If hit, find closest vertex
        if(hit)
        {
            float shortestDistance = Float.MAX_VALUE;
            Vec2 vertex = new Vec2();
            for(int v = 0; v < screenVertices.length; v++)
            {
                float distance = point.sub(screenVertices[i]).length();
                if(distance < shortestDistance)
                {
                    shortestDistance = distance;
                    vertex = screenVertices[v];
                }
            }
            Vec2 displacement = point.add(vertex.sub(new Vec2(screenX, screenY)));
            screenX = displacement.x;
            screenY = displacement.y;
            break fixtureLoop;
        }
        fixture = fixture.getNext();
    }

```

What I have here is my attempt that I have played around with WAAAY too much. Essentially what I'm trying to do is detect if and edges are hitting the screen, find the point where they hit, find the closest screen vertex, subtract them to find the displacement between them, and apply it to the screen so that they're no longer in contact: (The screenVertices array is essentially 4 vertices that look like `Vec2(screenX+WIDTH/2, screenY+HEIGHT/2)`, etc)

I was wondering if anyone could help me out, I'm not sure if I'm having logic problems, code problems, or both. Absolutely any help would be appreciated, thanks!

# Answer
> 2 votes
If I'm reading correctly, you want the camera to center on the player except when the player is at the edge of the map. Well, to do this you should first get the world coordinates of the screen, and just move the camera to stay centered around the player. However, you will want to clamp the x and y coords of the camera to the boundaries of the map:

```
//calc camera pos
int camera_x = playerx - (view_width / 2);
int camera_y = playery - (view_height / 2);
camera_x = clamp(camera_x, 0, map_width - view_width);
camera_y = clamp(camera_y, 0, map_height - view_height);

//draw map at camera_x and camera_y regardless of player position

```

---
Tags: opengl, java, box2d, platformer, jbox2d
---


# Question
Title: Need transform matrix to translate the center of the view to a custom position within the target texture
My problem is as follows:

I want to use a single render target texture for drawing 16 viewports where I want to display the 16 different combinations of the marching squares algorithm with my 3D tiles. Each viewport it's supposed to have its own camera and be located at a custom distance from the center of each tile set and this camera should be able to rotate around their center, zoom in and out, etc.

My current issue is that my current projection setting is placing the center of the camera view in the center of the target texture, instead of locating the center of the view in the center of the rectangle corresponding to that viewport.

I assumed I just had to push a translation to the final transform in order to translate the image within the normalized screen coordinates. However, when I tried to do this, it didn't work. How should I do this?

NOTE: Currently I achieved it by using the direct3d viewports, but I'd like to know how should I do if I want to use my custom transform pipeline.

# Answer
It seems I was missing some scaling. I get the code working by adding the following transformations after the projection transform.

```
GMatrix4 trans1;
trans1.Identity();
float TargetWidth = (vp->nWidth*4.0f),     // our target is 4*4 viewports size
    TargetHeight = (vp->nHeight*4.0f); //
switch( m_ProjectionType )
{
default:
case GPROJECTIONTYPE_PERSPECTIVE:
    m_mProjection.FieldOfView( pCameraData->fAngle, vp->nWidth/(float)vp->nHeight, pCameraData->fNearPlane, pCameraData->fFarPlane );

    // Scale to viewport units.
    trans1.Scale( vp->nWidth/TargetWidth, vp->nHeight/TargetHeight, 1.0f );

    // Move our center to the top-left screen corner.
    trans1._41  -= 1.0f;
    trans1._42  += 1.0f;

    // Add viewport offset in screen coordinates.
    trans1._41  += vp->x/(TargetWidth/2);
    trans1._42  -= vp->y/(TargetHeight/2);

    // Add offset from the top-left corner of the viewport to its center.
    trans1._41  += vp->nWidth/(TargetWidth);
    trans1._42  -= vp->nHeight/(TargetHeight);

    m_mProjection *= trans1; // push transform after projection.
    break;

```

Thank you!
> 0 votes

# Answer
As you say, this is exactly the sort of thing which viewports are intended to deal with. Setting up separate viewports would make all of this easy, and is the recommended way to handle this sort of rendering.

However, since you want to know how to do it using a single full-window viewport and instead use scissoring to restrict rendering to one bit of the screen (you could also do this with a stencil buffer, if you wanted something non-rectangular), then what you need to do is to multiply a translation matrix in front of your projection matrix. The translation you want is the offset from the middle of the window to where you want the projection center to be, measured in pixels. In effect, you're just offsetting the whole rendered image. You then use that combined pixel offset * projection matrix as your projection matrix, and proceed as normal.

This is the same method that people writing code for head mounted displays (VR goggles, etc) offset the rendered images so that each eye has a wider field of view further toward the ears than toward the nose; the image is biased so that the center of each eye's view is closer to the nose from that eye's point of view.

(Note that doing this can result in clipping issues, since you end up rendering a view frustum which is offset from the frustum you'd assume was visible based on a naive examination of the camera's matrix. In this specific instance, it should be fine. But if you decided to, for example, offset a whole-screen render by 50 pixels to the left, you'll be drawing 50 pixels further to the right than your clipping code thinks you will be, and so it may choose to throw out some models which actually would have been visible on-screen)
> 2 votes

---
Tags: 3d, mathematics, camera, transformation, multiple-render-targets
---


title: XNA HLSL Shader Glow

text:
# Question
Title: XNA HLSL Shader Glow
I have googled this to death, and I still don't quite understand it.

I'm trying to create a glow effect in XNA using HLSL. A long time ago I was able to do it the way most people suggest which is by sampling the pixels from a texture, however I've always been curious about how you can make it more advanced so that you could do things like set the glow distance and stuff. If I recall from back when I was creating something like this in a similar project, there was always a limit as to how much I could sample before the computer couldn't handle it, hence limiting the glow distance. I wanted to know if there was a more sophisticated way of doing it, one that would have no glow distance limit? And I'm not referring to lighting ground textures either, the idea I have in my head is to have a set of vertices that all join together to create a LineList (for this example lets say they create a cube), so you have very thin lines creating a shape, and then you can set a glow on this object that has no limit to its distance, kinda like how Photoshop works I guess.

Thanks

# Answer
> 1 votes
You can create arbitrary blur effects by first fourier transforming the image, applying the blurring and then transforming it back. This is how Futuremark's 3DMark 11 does it (Whitepaper) and possibly some other modern 3D engines as well. There is also a video of the effect here and explanation of the process. Unfortunately I didn't find any ready-made implementation of this with source code, but you can try searching for *FFT bloom*.

# Answer
> 2 votes
As you said, the way "most people suggest" to implement bloom is via postprocessing. It's clear from your question that you're somewhat aware of postprocessing's limitations. Extend the glow to *unlimited* distance, and your GPU will grind to a halt. On the other hand, you will hit the edge of the screenspace eventually, so "unlimited" is a misnomer.

Unfortunately, that 2nd part of your question is not answerable. "Should I try to do X?" is not suitable for Q&A format. Of course it is *possible* to create a large structure around an object (geometry shaders, modeling extra vertices, etc.) Exactly how you should do it is up to you.

That said, perhaps you don't need to reinvent the wheel. If you can create a custom version of bloom that fills the whole screen, then you won't have to constantly generate new geometry when you want to draw brightly lit objects. (That line list method sounds like a maintenance nightmare to me; I advise against it.)

If I recall correctly, the XNA sample project for a bloom effect already features the ability to adjust the intensity. Have you tried to build on that feature?

---
Tags: xna, shaders, glow
---


# Question
Title: blending with the foreground but not the background
I want to draw some very-semi-transparent objects on top of my scene and have them blend nicely with the other pixels in the scene, but not blend with the background; if I draw a semi-transparent object over the (black) background, I don't want it tainted and drawn dark.

The top scene is what I get - the semi-transparent orange triangle on top is blended with the black background. The bottom scene is what I want - the semi-transparent orange triangle is blended only with the blue triangle, but not with the black background.

How can this best be achieved? Is there a simple blend func that does this? I would like to avoid deferred rendering and such if I possibly can.

Is there some way that `gl.blendFunc` and perhaps `gl.blendFuncSeparate` can be used to achieve this?

# Answer
To build upon Sean's answer, you don't need to make a separate FBO in order to render the effect you're looking for. Unfortunately, you cannot do it in a single pass because you're asking for two different blending operations for the pixels depending on whether or not your orange triangle is overlapping the light blue one. Fortunately, this is an excellent example of a place where the stencil buffer can be used.

In order to generate the effect that you want you need to do the following:

1. Clear the stencil and color bits for your framebuffer.
2. Render the blue triangle into both the color buffer and the stencil buffer.
3. Render the orange triangle once with regular alpha blending testing whether or not the stencil value is non-zero
4. Render the orange triangle again without alpha blending (painter's algorithm) wherever the stencil value is zero.

You will need to make sure that your OpenGL context has a stencil buffer, which you can usually do during creation of the context. I believe that WebGL asks for it explicitly.

Here is some (untested) pseudocode as well:

```
// Enable both color and stencil buffers
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glEnable(GL_STENCIL_TEST);
glStencilMask(0xFF);

// Tell OpenGL to never pass the stencil test, and set the reference value to one.
glStencilFunc(GL_NEVER, 1, 0xFF);

// Tell OpenGL to replace the value in the stencil buffer with the reference value
// whenever the stencil test fails (which is always)
glStencilOp(GL_REPLACE, GL_KEEP, GL_KEEP);

// Clear your framebuffer
glClearColor(0, 0, 0, 0);
glClear(GL_STENCIL_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

DrawBackgroundTriangle();

// Set the stencil function to only draw against non-zero values and to not modify
// the stencil buffer on failure
glStencilFunc(GL_NOTEQUAL, 0, 0xFF);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

// Enable alpha blending as usual
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

DrawForegroundTriangle();

// Set the stencil buffer to only draw against zero values and to not modify the
// stencil buffer on failure. We do not need to call glStencilOp again because
// the arguments will be the same.
glStencilFunc(GL_EQUAL, 0, 0xFF);

// Disable blending
glDisable(GL_BLEND);

DrawForegroundTriangle();

```
> 3 votes

# Answer
Turning Sam's comment into an answer, you need to do all your rending in two passes.

For your first pass, draw only the foreground objects into an off-screen buffer/FBO. If you're using multiplicative blending you might get your desired effect with a white background; with additive blending, you may want a black background. Remember to clear to and update the alpha channel appropriately; you probably want to clear it to 0.

You can then do a second pass to render your background and the completed foreground scene. The foreground buffer should have alpha of 0 wherever there was no foreground object, so you can do a simple blend (or even just an alpha test) when rendering the foreground buffer /texture over the background.

In GL, the psueodocode would be something like (I don't recall the names or parameters of the GL functions; correct as necessary):

```
setup:
  fg_buffer = glGenTexture()
  glBindTexture(fg_buffer)
  glTexImage2D(size_and_format_crud)
  glBindTexture(0)

  fg_fbo = glGenFBO()
  glBindFrameBuffer(fg_fbo)
  glAttachColorBuffer(fg_texture)
  glBindFrameBuffer(0)

render_foreground:
  glBindFrameBuffer(fg_fbo)
  glClearColor(0, 0, 0, 0)
  glClear()

  setup_blend_and_draw()

  glBindFrameBuffer(0)

render_scene:
  render_background()

  render_foreground()
  glBindTexture(fg_buffer)
  glDraw(full_screen_quad)
  glBindTexture(0)

```
> 3 votes

---
Tags: webgl, blending
---


title: Setting texture in effect pass

text:
# Question
Title: Setting texture in effect pass
I created different types of cubes for my cube class and based on the height of the cube, the cube type is different. This means changing the texture for the cube.

```
               if (y >= 1)
                    {
                        SetUpIndicesAndVertices(x, map[x, z] - y, z, vertices, indices);
                        cubes.Add(new Cube.Stone(device, new Vector3(x, map[x, z] - y, z), stone));
                    }

                    else
                    {
                        SetUpIndicesAndVertices(x, map[x, z] - y, z, vertices, indices);
                        cubes.Add(new Cube.Grass(device, new Vector3(x, map[x, z] - y, z), grass));
                    }

```

So I thought this would work, but my texture for all cubes is still grass. I noticed in my draw method these few lines:

```
    foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            no++;
            pass.Apply();
            effect.VertexColorEnabled = false;
            effect.TextureEnabled = true;
            effect.Texture = grass;

```

Which sets every cube to grass. Is there a way that I can set the texture based on each cube type in the list "cubes"?

# Answer
A more OO approach would consist in looping through your objects like this:

```
foreach (RenderableObject rObject in Items)
{
    [...]
    effect.Texture = rObject.Texture;
}

```

of course this would result in you possibly having the context switch texture very frequently and unnecessarily. If you have the objects sorted by texture, you can move that assignment outside and before the loop. Then you just have one such render-loop for each different category of items that share the same properties.

I suggest you implement some functionality representing meta-information about the items you are going to render. This way you can sort them according to different properties (i.e.: texture, rendering order \[opaque, blended\], geometry. Then you pass this information to your draw call so that it sets the correct state.
> 0 votes

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


# Question
Title: OpenGL FBO, render off screen and texture
I need to do some offscreen render to use the rendered image in something different from OpenGL context (for instance I need to use the image in a QListWidgetItem inside a Qt application). After documenting a little bit I've found that Frame Buffer Object (FBO) is what I have to use in combination with `glReadPixels` for getting the raw image from OpenGL/GPU into my application. So, here I am against FBO.

I've found that I need to attach the FBO to a texture otherway it does not work and `glCheckFramebufferStatus` gives me: `GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER`. So when I try to init the FBO I need to add also `glGenTextures` and `glBindTexture` etc..

But.. why? I don't need a texture for now.. why do I have to declare/init/bind (don't know what is the best word here) a texture?

What is the "minimal" FBO setting for get the images? And what about if in my application I need also stencil or depth images? Are things different?

And using back buffer instead of FBO? Is it slower? Do I still need a texture?

I'm kind of afraid of using textures because of a lot of parameters () I don't understand for now..

Sorry for confusion..

# Answer
In OpenGL terms, a "Framebuffer" is an object that holds references to images which can be used as render targets. "Framebuffer Objects" are user-created framebuffers who's image references come from images you explicitly allocate (as different from the "Default Framebuffer", who's images come from the OpenGL context).

Framebuffers are not the *sources* of images; they only hold references to existing images, like pointers.

There is no "image object" in OpenGL. There are objects that contain one or more images. FBOs can therefore take their images from one of these objects. The object can be a texture or a renderbuffer. Textures can have one or more images (array levels, mipmap layers, cubemap faces), while renderbuffers only have a single image.

It sounds like you just want a renderbuffer or two for your color and depth/stencil images.
> 1 votes

---
Tags: opengl, textures, frame-buffer
---


# Question
Title: Camera Matrix Transform to scroll through level - Monogame, XNA
I am trying to change the way I scroll through a level. Currently I have a static camera class which stores a direction enum and a vector 2 position. This class then has a method to move the position of the camera (vecotr2) based on the direction value. This is called in the update method. Then when drawing my tile grid I loop through the number of visible tiles in the viewport and add the position of the camera to the counters to get the texture of the tile in question to draw. (note the main game class calls the level draw class passing it the sprite batch after starting it)

This seems like a pretty bad approach. I have seen in a few place that I should be using a matrix transformation to move the camera and then pass this as part of the draw method. However, I have absolutely no idea how to achieve this, I am literally lost.

I have attached my code below, and would greatly appreciate any advice you could provide.

Camera:

// Stores the position and scroll direction of the camera. static class Camera {

```
static public Vector2 Position;

static public ScrollDirection Direction;

public static void MoveCamera(Level level) {
    Vector2 scrollSpeed = new Vector2(20, 18);
    if (Camera.Direction == ScrollDirection.Up)
    {
        Camera.Position.Y = MathHelper.Clamp(Camera.Position.Y - scrollSpeed.Y, 0, (level.Height * 50 - level.mViewport.Height));
    }
    else if (Camera.Direction == ScrollDirection.Down)
    {
        Camera.Position.Y = MathHelper.Clamp(Camera.Position.Y + scrollSpeed.Y, 0, (level.Height * 50 - level.mViewport.Height));
    }
    else if (Camera.Direction == ScrollDirection.Right)
    {
        Camera.Position.X = MathHelper.Clamp(Camera.Position.X + scrollSpeed.X, 0, (level.Width * 50 - level.mViewport.Width));
    }
    else if (Camera.Direction == ScrollDirection.Left)
    {
        Camera.Position.X = MathHelper.Clamp(Camera.Position.X - scrollSpeed.X, 0, (level.Width * 50 - level.mViewport.Width));
    }
}

}

```

Level:

```
public void DrawTiles(SpriteBatch spriteBatch) {
    // Calculate the position of the camera in terms of tiles.
    Vector2 cameraPosition = new Vector2(Camera.Position.X / Tile.Width, Camera.Position.Y / Tile.Height);
    // Calculate the offset of the camera position for when it is part way through a tile.
    Vector2 cameraOffset = new Vector2(Camera.Position.X % Tile.Width, Camera.Position.Y % Tile.Height);

    // Loop through the number of visible tiles.
    for (int y = 0; y <= mViewportTiles.Y; y++) {
        for (int x = 0; x <= mViewportTiles.X; x++) {
            // Check that we have not exceeded the dimensions of the level.
            if (x + cameraPosition.X < Width && y + cameraPosition.Y < Height) {
                // If the tile is not an empty space.
                if (tiles[x + (int)cameraPosition.X, y + (int)cameraPosition.Y].Texture != null) {
                    // Get the position of the visible tile within the viewport by multiplying the counters by the tile dimensions
                    // and subtracting the camera offset values incase the position of the camera means only part of a tile is visible.
                    Vector2 tilePosition = new Vector2(x * Tile.Width - cameraOffset.X, y * Tile.Height - cameraOffset.Y);
                    // Draw the correct tile based on the position of the camera in the appropriate position within the viewport.
                    spriteBatch.Draw(tiles[x + (int)cameraPosition.X, y + (int)cameraPosition.Y].Texture, tilePosition, Color.White);
                }
            }
        }
    }
}

public void Update(GameTime gameTime) {
   Camera.MoveCamera(this);
}

```

Thanks in advance

# Answer
The code to set up your matrix should go something like this:

```
Viewport vp = GraphicsDevice.Viewport;

Vector2 cameraWorldPosition = (whatever);
Vector2 screenCentre = new Vector2(vp.Width / 2, vp.Height / 2);

// This first translates the camera target back to the origin (0,0).
// In SpriteBatch the origin normally appears in the top left of the screen
// and generally you want to centre it. So this then translates from the
// origin to the centre.
Vector2 translation = -cameraWorldPosition + screenCentre;

Matrix cameraMatrix = Matrix.CreateTranslation(translation .X, translation .Y, 0);

```

Then pass it to this overload of `SpriteBatch.Begin`, like so:

```
spriteBatch.Begin(0, null, null, null, null, null, cameraMatrix);

```

Then just `Draw` your sprites in their "world space" positions.
> 3 votes

---
Tags: xna, c#, camera, monogame, side-scroller
---


# Question
Title: Storing texture ID's for fast global retrieval
Simple question:

What is the fastest way to retrieve a texture ID, given an enum value? Say I have 100 textures, what would be the fastest way to get one texture ID?

Make a texture manager with a `HashMap<TextureEnum, int>` so I can call `TextureManager.get(TextureEnum.button_hover)`? (example, I know hashmaps are slow).

# Answer
> 1 votes
First of all, why do you think hash maps are slow? For run time data they are quite fast!

An easy and good to start with approach is using a `std::unordered_map` which maps `GLuint` texture ids to `std::string` names.

```
#include <string>
#include <unordered_map>
using namespace std;

unordered_map<string, GLuint> textures;

```

Then you could expand this to an easy manager by providing functions to create, get and delete textures. I wrote down this three functions without testing, but I think it is helpful anyway.

Function to create a new texture, load image data to it and add it to the system.

```
void TextureCreate(string Name, string ImagePath, bool Mipmapping = false;)
{
    // load image file from disk
    // ...

    GLuint id;
    // create OpenGL texture
    // ...

    textures.insert(make_pair(Name, id));
}

```

Function to get a created texture.

```
GLuint TextureGet(string Name)
{
    auto i = textures.find(Name);
    if(i == textures.end())
    {
        cout << "Texture with this name doesn't exist." << endl;
        return 0;
    }

    return i.second;
}

```

Function to delete a texture from the system.

```
void TextureDelete(string Name)
{
    auto i = textures.find(Name);
    if(i == textures.end())
    {
        cout << "Texture with this name doesn't exist." << endl;
        return;
    }

    GLuint id = i.second;
    // delete OpenGL texture
    // ...

    textures.erase(i);
}

```

Use case example.

```
// initialization
TextureCreate("button", "images/button/default.png");
TextureCreate("button hover", "images/button/hover.png");
Button.texture = TextureGet("button");

// on hover event
Button.texture = TextureGet("button hover");

// on blur event
Button.texture = TextureGet("button");

```

---
Tags: opengl, java, textures, resource-management
---


title: 2D game level progression

text:
# Question
Title: 2D game level progression
I'm creating a 2D game similar to Mario. What is a best practice to allow the character to move through the level given a limited screen size?

The way I have it now is the Player moves across the screen, and when they reach the far right edge, you reset them to the far left of the screen (basically teleport them back to the left side...). And if they're at the far left edge, keep resetting them to the far left side (to simulate a wall)

Check Player Bounds:

```
public void checkPlayerBounds (Player player) {
    if (player.getY() >= height-(playerHeight+25)) {
        player.reset("down");
    }
    else if (player.getY() < 0) {
        player.reset("up");
    }
    else if (player.getX() > width-(playerWidth)) {
        player.reset("right");
    }
    else if (player.getX() < 0) {
        player.reset("left");
    }

```

Reset:

```
public void reset(String val) {
    if (val.equals("down"))
        yLoc = gameboard.getHeight()-(height+30);
    if (val.equals("up") )
        yLoc = 0;
    if (val.equals("left"))
        xLoc = 0;
    if (val.equals("right"))
        xLoc = 0;
}

```

So I'm basically just either teleporting them when they get to the far right to simulate them (moving forward), at which point I would draw the applicable background and items (each time person reaches far right side, have a counter that is associated with the correct things to load on the screen)...

---

Or, should it be that the actual Player character doesn't move when you press right... it's actually the background items and map that moves (loads)?

If so, how would that look from a pseudocode/design perspective?

Thank you

# Answer
> 2 votes
Well, the whole solution is a lot of code, but there are a few concepts you need to be aware of:

The `Camera`: For every goomba and block's Draw method, they need a particular offset defined by the camera's position. So if the camera is at X:0,Y:0, the goomba's screen coordinates match their world coordinates. If the camera is at X:5,Y:0, then his world coordinates stay the same - none of his own values needs to change - but each run of his draw method would subtract 5 x from his own position to get the correct position to draw to.

Remember that the `Player` should not in any way be special, or "exempt" from the rules of the camera. He uses that same offset to draw. He'll usually stay at around the same spot as the camera, but many novice game programmers that always draw him at a special, locked screen coordinate tend to run into trouble fast (for instance, if you reach the end of the level, and the player should now move without the camera following him)

The `World` would likely be all loaded at once; no need to seperate it into individual screens. To ensure challenges are similar on each run, you could freeze each goomba's AI until their X coordinate is close enough to the Camera's X.

It might help you to draw it out a bit on paper. Initially, programmers are thinking in terms of how sprites should be positioned, and how they move across the screen. In truth, it makes more sense to think of how the world is laid out, and where your little rectangular view of it is moving around. It also makes it much easier to debug, since every goomba, block, and pirahna plant isn't having its position updated for each little camera movement.

---
Tags: java, maps
---


title: Game Map Implementation

text:
# Question
Title: Game Map Implementation
I want to know how I can create a virtual town or city (like skyrim towns or gta4 liberty city)

Should I create something on paper and copy coordinates? (Building1 floor corner coordinates are these, ceiling coordinates are these, 2nd floor coordinates are these etc, and then road1 coordinates are these...) And then apply texture on these things? Start with just 1 building and extend it in time?

But this seems like a ton of work. For simplicity if we assume that there are 5 buildings on a road, this is like 90 vertices. And if I decide to make a house wider, then many things will be affected and I have to find new coordinates for every house corners. How did the developers of GTA 4 do it for example?

I would like to know an appropiate method to create a static virtual map where the player can move into houses and interacts with objects in it. Please note that these buildings are not cosmetic only. I should be able to place objects in houses such as tables and the player should be able to jump on it etc.

Thank you, I will vote when I have the reputation.

# Answer
The models themselves are usually done in a dedicated graphics program (3ds MAX, Maya, etc if you have the funds, Blender and others if you don't). Once you load such models into your program (either by writing your own importer, or using your engine's importer), you can place the like blocks.

Modern engines usually come with a dedicated editor where you place the premade objects. Play around with Skyrims creation engine for a better grasp of how it works.

Once you load the mesh data it is used for collision detection.
> 1 votes

# Answer
There are really several approaches to this. The way the maps for Grand Theft Auto 3 and beyond were (likely) made is the entire map or large parts of the map is/are created in a 3D modeling program such as 3DS Max or Maya, then split up into pieces (a single lot or a neighborhood may be a piece, an airport runway may be a piece, a bridge will be a piece) which can be loaded into the game as the player approaches them. There are also low-poly Level-Of-Detail versions of these pieces which can stand-in for the high-detail version of a piece when viewed from a distance. In-engine, these pieces are fitted together to create the entire map.

I can't speak for Skyrim because I don't have the game or the editor, but TES: Oblivion and Fallout 3/New Vegas as well as Far Cry and Crysis make use of a large heightmap for terrain and then objects such as buildings and rocks and trees are placed upon the heightmap. CryEngine would probably be excellent for making such a map. You still must model the objects themselves in a 3D editor, but this may be the easiest route.
> 1 votes

# Answer
For many simple games, you can use an existing editor. I think for some purposes, people have managed to just use 3D modelling programs as their editor, but I've never done that.

Another random example: Valve's Hammer Editor stores block data as text files in their .vmf's. If you're making a pretty small test game with little need for optimization, you could load those text files as your levels.

Otherwise, consider the possibility of implementing an existing open-source level editor, creating your own in your choice of UI-development language, or, as some recent engines have done: Integrate a level editor with your game, so it's easy to jump to game mode and check how well something works.
> 1 votes

---
Tags: game-design, models, maps
---


# Question
Title: Best Practices for class usage and game architecture
I'm making a 2D game similar to mario in Java.

I have some questions about class organization and proper method usage.

I have the following classes:

* Main: runs the game in a JFrame
* GamePanel: JPanel with boundary rules, timer, paintComponent, scoring, keyboard input, collision check
* Player: only knows about its own attributes... has getter and setter methods for `x, y` location, `height, width, weight` etc...
* Item: Same thing as `Item` class... this class will be used for items in the game, like bullets, cars, etc...
* Physics: I was going to use this class to contain all actions for all items in the game (items class, player class, etc)... Like the rules for jumping, or running, etc...

Am I using the classes appropriately? I'm not sure whether each class should contain its own unique methods...

For example, only `Player` class objects will be able to jump and run... So should Player class have `jump()` and `run()` methods? Or should it just have `setX()`, `setY()` methods which alter its location based on `run()` from another class like `Physics()`?

And for a gun, I have `shoot()` which creates a new Item

```
 bullet = new Item(this, player.getX(), player.getY()+40, 25, 10, 10, bulletVelX, 0);

```

But as you can see below, I'm actually moving the bullet via the `timer()` class by calling the Item class's `autoMove()` method to change the bullet Item's location.

**I'm also confused on the correct usage of timer():**

I'm using it to run methods at a certain interval if a given `boolean` is set true...

```
public void timer() {
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            collisionCheck();
            if (jump) {
                player.jump(velocityX, -velocityY);
                velocityY--;
                checkPlayerBounds(player);
                repaint();
            }
            if (shoot) {
                if (!bulletMag.isEmpty()) {
                    for (Item bullet : bulletMag) {
                        bullet.autoMove(bullet.getVelocityX(), bullet.getVelocityY());
                    }
                    if (bulletMag.size() > 30) {
                        bulletMag.clear();
                    }
                    repaint();
                }
            }
        }
    }, 0, 100);
}

```

Is is okay to put all that logic **inside** the timer class? Or should the timer class be kept as clean and empty as possible? Is that where my main **Game loop** is?

**Lastly, paintComponent():**

I put a paintComponent in each class (Player, Item, and GamePanel so far), and paint them by calling them from within the GamePanel's paintComponent. Is that right?

```
public void paintComponent(Graphics g) {
    g.setColor(Color.white);
    g.fillRect(0, 0, width, height);
    player.paintComponent(g);
    for (Item bullets : bulletMag) {
        bullets.paintComponent(g);
    }
}

```

---

**So, in summary is my usage of classes, timer, and paintComponent correct?**

# Answer
> 2 votes
Notch actually made a Mario clone in Java and has the source code available for perusal. Notably he has a Sprite class that gets extended by classes named things like Fireball, Enemy, and BulletBill. His Mario class is also a subclass of Sprite but whether that class is called Mario or Player probably won't help or hurt in the whole scheme of building this. Passing the Graphics context to the classes that represent visible constructs so that they can draw themselves will work out nicely and is indeed what Notch has done. However, you will most likely want to control when this happens instead of letting Swing make that choice for you. This would mean calling the equivalent of paintComponent yourself which would then make it unnecessary for these things to be JComponents.

As for the use of TimerTask to update a the state of the game; when the game hits the performance wall you won't be simply dropping to a lower framerate, the game logic itself will slowdown. This will be noticeable even when the drop in framerate on its own would normally not be. What's worse is that the TimerTask schedules will stack up during this time so the player will experience a period of slowdown followed by a fast-forwarding of both the game logic and framerate. When a game drops frames we expect to miss out on things, not for the passage of time in the game world to be altered. It is common to separate the logic and graphics updates into multiple threads for precisely this reason. The thread that controls the rendering could have its core logic look something like the following:

```
// Inside the run function of a class implementing Runnable
while (running) {
  double lastTime = time; // save the last time the loop ran
  time = getTime();
  if (time - lastTime < TARGET_FPS) {
    // do nothing to avoid being greedy with CPU cycles for no good reason
    Thread.sleep(5);
  } else {
    // draw graphics and process gamelogic with respect to real time, not anything
    // tied to the graphical representation of time
    renderGraphics(time);
    processGameLogic(time);
  }
}

```

---
Tags: architecture, oop
---


# Question
Title: How to detect whether my Java application is active?
I want to pause my game (written in Java Swing), when the player switches to another application.

But I did not find a way to detect this switch. `window.isActive()` only works for multiple windows within one Java application. But it does return `true`, when a different application has the focus.

The same is true for the `KeyboardFocusManager`, it returns the window of my application that had the focus before the focus was given to another application.

# Answer
> 2 votes
Use the focus subsystem, as documented here.

An example of detecting focus being gained:

```
//Make textField get the focus whenever frame is activated.
frame.addWindowFocusListener(new WindowAdapter() {
    public void windowGainedFocus(WindowEvent e) {
        textField.requestFocusInWindow();
    }
});

```

---
Tags: java, swing
---


title: How many levels should I make?

text:
# Question
Title: How many levels should I make?
One issue I grapple with across many of my games is trying to decide **how many levels to put in my game.** This is across genres and platforms.

In general, constraints that may decide -- although they are not applicable in my case -- can include:

* Pre-determined schedule or release dates
* Fixed budget
* The game's story finishes/concludes
* (PCG games): difficulty becomes "impossible"

These are all great, but not sufficiently constraining as to tell me how many levels to make.

Another constraint that sounds good in theory but is hard to implement is game time -- for example, Mario or Super Meat Boy, I can guesstimate `x` minutes per level, and target `y` minutes of intended total gameplay, yielding `y/x` levels.

But none of these seem quite right to me. It seems like there should be a better way to decide when to add more levels and when to stop.

# Answer
> 12 votes
Asking how many levels to include in a game is sort of like asking how many paragraphs to include in your essay, or footsteps to take in your journey. Once you have a clear idea of your destination and your path, the question answers itself.

But it is a question worth considering because it leads to some interesting observations about game design.

# What is a level?

Let's take a step back and look at what a level is, what it does, and what is its purpose.

* It introduces something new to the game, such as:
    + Higher difficulty *e.g. space invaders, pacman*
    + A new mechanic or puzzle *e.g. donkey kong*
    + Progressing the story
* It's used to control pacing, giving a temporary lull in the action. Sometimes entire levels are devoted to this purpose, *e.g. bonus stages*
* It rewards the player, giving them a sense of progress *e.g. the castle fireworks in Super Mario Bros*
* It is often used as a checkpoint, somewhere players can resume if they fail in the game
* Historically, there were technical limitations to how much content you can have all together, so the game was split up into levels

Usually levels are used for many of the above reasons, but you may have noticed a common thread: **levels encompass a unit of content, a self-packaged experience meant to be consumed as a whole**. That isn't to say you must consume one unit of content at a time, but usually you (are encouraged or compelled to) finish playing after the end of a unit.

Units of content occur in many places, outside video games too, and there are many ways artists/authors encourage audiences to consume these in units. Books have chapters, and readers often - if they have a choice - stop and start reading between chapters. TV series have episodes, where each episode covers a self-contained story, sometimes within a greater story arc. Some media have only one unit of content, for instance movies are best enjoyed in a single sitting.

So it is with games; some have lots of small units of content, *e.g. Angry Birds*. Some have a single large unit of content, *e.g. Civilization*, where you are never encouraged to take a break until you've finally conquered the world, some 20-30 hours later. (Some days I think Sid Meier isn't aware that his players need to *sleep*.)

I believe the question "how many levels should I make" is better answered if you split it into two:

* How long should my "units of content" be?
* How long should my game be?

And divide the second by the first to get your answer.

# How long should my levels be?

There are many factors that will affect the length of your levels:

### How long do I want my players to play the game, at a time?

This goes right to the heart of your game design. If I'm standing in a line, I'd play Angry Birds or Candy Crush; if I were at home on a lazy weekend, I have more time and attention available - I could watch a movie.

### How much time is necessary to teach the player a new mechanic?

This depends on the complexity of your game. A particularly complex strategy game might require long levels.

### How much content do I need to meaningfully progress the plot?

For story-driven games, the appeal comes from seeing the plot unfold, and if your levels are too short there is simply not enough time to meaningfully move forward with your plot.

# How long should my game be?

The answer to this one depends on quite a few things I've touched earlier. Your game should be:

* Long enough to tell the story, but your levels should be meaningful in terms of plot
* Long enough to teach the player about the game, but your levels should avoid being too repetitive
* Long enough to keep players interested, but keep in mind if it's worth the budget!

Sometimes there is no upper limit to the length of your game; you can keep making it longer so long as the cash is flowing in and the players are there. Just as they keep making episodes of *The Simpsons* by adding characters or even rehashing plots, you can add levels, new mechanics, rehash old mechanics... and sometimes the players love it!

# Answer
> 3 votes
Based on my experience (mainly on the action/puzzle genre), I could only say to you that it depends on the features.

For example when I had a new set of puzzle logic, I needed 1-2 levels to introduce the feature, then 3-12 levels to build it up and complicate it / fix the difficulty curve, and then maybe in those 3-12 or in some extras I would mix this new feature with previous ones that appeared.

A great example of how level design works is Cut the Rope! They really nailed this.

Hope you find my experience useful.

# Answer
> 2 votes
A somewhat viable choice is to have a constant of levels you want to make that aims at some % of the budget( and or time) like 70 or 80. Once you have achieved that you have some freedom for the remaining time/money.

The options are almost limitless: you can start adding achievements (if you haven't already) You can add extra levels, challenges, bonus content like skins, rewards add extra rooms to some levels.

tl;dr: Finish the game with not the optimal amount of levels for the time/resources add extra content.

Edit: The X minutes per level is impossible to make, since how fast the player will go through the level depends entirely on his play-style experience. For example an FPS veteran will speed through CoD missions (let's consider that they will be played) where as an RTS player will slowly and methodically go through each part of the level.

# Answer
> 1 votes
I like this question because it is something most developers have to face.

The only thing I would like to add, is that you NEED to have your game played by impartial, virgin (they haven't played it before) testers.

You could put in 100 levels to get X hours of gameplay, but if it is you who is testing (you the programmer who knows the game's algorithms and quirks, you the gamer who is already an expert with the controls, you the designer who knows the level design and shortcuts like the back of your hand) then your calculations may be way off. When it comes to new players, you may only need 20 levels to get the same X hours of fun.

I speak from experience as a lone indie developer.

# Answer
> 0 votes
Here is a formula I use for iOS specifically. In iOS you're allowed to create about 25 leaderboards / gamecenter boards. So depending on what you want to show as leading metrics such as time or score you can have 25 levels. If you have leaderboards with both metrics, you can only have 12 levels a piece. 12 leaderboards for time, and 12 for score. This is what I generally use for iOS only, not sure what it matriculates to on other platforms.

Of course you don't have to have game center integration and you can create as many levels as you want! Or you can aggregate multiple times/scores into a single leaderboard(s). Just some food for thought.

---
Tags: game-design, levels
---


# Question
Title: How can one impliment multiple control schemes for a single player?
I am working on a platformer and I want to have the player be able to switch control types based on items that may be carried + default controls for things such as water, in the air, on the ground etc...

I understand how to make a player move in anyway I desire but I don't understand how I can encapsulate these behaviors into their own classes and call and apply them to the player when needed.

The way I have it is this:

Input is handled by the input class. During the update, the player looks at the input class. It then figures out how it should move itself with a bunch of if statements to figure out what rule set should be applied. For example: Am I in the water? Am I on the ground? Am I in the air? and so on. Based on the previous questions the player object then decides how to interpret the input. After everything is done, the results are edited by world rules which applies things such as gravity, etc...

This seems to work but it is not elegant and results in duplicated code. Its ugly. How should I set up some classes and how should they talk to each other? All I manage to do is make a mess of my code trying to class it out. I have searched around for sometime on how I need to do this but can't find anything.

Any pointers on where I can go to figure this out? Any advice? I just know I need the code contained so it's easy to debug later and figure out what is happening.

# Answer
Add an intermediate layer.

You have some kind of `PlatformInput` that manages all the different input methods and generates low-level events like `KeyUp`, `KeyDown`, etc.

Another layer then processes these messages into logic events, like `MoveUp`, `Jump`, etc. It can do this by receiving the inputs, mapping keys to logic events, and doing only the most basic checks. The main idea is that you have multiple events coming into this layer from multiple devices but only a simplified and unified output stream of events.

The actual character controller then processes the logic input events as normal, e.g. if it gets a `Jump` event it makes sure the player is actually allowed the jump and if so makes the player avatar jump.

The mapping layer an be data-driven to a degree, so e.g. you have an entry saying `KeyDownEvent:<JumpKey> --> Jump` and `ButtonDownEvent:<JumpButton --> Jump` and then players can change mappings for `JumpKey` to whatever keyboard key (or keys) they want and the same for buttons (or select from some pre-configured controller layouts). In this way, you both have easy support for multiple devices and multiple configurations.

I would also put more intricate input "combinations" here. That is, if you have an attack that requires holding the left trigger and pushing the A button, the logic event should still just be `Attack` and the mapping layer is responsible for sending that event when A is pressed but only if the trigger is held, e.g. `ButtonDownEvent:<AttackButton> AND TriggerValue:Left>=0.9 --> Attack`. Combo attacks are a different story and belong in your character controller, since the state is dependent on the game/avatar.

Basically, all input handling that is dependent on low-level input state goes into the mapping layer. All input handling that is dependent on the game state goes into the character controller. Any input handling that is somehow dependent on both should be split up into separate parts each dependent on either only low-level input or only game state.
> 6 votes

---
Tags: xna, c#, platformer, control, behavior
---


# Question
Title: Gravity and collision detection interfering with player movement
I am attempting to implement collision detection for a 2d sidescroller game and I'm having trouble keeping gravity from interfering with player movement.

Every frame I get and handle input, creating values for a point that represents the players movement vector. I then add gravity to the vector and check for collisions. This is the way AI will be handled as well.

The problem I'm having is when the player is on a floor tile, even if the input says to walk horizontally, after I add gravity to the move vector, collision detection returns a collision so the movement is completely negated.

I know i can test which a is is the problem, negate that and move the player but then if I change the players movement vector inside collision testing, wouldn't I have to cull for collisions again based off the new move vector?

I don't know if this has to do with input handling or collision testing. So how should I go about adding gravity to the players movement?

# Answer
> 2 votes
It sounds like the issue is your collision resolution mechanism. The correct resolution depends on the particular type of collision, but here's some points that could be your issue:

Collision-generated impulses should be directed along the normal of the collision surface. In the case of static, axis-aligned world geometry, you just need to zero-out that component of the velocity. For example, when a character lands on a surface, it's just the y-component of his velocity that should be set to 0, not necessarily all of his velocity. You can certainly damp his x-velocity, but for the reason you're experiencing it shouldn't just be zero'd out.

Now, it's possible that once you've done this you still have collision issues. Imagine a character standing on a solid, square block, and walking onto an adjacent touching solid, square block. When he first tries to step onto the second block, he will be colliding with the corner. For that moment, the face of largest penetration will in fact be the side, not the top. He could be 'colliding' with the corner of the block facing him. I can't speak with authority on the best resolution for this issue, but I think adding some penetration tolerance should do the trick.

An alternative, one I don't like and I don't know why you would choose to do it but I offer it anyway because I don't know anything about your game, is to try to manage gravity with some sort of state machine. You do gravity checks on your physics-enabled objects and toggle between gravity states. Again, I don't see any advantages to this, but if you're doing something strange with gravity or game mechanics, this could work for you.

In summary, it sounds like your gravity system is working and the issue is collision resolution, and not gravity, per se.

# Answer
> 2 votes
It sounds to me like your problem is that you are blindly applying gravity without considering the effects of whatever the character is standing on. If there is something below you there is no meaningful effect of gravity!

Furthermore, you don't want to simply not move if a collision results. Consider what happens if you jump off something--at the point the next movement frame intersects the ground you're frozen in space for all eternity.

Instead you want to stop the character (or perhaps only zero out the velocity in the direction that caused the collision) at the point of impact but allow them to move that far.

Simply stopping the movement only works if you don't care about exactly where you are. (And, yes, that can happen. I did a simple 3D first person journey through an environment once--more an experiment in 3D than a real game. I implemented collision handling by zeroing any velocity component that would take you within .1 of a wall. The result is how closely you can approach the wall depends on how fast you impact it, the guy heading straight for it will be stopped sooner than the guy approaching it at a very narrow angle. Without a debug display showing the actual numbers you would never know, though, as being first person you can't tell exactly how close you are anyway as the point of contact isn't in your field of view.)

---
Tags: collision-detection, input
---


title: Different types of cubes

text:
# Question
Title: Different types of cubes
I'm looking into making 4 types of cubes; grass, stone, dirt, and empty. I have a cube class that is just for storing the location of the cube.

```
    public Cube(GraphicsDevice Device, Vector3 Position, Texture2D Texture)

```

I want the Texture2D to be changed to something like CubeType. In my cube class, I have a grass and stone class which both inherit cube, but I don't know how to make that work for what I want.

```
    public class Grass : Cube
    {
        public Grass()
        {
            isMineable = false;
        }
    }

    public class Stone : Cube
    {
        public Stone()
        {
            isMineable = false;
        }
    }

```

The only thing that makes each cube differ from each other is the texture and if theyre mineable or not. What's the easiest way to implement what I want? I guess one way of doing it is just adding another parameter to Cube(bool isMineable), but for learning purposes I want to see if there's a better way to do it.

# Answer
You have two (common) problems with this design.

First, you don't need a `Cube` class at all. Things like a cube's position are implicit if you store your data appropriately. Having a separate class is a waste of memory and, due to how C# gives you no control on memory layout of class objects, is going to hurt performance when you iterate over all your cubes.

Second, don't use inheritance and classes unless you really need them. Always try to reserver inheritance for logical interface extension, not "is-a" relationships between object. Yes, a `StoneBlock` is a `Block`, but that's a real-world taxonomy issue, not something the code needs to at all care about.

First, change your representation of blocks. You need a `BlockDescriptor` that describes a type of block, similar to your sub-classes but data-drive. The actual type can be a free-form integer and all the data loaded from a file for easy extensibility and modding. To start, you can hard-code a table.

```
public static class Blocks {
  public enum EBlockType { Air, Stone, Grass, Wood };

  public class BlockDescriptor {
    public EBlockType BlockType;
    public string DescriptiveName;
    public Texture2D Texture;
  }

  public static BlockDescriptor[] TypeTable = {
    { EBlockType.Air, "open space", null },
    { EBlockType.Stone, "granite", LoadTexture("stone.png") },
    { EBlockType.Grass, "dirt & grass", LoadTexture("grass.png") },
    { EBlockType.Wood, "oak", LoadTexture("wood.png") },
  };

  public static DrawBlock(Device device, Vector3 position, EBlockType type)
  {
    Texture2D texture = TypeTable[type];
    if (texture != nullptr)
      your_draw_cube(device, position, texture);
  }
}

```

Now you can easily add rows to this table. You can do it at runtime, from a file, however you want. Add new fields to `BlockDescriptor`, like `IsMinable`, as needed.

The other problem is that you only need a single integer and an array to store your world (or a chunk in your world).

```
class Chunk {
  public const int WIDTH = 512;
  public const int HEIGHT = 512;
  public const int DEPTH = 512;

  private int[] _Blocks;

  public Chunk() {
    _Blocks = int[WIDTH * HEIGHT * DEPTH];

  public int GetAt(int x, int y, int z) {
    return _Blocks[y * WIDTH * DEPTH + z * WIDTH + x];
  }

  public void Draw(Device device) {
    for (int y = 0; y < HEIGHT; ++y)
      for (int z = 0; z < DEPTH; ++z)
        for (int x = 0; x < WIDTH; ++x)
          Blocks.DrawBlock(device, new Vector3(x, y, z), Blocks.EBlockType(GetAt(x, y, z)));
  }
}

```

To store more data than just the type, you can use bit manipulation to pack all the data into an int (or long or short, whichever you need and no larger). You could also use a C# struct type if you want easy mode.

The idea of this data structure is that the entire chunk is tightly packed into a single contiguous chunk of memory. The CPU doesn't get stuck in a wait state while chasing down a bazillion `Cube` instances.

Also note that at no point did I store a refernce to `Device`. Blocks themselves have absolutely nothing to do with graphics; they're data. Neither the block instances nor the chunk have any reason at all to hold on to the device. You easily make the argument that `Blocks.DrawBlock` should be split out into a separate place, too.

Really, you'll end up doing that anyway. You do *not* want to just draw a cube for each block. That is quite inefficient. First, it means one draw call per cube. That will be *slooow* and heavily underutilize your GPU which is designed for massive parallelism and drawing thousands of triangles at once. Also, if you have two blocks next to each other, why spend time processing the triangles between the blocks that you can't possibly see anyway? You'll want a separate pass that iterates over the blocks, finds outward faces (the faces of blocks that are adjacent to empty space), and push the triangles for those blocks into a separate mesh array and call this any time a block changes (which won't be too often). Note you'll need to switch to using texture atlasing rather than individual textures for each block for this to work.

Then your nice separate rendering code can just draw that mesh. One single draw call, no excess cube faces, super fast and efficient if nothing is changing (which, the vast majority of the frames, nothing will be).
> 2 votes

# Answer
I think are doing over engineering the cubes...

it would be easier to use an enum, it is better because let's you indexing cube properties in arrays or sorting the cubes easily,

You don't need to store the texture and graphicsdevice for each cube... you can implement a CubeCollectionRenderer or similar where you manage that...

```
  enum CubeTypes { Grass, Stone, ..}

  public class Cube
  {
      public Vector3 cubePosition { get; set; }
      public bool isMineable { get; private set; }
      public CubeTypes CubeType {get; private set;}

      public Cube(CubeTypes CubeType)
      {
         this.CubeType = CubeType;
         this.isMineable = (Cubetype == Cubetypes.Stone);
      }
  }

  public class CubeCollectionRenderer {
      // Approach 1: One texture atlas that contains all the cube type textures,
                     the texture portion sources can be included in the shader and
                     pass the cubetype to index the right texture portion in the
                     atlas.
                     This is quite good and can be used with intancing techniques.
      Texture2D  Atlas;
      Rectangle[] Sources;
      List<Cube> Cubes;

      // Approach 2: Single textures for each cube type, to avoid state changes
                     drawing cubes is recomended to keep the cubes ordered by
                     CubeType.
      Texture2D[] Textures;
      SortedSet Cubes = new SortedSet(
          delegate (Cube a, Cube b) { return (int) a.CubeType - (int) b.cubeType; }
      );

      public CubeRenderer(GraphicsDevice device) { .. }

  }

```
> 4 votes

# Answer
Well I figured that out easy enough. My brain wasn't working for a bit so here it is.

```
    public class Cube
{
    GraphicsDevice graphicsDevice;
    Vector3 cubePosition { get; set; }
    Texture2D texture { get; set; }

    public bool isMineable { get; set; }

    public Cube(GraphicsDevice Device, Vector3 Position, Texture2D Texture)
    {
        Device = graphicsDevice;
        Position = cubePosition;
        Texture = texture;
    }

    public class Grass : Cube
    {
        public Grass(GraphicsDevice Device, Vector3 Position, Texture2D Texture)
            : base(Device, Position, Texture)
        {
            Device = graphicsDevice;
            Position = cubePosition;
            Texture = texture;
            isMineable = false;
        }
    }

    public class Stone : Cube
    {
        public Stone(GraphicsDevice Device, Vector3 Position, Texture2D Texture)
            : base(Device, Position, Texture)
        {
            Device = graphicsDevice;
            Position = cubePosition;
            Texture = texture;
            isMineable = true;
        }
    }

```

Added to the list with

```
    cubes.Add(new Cube.Grass(device, new Vector3(x - 50, map[x, z] - y, z - 50), grass));

```
> 0 votes

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


# Question
Title: Entity system game design and input handler
I have started create a lightweight game engine with Ogre and C++. I have a abstract component class and an abstract entity class.

```
#ifndef ENTITY_HPP_
#define ENTITY_HPP_

#include <string>
#include <vector>

#include "Component.hpp"

class Entity
{
public:
    Entity(int uniqueId) { m_UniqueId = uniqueId; };
    ~Entity();

    void AddComponent(Component *comp);
    void RemoveComponent(Component *comp);

    Component *GetComponent(m_ComponentTypes type);

    int GetID() { return m_UniqueId; };
protected:
    std::vector<Component*> m_Components;
    int m_UniqueId;
};

#endif /* ENTITY_HPP_ */

```

Component:

```
/*
 * Component.hpp
 *
 *  Created on: Jul 15, 2013
 *      Author: dominik
 */

#ifndef COMPONENT_HPP_
#define COMPONENT_HPP_

#include <string>

class Entity;

typedef enum
{
    MESH_COMPONENT,
    POSITION_COMPONENT,
} m_ComponentTypes;

class Component
{
public:
    Component(m_ComponentTypes type) { m_Type = type; m_pParent = NULL; };
    virtual ~Component();

    void SetParent(Entity *entity) { m_pParent = entity; };
    Entity *GetParent() const { return m_pParent; };

    m_ComponentTypes GetType() const { return m_Type; };

protected:
    Entity *m_pParent;
    m_ComponentTypes m_Type;
};

#endif /* COMPONENT_HPP_ */

```

After this I created an EntityManager where I manage all entities in the game world, an a rendersystem where I render all entities and initialize Ogre. Now I have a window, but I need the escape button managed -\> so I implement an inputsystem and here is the problem. My InputSystem works with OIS which needs a handle to the window, the handle to the window is available in the RenderSystem but not in the InputSystem, how can I get this data?

Here is my engine class:

```
/*
 * Engine.hpp
 *
 *  Created on: Jul 15, 2013
 *      Author: dominik
 */

#ifndef ENGINE_HPP_
#define ENGINE_HPP_

#include "EntityManager.hpp"
#include "RenderSystem.hpp"

#include <vector>

class Engine
{
public:
    static Engine *GetInstancePtr()
    {
        if (!instance)
            instance = new Engine();

        return instance;
    }

    EntityManager *m_pEntityManager;

    void update(double timeSinceLastFrame);
    void loop();

    void Shutdown() { m_bShutdown = true; };
private:
    static Engine *instance;

    Engine()
    {
        m_pEntityManager = new EntityManager();

        m_Systems.push_back(new RenderSystem());

        m_bShutdown = false;
    }
    Engine(const Engine&);

    ~Engine()
    {
        delete m_pEntityManager;

        while(!m_Systems.empty())
        {
            System *sys = m_Systems.back();
            delete sys;
            m_Systems.pop_back();
        }
    }

    std::vector<System*> m_Systems;

    bool m_bShutdown;
};

#endif /* CORE_HPP_ */

```

In my Engine singleton I have only the abstract system class, so I can't get the window handle. Is there a nice solution?

Any suggestions? Is my approach correct, or is it limitated in any way?

How should I implement the input manager, should he handle all the clicks on keyboard and mouse and send events, or should I create a component with the input manager fields and react on this in this entities which have this component added?

# Answer
Input and windowing is just kind of a pain. You typically need to tightly integrate input, windowing, and the main loop, and cross up responsibilities to some degree.

One option is to just put a lot of core utility code and classes for input, windowing, and so on into a separate "platform" module (you can also put low-level I/O and threading routines here). Your engine can then just call into a `PlatformPumpMessage`, your input system can register a callback via a `PlatformSetInputCallback(&input_handler)`, and so on.

Another option is to move everything into a subsystem of your engine, such as windowing.

Messaging of some kind is probably the most important part. In order for one system to know what's happening in another (like your `InputSystem` knowing what's happening in whatever handles the low-level input events), you need to have some way for the input system to subscribe to such events. A simple callback pointer works very well. A more complicated message/event layer is another possibility.
> 3 votes

# Answer
In my experience with Ogre, I follow Sean's advice and factor out all this logic into a separate platform-specific module or some application specific class/module rather than trying to tie it into the game engine itself.

For example, OIS is designed where you need to pass the external window handle to it for the input hooks to be properly hooked into the platform's main loop. Similarly, you can initialize Ogre where it doesn't create the window but instead you give it the external window handle to where it is to render. At that point, all Ogre does is hooks into the windowing API and renders to that handle when the RenderWindow object gets instantiated.

I personally prefer this approach rather than having Ogre create the render window. Now, depending on whether you're using the engine in a game client situation or embedded into an editor application, the rendering system interface and interaction should basically be the same. Plus, you can wire input/windowing however necessary based on the application's needs without extra method calls for either case within the engine.
> 0 votes

---
Tags: c++, component-based, input, ogre
---


# Question
Title: How do I implement a 2D camera in JPanel?
I'm trying to create a mario-esque game in Java and am at the point of implementing a camera.

Following normalocity's example, I understand the difference between the `GameWorld` and the `Camera` that follows that objects within the context of the world.

From a technical perspective,

I have JFrame that adds `GamePanel` (extends JPanel) and sets its size to 500,500 (that's the window size that I see pop up when I run the program).

Before learning about GameWorlds and such... I was using GamePanel as a generic JPanel to paint my objects and to implement boundary rules, timer, paintComponent, scoring, keyboard input, collision check... All painted objects are placed and shown relative to GamePanel's coordinates/size.

**Now I'm trying to implement a Camera...**

Is Camera a smaller JPanel added to the GamePanel? How do I make my GamePanel more like a GameWorld with a huge size (10,000 x 10,000 px), and only render everything on that GamePanel through the Camera JPanel?

From the GamePanel, I've tried altering the coordinates of the Camera using arrow keys... the camera coordinates of course change, but the objects painted on the GamePanel do not move with respect to the coordinates of the Camera.

---

EDIT: I'm using JPanel because that's what I'm familiar with. If you have a better suggestion on game dev in Java, please let me know!

# Answer
You've misunderstood what a GameWorld is. It is not a concrete JPanel, it is not a concrete frame rendered on the screen. The world is the collection of all objects and their position, it is something more abstract.

The camera is not a JPanel either. It is a set of rules that allow you to decide what part of the world should be drawn.

For example, imagine you are looking at your desk and you have tons of stuff cluttered. The top of desk is your world. Your eyes are your camera and based on their natural constraints you only see a part of the world.

Let's get technical now. How do you define the camera? Well, it simply a rectangle - (x, y, width, height). How do you decide what to draw? Well, a sprite is simply another rectangle. In order for it to be visible by the camera, the rectangles defined by the sprite and the camera must intersect.

Here's the code that tests for intersection:

```
bool overlaps(r1, r2) {
  return !(r2.x> r1.x + r1.width ||
           r2.x + r2.width < r1.x ||
           r2.y> r1.y + r1.height ||
           r2.y + r2.height< r1.y);
}

```

Now in your draw / render method, test each sprite for intersection with the camera. If the result is negative, skip the sprite. If it is positive - you should draw the sprite at appropriate screen coordinates. Using some basic math, you can see that the sprite should be drawn at screen coordinates `(sprite.X - camera.X, sprite.Y - camera.Y)`. And that's it.
> 1 votes

# Answer
If I am understanding this correctly, you wish to render only the objects on GamePanel that are within the visible bounds of the camera? I don't think that using a JPanel and moving it is the best of ideas, but maybe what you can do is override the paintComponent procedure of JPanel and do your rendering there. You may need to take a look at java graphics if you are not too confident with it.

In every game that I have made, I have overridden the method and used an x- and y-offset (for the camera x and y) and I use this method: g.drawSomething(thing, thing.X + xOffSet, thing.y + yOffSet);

And when you press the arrow keys or a & d, you update the x- and y-offsets instead of moving a JPanel. Do all the rendering within just one panel.
> 1 votes

---
Tags: java, 2d, camera, perspective
---


# Question
Title: XNA 3.1 to 4.0 Vertex Shader Not Drawing
I have recently been converting our XNA 3.1 game to XNA 4.0 and am stuck on the shaders. I have the game running, but nothing is drawing to the screen, except things not using a shader.

This is only 2D drawing, using SpriteBatch, which im sure is where the problem is coming from.

In XNA 3.1 everything works fine with my custom vertex and pixel shaders targeting SM 3.0. I cant find any info on what has changed or why its not working. Ive stripped it down as far as I can to try to figure it out, but am not sure. It definitely seems like a coordinate issue with the vertex shader. If I strip our the vertex shader and switch to SM 2.0 for the pixel shader so it uses XNAs default vertex shader for SpriteBatch, it works as expected, but I need 3.0 and custom vertex shader functionality.

Here is stripped down version of things, I cant get PS to output anything anywhere:

```
// Input parameters.
float2   ViewportSize    : register(c0);
float2   TextureSize     : register(c1);
float4x4 MatrixTransform : register(c2);
sampler  TextureSampler  : register(s0);

struct VS_INPUT
{
    float4 position : POSITION0;
    float4 color    : COLOR0;
    float2 texCoord : TEXCOORD0;
};

struct VS_OUTPUT
{
    float4 position : POSITION0;
    float4 color    : COLOR0;
    float2 texCoord : TEXCOORD0;
};

struct PS_INPUT
{
    float4 color    : COLOR0;
    float2 texCoord : TEXCOORD0;
};

VS_OUTPUT VertexTileShader(VS_INPUT input)
{
    VS_OUTPUT output = (VS_OUTPUT)0;
    float4 position = input.position;

    // Apply the matrix transform.
    output.position = mul(position, transpose(MatrixTransform));

    // Half pixel offset for correct texel centering.
    output.position.xy -= 0.5;

    // Viewport adjustment.
    output.position.xy /= ViewportSize;
    output.position.xy *= float2(2, -2);
    output.position.xy -= float2(1, -1);

    // Compute the texture coordinate.
    output.texCoord = input.texCoord / TextureSize;

    // Pass on color
    output.color = input.color;

    return (output);
}

float4 PSTileLighting(PS_INPUT input) : COLOR
{
    return float4(1.0, 1.0, 1.0, 1.0);
}

technique TileLighting
{
    pass Pass1
    {
        VertexShader = compile vs_3_0 VertexTileShader();
        PixelShader = compile ps_3_0 PSTileLighting();
    }
}

```

C#:

```
// Setup matrix
transform = Matrix.CreateTranslation(-bounds.X, -bounds.Y, 0);

// Setup viewport
SectionViewport.X = 0;
SectionViewport.Y = 0;
SectionViewport.Width = bounds.Width;
SectionViewport.Height = bounds.Height;

Engine.GraphicsDevice.SetRenderTarget(background);

Engine.GraphicsDevice.Viewport = SectionViewport;
Engine.GraphicsDevice.Clear(Color.Transparent);

Map.TilesEffect.CurrentTechnique = Map.TilesEffect.Techniques["TileLighting"];

Vector2 viewportSize = new Vector2(SectionViewport.Width, SectionViewport.Height);
Map.TilesEffect.Parameters["ViewportSize"].SetValue(viewportSize);
Map.TilesEffect.Parameters["TextureSize"].SetValue(new Vector2(2048, 2048));

Engine.SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, Map.TilesEffect, transform);
DrawTiles(tileLayer, 0, 5, bounds, Color.White);
Engine.SpriteBatch.End();

```

DrawTiles calls the draw function on all the tiles within the bounds rectangle. They are all in a large 2048x2048 sprite sheet. Map is broken up into blocks of these which the transform matrix is used to offset.

This all works in XNA 3.1. I stripped the pixel shader to absolutely nothing, just outputs white (or is supposed to). Im sure its not any of the specific drawing code because like I said if I switch to the default SpriteBatch vertex shader (IE not defining one, and rolling the PS back to 2.0). Then it works as expected. It draws white pixels everywhere it should.

There must be something wrong im doing with the matrix / viewport manipulations, but am not sure what. Ive looked at SpriteBatches default shader, but it uses a lot of macros and sets the matrix up before going to the shader and not sure how to correlate it with mine.

Any help is appreciated, thanks.

# Answer
> 0 votes
I think you are not initalizing the shader right. I don't see projection matrix initialization.

Here you can find how custom shaders work in xna 4.0

http://blogs.msdn.com/b/shawnhar/archive/2010/04/05/spritebatch-and-custom-shaders-in-xna-game-studio-4-0.aspx

# Answer
> 0 votes
I believe ive solved this immediate issues, though now I have other unrelated ones lol. I dont know why this is, but this fixed it. Before I could not get any output whatsover, all blank/transparent. But just changing this fixed most of it:

From:

```
// Compute the texture coordinate.
output.texCoord = input.texCoord / TextureSize;

```

To:

```
// Compute the texture coordinate.
output.texCoord = input.texCoord;

```

Maybe it was a quirk in XNA 3.1 where the input texture coordinates wasnt in the 0-1 range? Bleh, I dunno.

---
Tags: xna, c#, xna-4.0, graphics, hlsl
---


# Question
Title: How to Initilize CCPoint Array from String?
I've got string like this: {{0,168},{20,20}}, here indicates two points. I want to get them out to initialize my CCPoint. Do you guys know how to convert this?

# Answer
An easy fix , if you have string in that specific format:

```
CGRect rect = CGRectFromString(@"{{0,168},{20,20}}");
CGPoint point1 = CGPointMake(rect.origin.x, rect.origin.y);
CGPoint point2 = CGPointMake(rect.size.width, rect.size.height);

```

If you have more and you want to get them use this:

```
NSString *string = @"{{0,168},{20,20},{20,20},{20,20},{20,20}}";
NSRange range;
range.length = string.length - 1;
range.location = 1;
//because you have commas everywhere you need to change it to a different separator
NSString *modString = [[string substringWithRange:range] stringByReplacingOccurrencesOfString:@"},{" withString:@"}#{"];

NSArray *pointList = [modString componentsSeparatedByString:@"#"];

for (NSString *str in pointList)
{
    CGPoint point = CGPointFromString(str);
    NSLog(@"%@",NSStringFromCGPoint(point));
}

```
> 1 votes

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