# Question
Title: Disappearring instances of VertexPositionColor using MonoGame
I am a complete beginner in graphics developing with XNA/Monogame. Started my own project using Monogame 3.0 for WinRT. I have this unexplainable issue that some of the vertices disappear while doing some updates on them.

Basically, it is a game with balls who collide with the walls and with each other and in certain conditions they explode. When they explode they disappear. Here is a video demonstrating the issue. I used wireframes so that it is easier to see how vertices are missing. The perfect exploding balls are the ones which are result by user input with mouse clicking. Thanks for the help.

The situations is: I draw user primitives with triangle strips using like this

```
graphicsDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.TriangleStrip, circleVertices, 0, primitiveCount);

```

All of the primitives are in the z-plane (z = 0), I thought that it is the culling in action. I tried setting the culling mode to none but it did not help.

Here is the code responsible for the explosion

```
private void Explode(GameTime gameTime, ref List<Circle> circles)
    {
        if (this.isExploding)
        {
            for (int i = 0; i < this.circleVertices.Length; i++)
            {
                if (this.circleVertices[i] != this.circleCenter)
                {
                    if (Vector3.Distance(this.circleVertices[i].Position, this.circleCenter.Position) < this.explosionRadius * precisionCoefficient)
                    {
                        var explosionVector = this.circleVertices[i].Position - this.circleCenter.Position;
                        explosionVector.Normalize();
                        explosionVector *= explosionSpeed;
                        circleVertices[i].Position += explosionVector * (float)gameTime.ElapsedGameTime.TotalSeconds;
                    }
                    else
                    {
                        circles.Remove(this);
                    }
                }
            }
        }
    }

```

I'd be really greatful if anyone has suggestions about how to fix this issue.

# Answer
From looking at the video and your Explode() method, I am taking a guess that under certain conditions your vertices are located at the center and therefor are not getting updated correctly. Is there any particular reason that this check is in there?

```
if (this.circleVertices[i] != this.circleCenter)
{
...
}

```

I would try disabling that condition and see what happens.
> 1 votes

---
Tags: xna, vertex, monogame
---


# Question
Title: Rotating Objects in OpenGL: glRotate or Quaternions?
I'm coding my first engine and I'm trying to have performance in mind since I'll probably use it for mobiles, and I have this question, should you use **glRotate** or **Quaternions** for rotating objects in the 3D space?

I have a set of classes that manage the information about all vertices and faces of the objects, and currently when I'm rendering I'm doing:

```
void DrawObject(Object* object)
{
    glTranslate(object->x, object->y, object->z);
    glRotate(object->rotationX, 1.0, 0.0, 0.0);
    glRotate(object->rotationY, 0.0, 1.0, 0.0);
    glRotate(object->rotationZ, 0.0, 0.0, 1.0);

    for(int i = 0; i < object->totalFaces; i++)
    {
        glVertex3f(object->faces[0]->x, object->faces[0]->y, object->faces[0]->z);
        glVertex3f(object->faces[1]->x, object->faces[1]->y, object->faces[1]->z);
        glVertex3f(object->faces[2]->x, object->faces[2]->y, object->faces[2]->z);
    }
}

```

From what I could understand, glRotate will make the graphics card to do the rotation calculation, while using Quaternions would make the processor do it. But saying I have about 200 objects in a given scene, what is the best acceptable way of handling rotations?

# Answer
You appear to have some misconceptions about how the graphics pipeline and OpenGL work.

All `glRotate` does is perform a matrix multiplication and store the result in the OpenGL matrix stack. It doesn't actually cause anything to happen on the GPU. That saved matrix will eventually be sent to the GPU, just like the matrix that would be saved if you using quaternions, turned them into a rotation matrix, and loaded it via `glLoadMatrix`. The GPU *always* has to perform a transformation on the geometry you send it, you don't avoid that by using quaternions at all.

There isn't really a useful performance differential between "using `glRotate`" and "using quaternions." The larger performance concern you probably have is that you are using immediate-mode calls (`glVertex`) to render. These are the least-efficient means of getting geometry to the card (albeit the simplest); you may want to look into VBOs or similar.

As for your actual question: the graphics pipeline (and OpenGL) only operate in terms of transformation matrices. If you use quaternions, you will need to convert the quaternion representation of your rotation into a matrix representation prior to use; generally one converts a quaternion to an axis-angle rotation matrix, which is exactly the same kind of matrix that `glRotate` constructs and multiplies on to the matrix stack (but in your case you could just store it to the OpenGL matrix stack using `glLoadMatrix`).

Although there really isn't going to be a performance difference, I'd recommend you use quaternions for your rotation representation simply for the following reasons:

* You'll get experience with them.
* They have nice properties, such as being more readily interpolatable.
* By relying less on the deprecated fixed-function functions like `glRotate`, you'll make it easier to eventually move to a more modern version of OpenGL.
> 3 votes

---
Tags: c++, opengl, rotation, quaternion
---


# Question
Title: How to override onSetContentView while Using Ratio Resolution policy in Andengine Base game activity
I am developing (Learning to build :) ) a game with andengine GLES2. I am using base game acitvity , and i overrides the setContent view to place my admob ad.
Every thing works fine except the resolution policy .
**Ratio Resolution policy** is the one I am using along with **CAMERA\_WIDTH = 800; and CAMERA\_HEIGHT = 480;**

The issue is whenever overided onsetContentView **scene is not get aligned to center** ,**margins displayed only on bottom** not on both top and bottom, Same will cause when horizontally align the margin will be displayed only at right side, not on both sides. how can i correct this. I am giving my code below

```
@Override
protected void onSetContentView() {

    System.out.println("Content setting");
    this.mRenderSurfaceView = new RenderSurfaceView(this);

    final LayoutParams layoutParams = new LayoutParams(
            android.view.ViewGroup.LayoutParams.MATCH_PARENT,
            android.view.ViewGroup.LayoutParams.MATCH_PARENT);

    layoutParams.gravity = Gravity.LEFT ;

    final android.widget.FrameLayout.LayoutParams surfaceViewLayoutParams = new FrameLayout.LayoutParams(
            layoutParams);

    adView = new AdView(this, AdSize.BANNER, "xxxxxxxxxxxxx");

    final FrameLayout.LayoutParams adViewLayoutParams = new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.LEFT
                    );

    final FrameLayout frameLayout = new FrameLayout(this);
    final FrameLayout.LayoutParams frameLayoutLayoutParams = new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.FILL_PARENT,
            FrameLayout.LayoutParams.FILL_PARENT,Gravity.CENTER);

    frameLayout.addView(this.mRenderSurfaceView, surfaceViewLayoutParams);
    frameLayout.addView(adView, adViewLayoutParams);

    this.setContentView(frameLayout, frameLayoutLayoutParams);
    this.mRenderSurfaceView.setRenderer(this.mEngine, this);

}

```

here is the image what i get you can see the white margin below the scene if you select the image ( its not get into attention due to stack overflow also had white background )

any suggestions will be very help full to me

How Can i solve this Isuue Please help me

Thanks to all,

# Answer
FIXED:

After a little big game with the layouts I am able to fix this.

Now my surface view get aligned to center and the ad displays in a desired way.

Here is my code

```
@Override
protected void onSetContentView() {

    final RelativeLayout relativeLayout = new RelativeLayout(this);
    final FrameLayout.LayoutParams relativeLayoutLayoutParams = new FrameLayout.LayoutParams(
            RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);

    this.mRenderSurfaceView = new RenderSurfaceView(this);
    this.mRenderSurfaceView.setRenderer(this.mEngine, this);

    final android.widget.RelativeLayout.LayoutParams surfaceViewLayoutParams = new RelativeLayout.LayoutParams(BaseGameActivity.createSurfaceViewLayoutParams());
    surfaceViewLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);

    relativeLayout.addView(this.mRenderSurfaceView, surfaceViewLayoutParams);

    FrameLayout frameLayout = new FrameLayout(this);
    adView = new AdView(this, AdSize.BANNER, "xxxxxxx");
    adView.refreshDrawableState();
    frameLayout.addView(adView);
    relativeLayout.addView(frameLayout);

    this.setContentView(relativeLayout, relativeLayoutLayoutParams);

}

```
> 2 votes

---
Tags: andengine
---


title: box2d with lines

text:
# Question
Title: box2d with lines
I have a very simple platform game builder and I've specified the ceilings, walls and floor as line segments.

A line has a winding, or normal; you can determine the direction that a line should be solid from. And I want the line to be non-existent when passing from behind through it - I want one-way platforms (and ceilings you can fall through but not jump back up out of).

Here's an example level, with yellow for ceilings and red for floor (with winding determining their facing, they don't differ in implementation):

I want to move to box2D (Javascript). How can I best port across these line segments and make them one-way static barriers in box2D?

# Answer
> 1 votes
Box2D has functionality called a "Pre-Solve Event".

> Pre-Solve Event
>
> This is called after collision detection, but before collision resolution. This gives you a chance to disable the contact based on the current configuration. For example, you can implement a one-sided platform using this callback and calling b2Contact::SetEnabled(false). The contact will be re-enabled each time through collision processing, so you will need to disable the contact every time-step. The pre-solve event may be fired multiple times per time step per contact due to continuous collision detection.

If you search the box2d user manual for "Pre-Solve" you'll find an example for implementing one-way platforms:

```
void PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
{
    b2WorldManifold worldManifold;
    contact->GetWorldManifold(&worldManifold);
    if (worldManifold.normal.y < -0.5f)
    {
       contact->SetEnabled(false);
    }
}

```

As for what collision object to create, Edge Shapes fit the bill, again from the manual:

> Edge shapes are line segments. These are provided to assist in making a free-form static environment for your game.

They are simple to create, as you would expect, they're created from two points:

```
// This an edge shape.

b2Vec2 v1(0.0f, 0.0f);
b2Vec2 v2(1.0f, 0.0f);

b2EdgeShape edge;
edge.Set(v1, v2);

```

Combine those two together and you have static one-way barriers.

---
Tags: collision-detection, javascript, box2d
---


# Question
Title: How to use images/text/etc. in XNA without Content Pipeline?
I'm currently writing a program in C# with the XNA framework. It is absolutely necessary for the game's images and text assets to be visible by the end user in the form of PNG files, so I can't use the content pipeline.

How would I go about using graphics and text in my XNA game without it?

# Answer
> 4 votes
You don't need the content pipeline.

MonoGame, for example, allows you to use `LoadContent<Texture2D>` and specify an image name of a file that's just a simple PNG in your `Content` directory. This is what I do for all my projects (since MonoGame has difficult/flakey? support of the content pipeline today), and because I don't care about "protecting" my assets by converting them into `XN*` format.

From what I remember of "vanilla" or MS XNA, this worked there too.

# Answer
> 0 votes
Use Texture.FromStream to load the texture at runtime. This is a little tricky because of premultiplied alpha as referred to in ashes999 answer. Here is a great explanation from David Gouveia on how to do it correctly

---
Tags: xna, graphics, textures, xna-content-pipeline
---


title: Creating a alive object list

text:
# Question
Title: Creating a alive object list
I'm currently working on a Java game I know a lot of games created all instances of objects beforehand and then bring then in and out of play when they are needed.

Will it be worth it to have a Vector of all instances that are alive, and loop through that instance of going through all of the instances and checking the alive boolean?

Thanks

# Answer
For simplicity, it's easier to have one vector/array that has all the objects that are alive. You don't want to check if they are alive in order to update them. That list represents the objects that need to be updated. Have a second vector/array, a stack if you will, that you add "dead" objects to once they are not needed for the time being. Once you need to reuse them simply pop them back into your vector that you're calling an update on.

If you're going by this approach might be interesting to read on object-pools

Of course you could also just remove them from memory and create new objects by instantiating them when needed. Eitherway, it's cleaner if you only hold your objects that actually need updating. All your objects that don't need to be updated( because they are inactive/dead) shouldn't be there.
> 3 votes

---
Tags: java
---


# Question
Title: Why are some games using some dithering pattern instead of traditional alpha for transparency?
Recently, I have seen some 3D games (eg: `GTA IV`) to use some kind of ordered dithering to simulate transparency / alpha.

The polygons are not transparent as usual, but instead render a dithering texture that gradually switch from left to right to simulate transparency :

The effect is not unpleasant but rather surprising to see at first (vs traditional alpha blending)

Except for the visual aesthetic effect it produce, **is there any reason some games do this** (better performance, saving bandwidth or any else i do not think about) ?

I have searched on the web but cannot found anything about this technique.

# Answer
> 30 votes
This is a fairly common approach to transparency in games that use deferred shading. Proper transparency doesn't work well at all with deferred shading, since only one surface's data (depth, normal vector, color, etc.) can be stored at each pixel, and proper transparency involves multiple surfaces overlapping at a pixel, each requiring independent lighting.

There are a few ways game engines can deal with this:

* Use forward shading (possibly with a reduced lighting model) for transparent surfaces, and deferred shading for the opaque surfaces. The transparent surfaces have to be drawn in a separate pass with back-to-front sorting.
* Use dithering, more commonly known as stippling or screen-door transparency, which works with deferred shading since it gives just one surface per pixel. This works particularly well for LOD transitions, since they usually finish in a fixed amount of time, limiting how long the stippling is visible. It doesn't work very well for, say, glass windows on a building.
* It's also possible to use stippling but then apply a post-process blur that recombines the stippled pixels, giving an approximation of proper transparency. Volition does this in Saints Row the Third (and perhaps some of their other games too), under the name of "inferred lighting". This can look quite nice, but the post-process blur is expensive.
* And of course, there are all the order-independent transparency methods out there, although I don't know of any game that uses them. They are just for tech demos so far.

One can also use a combination of these approaches, e.g. forward shading for glass windows and stippling for LOD transitions.

It's also worth noting that some games use stippling for soft shadows. This is a performance tradeoff; nicer shadows require more texture samples in the pixel shader, which takes longer, but you can get okay-looking results by using fewer samples and offsetting their positions randomly. The random offset produces the stippling effect.

# Answer
> 0 votes
It’s a simple performance trade-off. Alpha blending requires reading from the current colour buffer, whereas this kind of dithering is write-only (or discard-only, of course).

It is possible to mix this technique with multisampling, which is then called alpha to coverage.

---
Tags: textures, rendering, transparency, alpha
---


title: Tile Draw Order

text:
# Question
Title: Tile Draw Order
I started working on a tile engine recently and have been trying to get this depth sorting for the tiles right. I am using XNA and the SpriteSortMode.Deferred to get the tiles to sort correctly in the X direction along with a for loop to loop through all tiles that should be drawn, but the Deferred mode does not work in the Y direction. Anyone have any advice or a solution?

Just an image for reference: http://dl.dropbox.com/u/31957180/test\_1\_2.png

# Answer
> 2 votes
You could try drawing with Z order. Make each row have a different Z. That will require you to change the sortmode to front-back / vise-versa.

Another option is to draw columns first (| | | | |).

---
Tags: xna, c#, tiles, graphics-programming
---


# Question
Title: How do I detect when the Xbox home button is pressed XNA?
How do I detect when the big Xbox button in the middle of the gamepad is pressed in XNA?

# Answer
> 3 votes
You're talking about the guide button, it sounds like. The guide button is reserved, and you can't detect its state directly.

You can, however, detect if the guide is active so you can pause your game (or whatever). To do this, you'll want to have a look at the IsVisible property of the Guide class.

---
Tags: xna-4.0, gamepad
---


# Question
Title: Why do I get "Undefined" only on the "Vertical" Grid?
Problem:

When I get to the end of the Grid it gives me an Error :-/

The X axis is fine, the problems occur then I move "over the end" of TOP and BOTTOM.

This code works:

```
if(new_data[1] == "right"){
            // If New Grid Location is Empty
            if(grid[player_y][player_x  + 1] == 0){
            grid[player_y][player_x] = 0;
            player_x = player_x + 1;
            grid[player_y][player_x] = 1;
            socket.emit("message", "move," + "right");
            }

```

And this one does not:

```
if(new_data[1] == "up"){

        // If New Grid Location is Empty
        if(grid[player_y - 1][player_x] == 0){
        grid[player_y][player_x] = 0;
        player_y = player_y - 1;
        grid[player_y][player_x] = 1;
        socket.emit("message", "move," + "up");

```

It says the error is "Cant == 0 of Undefined"

I assume that the Problem lies in the First Array being less then 0 and therefore giving a Undefined Error on the Second Array..

**I fixed this by creating a "Wall" at the X Edges:**

```
for(var i = 0; i < 20; i++){
grid[0][i] = 1;
}
for(var i = 0; i < 20; i++){
grid[19][i] = 1;
}

```

But why does it not give an Error when I try to access a "undefined" of the Second Array?

# Answer
> 2 votes
That's probably because in here `if (grid[player_y - 1][player_x] == 0)` you actually do `if (grid[0 - 1][player_x] == 0)` at some point. Accessing -1 element of array gives you the error.

You need to check your bounds first, before testing with array. Probably like so:

`if (player_y >= 0 && player_y < width) && (grid[player_y - 1][player_x] == 0)`

*I'm not entirely familiar with how JS handles out of range in arrays, is it possible that when you access x+1 JS increases the arrays length or accesses next element at \[y+1,0\]*

---
Tags: javascript
---


title: ScaleX and Y for stretching MovieClip

text:
# Question
Title: ScaleX and Y for stretching MovieClip
I'm developing a game, and the game has a shop. In that shop there is an option for a house expansion. This is a movieclip that I want the user to be able to spend their coins to increase their house in the following ways:

-\> stretch house to right \<- stretch house to left ^ stretch house upward v stretch house downward.

The thing is, I've been thinking of using `ScaleX` and `ScaleY` to accomplish this. The only problem: It stretches the left **and** right, I can't make it do one. I'm sure there is a way to do this, but I haven't yet figured it out. Any ideas?

# Answer
Set up the stage:

```
var num:Number = 10;

```

Change mc to your MovieClip

For up:

```
mc.height += num;
mc.y -= num/2;

```

For down:

```
mc.height += num;
mc.y += num/2;

```

For left:

```
mc.width+=num;
mc.x -= num/2;

```

For right:

```
mc.width+=num;
mc.x+=num/2;

```
> 0 votes

# Answer
Change the registration point of movieclip from "center" to x=0 and y=0 . Keeping the registration point in the center, causes the movieclip to stretch on both the sides equally.
> 0 votes

---
Tags: flash, actionscript-3
---


# Question
Title: Prevent Reavers from dealing splash damage to friendly and allied units
Just for fun I made some games in the Starcraft Broodwar map editor (scdraft2.0).

I notice that in my map Reavers deal damage to friendly and allied units as well as to neutral units. It's a cat and mouse map so when friendly units kill your teammates it's not fun.

Is there any way to prevent this?

# Answer
> 2 votes
There's no way to disable the reaver's friendly splash damage except through modding. For your map, you may just have to accept that reavers will be able to hurt friendly units and re-balance your other units accordingly. Alternatively, you could just avoid using reavers in your map.

---
Tags: level-design, modding, starcraft
---


# Question
Title: How do I disable the graphical output of Quake 3?
I have been working with the Quake 3 source code for a few weeks now and am in the process of integrating a custom bot as part of my M.S. thesis. I am using a machine learning algorithm to allow the bot to improve over time; however, for testing purposes I would like to disable the graphics out and load up a bot vs. bot match which can play out at a faster speed.

Has anyone done this before or can anyone recommend somewhere to read? I know I have seen this done before, but I have not seen any code examples. I have also heard there may be some 3rd party utilities that will allow you to disable graphics arbitrarily on any application. As a note, I am working with this on Windows if that makes a difference.

# Answer
Have you tried running the game in a "dedicated" server mode? This mode is usually run on network servers.

Then try combining this with the "timedemo" command somehow to make it run the game faster than realtime.
> 4 votes

---
Tags: c++, quake3
---


# Question
Title: iOS game integrated with Facebook - Random game
How could I implement a random game for iOS via Facebook. I registered my game with Facebook and done everything so far... Can Facebook do such a thing?

**EDIT**

I connected my app to Facebook, I can send requests, publish open graphs etc. But i need to connect players to play online via Facebook, such as Bubble Galaxy with Buddies. Do they use Facebook for this? Any tutorial or idea ?

# Answer
> 3 votes
Last time I used the Facebook API they didn't provide any multiplayer or gameplay functionality. I'm pretty sure you have to write that yourself.

You can still leverage the Facebook API to publish scores/achievements and find friends of a user. Eg. You can get the user-names, profile pictures from FB and also use the Facebook API to post something on the users wall to draw more attention to your game. Achievements and scores are also a part of the Facebook API now.

The tutorial you followed is pretty much all there is to it. Facebook gives you the "social" data of users, everything else is up to you.

To find friends for a multi-player game (as your question suggests), you could use the FB API to find the friends of a user which are currently online and send a request. Your server-application will have to handle the creation of a multi-player session when requests are being accepted.

---
Tags: iphone, ios, multiplayer, objective-c, facebook
---


# Question
Title: Drawing sprites messes up my model in XNA4
I have a model which draws correctly in XNA4.

However if I try to add a background image (or any sprite), the rendering of my model is messed up. There are two problems with the rendering

1. model is partially transparent
2. hidden surfaces are visible.

Above is the 'problem' rendering (the cyan coloured cockpit cover is visible through the bottom of the ship)

This is how the rendering *should* look

# Answer
> 4 votes
The problem is caused by the SpriteBatch.Begin() changing some of the rendering states.

This problem is solved in XNA 3.1 and earlier by using the SaveState flag (see this answer).

However in XNA 4.0+ you need to restore the state yourself.

Insert the following code *after* your sprite drawing but *before* your model drawing (or 3D primitive drawing)

```
GraphicsDevice.BlendState = BlendState.Opaque;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;

```

Information based on original article by Shawn Hargreaves

---
Tags: graphics-programming, state, depth-buffer, blending, xna-4.0
---


# Question
Title: Does the Maya FBX 2013.3 exporter write tangent and binormal data?
I'm making an XNA game at the moment and I'm trying to knock out my bump map shader right now. However when I compile the game crashes at the mesh.Draw() line and tells me TANGENT0 is missing. Apparently the FBX 2012 exporter didn't export tangent and binormal data properly, and I'm still having this problem despite installing the most recent exporter for Maya 2012.

For the record the plug-in readme tells me that bug is fixed and I am checking 'Tangents and Binormals' when I export.

What am I doing wrong?

# Answer
> 0 votes
The answer is yes it does. When adding your FBX models to your game content, right click the file, go to properties and set the 'Generate Tangent Frames' to true.

---
Tags: maya, fbx
---


title: Simple Alternate Art Style

text:
# Question
Title: Simple Alternate Art Style
I'm looking for suggestions on easy or simple art styles that can be created by anyone. It would be for a 2D game, but pixel art isn't really my thing. An example from a game would help. Thank you very much.

# Answer
When you want to create a game without access to artistic talent to create artwork, you could go for a graphic style which is rather abstract than representative. You could, for example, represent all gameplay objects with geometric shapes, like in Geometry Wars.
> 7 votes

# Answer
Some games, such as roguelikes, feature graphics made up of nothing but colored ASCII characters. Dwarf fortress is a deep and complex game modeled after roguelikes. Here's what its graphics look like:
> 4 votes

# Answer
Making it look childish isn't a bad idea at hindsight. Look at An Untitled Story.
> 1 votes

# Answer
Vector art. Check Revange of the Titans.
> -1 votes

---
Tags: art
---


# Question
Title: Dynamically save an assetbundle during run time
I'm wondering if it is possible to dynamically save / amend a current asset bundle during the running of my Unity application.

I've been looking into this for a few hours, but can't find anything about how to do this. I know you can download / stream assets from a server at run time, but I'm interesting in knowing if it's possible to do the same but in the opposite direction.

Has anyone ever attempted this before? Is there any good examples of how this could be done?

# Answer
the only way to create assetbundle is to use BuildPipeline. BuildPipeline is an editor class, so it cannot be used in game. However this does not prevent you from creating your own assets. For example you could create a png in run-time, upload it, then download it another time and use WWW.LoadImageIntoTexture to use the image as texture.
> 3 votes

---
Tags: c#, unity
---


title: How to create a walkable 3D terrain

text:
# Question
Title: How to create a walkable 3D terrain
I want to make a terrain for a RPG game that I'm developing. I started modeling the surface and implementing it to my game, but now I realized that i might be doing everything wrong. So I would like to ask a few questions:

* **How should I make the surface Model?**

I'm developing my game without an engine, so I have to do coding for everything (Java, LWJGL). I use Blender to model the surface, and I export it to an .smd model file.

* **How to detect intersections between the surface and other models?**

I guess I need to detect intersections, to make the terrain walkable. The problem is that I don't know the best and easiest way to do that. I tried making a triangle-triangle intersection detection algorithm, but it was to hard for me, and I guess I need something faster and simpler.

# Answer
> 5 votes
You can generate your surface as height map (2D table of heights, regular grid). It might look like this

http://mrdoob.github.com/three.js/examples/webgl\_geometry\_terrain.html

You probably don't need physical simulation, so you just find the height at certain coordinate and check, if your model is above it /under it. That is only the basic idea and I am sure you can extend it.

# Answer
> 3 votes
One solution is to create a navigation mesh which defines walkable surfaces. This mesh can also be used for pathfinding for AI. There is a C++ library to automatically create a navigation mesh called Recast & Detour.

Recast has been integrated into Blender. Switch the renderer to "Blender Game". In the Scene properties panel you can then find a "Build navigation mesh" button, which creates a navigation mesh for the currently selected objects.

---
Tags: 3d, terrain, computational-geometry
---


title: When to Dispose Textures

text:
# Question
Title: When to Dispose Textures
I recently realized `Texture2D` implements `IDisposable`, and now (while trying to track down a memory leak) wonder about where and when I should dipose this.

My current architecture is that I have a `SpriteComponent` instance which encapsulates and hides the `Texture2D`. Internally, when I switch screens (eg. `MainMenuScreen` =\> `WorldMapScreen`), I call `Dispose` on the current screen, which calls dispose on the entities, which calls dispose on the textures.

But this results in some wacked-out behaviour, like textures apprearing super zoomed in momentarily, or appearing black, or appearing as garbage image data.

So my question is really, **when should I call `Dispose` on `Texture2Ds`?**

(FYI, I also can switch to a screen, and then later switch back to it, which currently causes me to reload the sprites, and by proxy, the textures.)

# Answer
> 2 votes
Well, the obvious answer, dispose of them only when you're completely done with them. If you know a screen will not be loaded again in a certain session of a game, it's safe to unload the textures used exclusively in that screen.

If all the textures or most of the textures are going to change, you may want to unload them to make room for the new textures. However, if you're not over your memory budget, there's no reason to unload textures that may be used again.

**Edits from comments:** For most games, unless you're loading a huge amount of textures, it's normal to load the textures up-front and keep them loaded for the entire play session. Disposing and re-loading is probably expensive, and it's simpler to just leave them in memory.

---
Tags: xna, monogame
---


# Question
Title: Scaling 3D furniture while keeping the thickness constant
I am creating a program in WindowsForms and Xna that allows users to create a 3D room. By dragging and customizing different .fbx models, they can "build" a room or whatever and then look at it in 3D. Everything worked nicely so far, until I got to a point that involves scaling a model. A model is usually made up of multiple meshes, and each mesh has a class that contains information about that mesh such as, position, rotation, name, mesh, scaleFactor, etc. This class also contains a list called **ScalableAxes** which contains strings of the axes name, in which this mesh can be scaled.

I have also included a parent-child relationship, when a user imports a .fbx model, there is also a custom .pdn file which contains information about parenting. Usually every mesh in the .fbx model becomes a child of an "empty mesh" (just a class, with no mesh or bone assigned to it).

Now let's say this "empty mesh" name is **Body** and it contains few child meshes such as **left side**, **right side**, **top side**, **bottom side**, **top door**, **bottom door**. Let's say I scale **Body** on the Y axis by a factor of 2. Since **Body** has no Mesh in his class assigned, it would skip this and loop through his children. If a child has a mesh, then it would look to **ScalableAxes** list and if it contains Y (in this case) it would go on to the scaling part.

The problem starts here. Let's say I come to **Left side**, left side can be scaled on the Y axis, but the **top** and **bottom** sides ***CAN'T*** be scaled on the Y axis. So scaling it this way would lead to gaps between **left side** and **top** and \*bottom side\**. Also there can be a whole variety of different models, and meshes. For example: one has only one door, other has **sides** between **top** and **bottom**, and so on...

**EDIT:** For example: **left side** is 964 on Y axis, **top** and **bottom side** are each 18 on Y axis, so the combined length is 1000 on Y axis. I scale the whole **Body** by 2 on the Y axis (meaning the new Y size should be 1000 * 2 = 2000). If I were to use scaling by 2 on the Y axis on all meshes (that can be scaled on the Y axis), then **left side** would be 1928, **top** and **bottom** would stay the same so, 18 each on Y axis. This would lead to 1928+18+18, 1964 size on the Y axis instead of 2000.

**EDIT2:** This program is all about arranging / making furniture in 3D. So let's say you got this night stand in your project made with this program.

And you find the size of it to small, and you want to scale it vertically. When you would scale it the "thickness" of all of the elements (meshes that made up this model) should stay the same since you want to make it bigger not "thicker". Only the length and width should change. So the **left** and **right** side would get scaled vertically, but **top** and **bottom side** wouldn't since that vertical direction is their "thickness". And if you would want to scale the model horizontally (make it wider), the **top** and **bottom sides** would get scaled, but **left** and **right** would stay the same since that direction is their "thickness" (they would only have to get moved to the right positions).

Thats why in my previous picture I said that **top** and **bottom side** cant be scaled on the Y axis, since that was their "thickness".

**EDIT 3:** bummzack, your method works great and all, but what if I have a furniture that has, 3 or more doors. How would I be able to scale all of the doors equally?

Any help is greatly appreciated!

# Answer
> 4 votes
I wrote an application in Flash that does something similar to what you want to do (it's a tool where you can build and order your custom furniture in the browser).

I'm afraid your approach with scaling is never going to work, unless you provide some meta-data or structural information with your furniture. The bedside table you posted is a good example for this. How would your application know that the feet/base of the table is actually the base and should not be scaled vertically?

As soon as you're dealing with textures, things also get more complicated. Optimally, you would also scale UV coordinates, so that textures repeat along the model and don't get stretched. But this requires tileable textures without baked shadows or anything...

In the application I wrote, the "walls" of the furniture are being created dynamically (these are simple cuboids). By dynamically creating/altering the mesh, it's easily possible to also change UV coordinates etc. Different layouts (think GUI layouts, but 3D) ensure the furniture layout/structure.

There is also more complex geometry (such as drawers or clothing hangers) which can be added to the furniture (here's an example configuration). That's probably really close to what you want to do, because in this case, we load the geometry dynamically from file but it still has to adjust its size when the furniture measurements change. To achieve this, we created different bones (or vertex-groups).

Here's the screenshot of a simple drawer model:

There are two "bones" (or vertex groups) called "LEFT" and "RIGHT". We simply established a naming convention for these bones (eg. LEFT, RIGHT, TOP, BOTTOM, CENTER, etc.) and moved these bones to different positions in code when the model needed scaling.

If you need to scale in all 3 axes, you might be better off with vertex groups for all the corners of the model, but even then you won't get perfect results with every type of furniture.

In case of your nightstand you could have a bone in every corner (8 corners) of the model. Then you would have to move 4 corners to adjust one side. This requires careful preparation of the model though and you can still run into issues, especially if the center of the model needs special scaling/treatment and with texture scaling.

If your app allows the user to upload his own models, then I guess you'll be better off with uniform scaling of the model (as your approach with individual scaling just won't work).

# Answer
> 1 votes
I think what you're looking for is the 3d equivalent of a 9-patch image. 9-patch images are often used in 2d graphics to draw UI elements, like buttons, which need to be rescaled to different heights and widths. Scaling the button image uniformly will look dreadful, so different scaling is applied to different parts of the image so as to retain the corner and edge details without stretching.

So basically you want to leave the corners unscaled, scale the edges in only one axis, and the middle can be scaled in both axis. For 3d graphics, it'd be the same except you'd limit scaling in the edges along a plane rather than axis.

http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch

# Answer
> 0 votes
It seems like you need to practice equations, especially finding out what your knowns and unknowns are.

Let's take your first example:

```
left_side = 964
top_side = 18
bottom_side = 18
total = left_side + top_side + bottom_side
      = 964 + 18 + 18
      = 1000

```

Now you want to scale `total` by 2. The only value that is allowed to change is `left_side`, it's your unknown. The others are knowns. Hence the equation:

```
left_side + top_side + bottom_side = 2000
left_side = 2000 - top_side - bottom_side
          = 2000 - 18 - 18
          = 1964

```

Giving a scaling factor of:

```
scale = 1964 / 964 = 2.03734439834

```

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


title: Changing the texture in a Sprite

text:
# Question
Title: Changing the texture in a Sprite
I'm a bit new to libGDX. My problem is ,in my code, only if I set the texture in the constructor of the Sprite instance, it will draw anything. My question is shouldn't it be working when I only call setTexture() when rendering? Or is there another way to render while changing the texture?

Following code doesn't draw anything.

```
public Sprite getSprite() {
    if (this.sprite == null) {
        this.sprite = new Sprite();
    }
    return this.sprite;
}

public void render(final float deltaTime, final SpriteBatch batch) {
    this.getSprite().setTexture(this.getCurrentTexture());
    this.getSprite()
            .setPosition(this.getPosition().x, this.getPosition().y);
    this.getSprite().setRotation(this.getRotation());
    this.getSprite().draw(batch);
}

```

Following is the working code.

```
public Sprite getSprite() {
    if (this.sprite == null) {
        this.sprite = new Sprite(this.getCurrentTexture());
    }
    return this.sprite;
}

public void render(final float deltaTime, final SpriteBatch batch) {
    this.getSprite().setTexture(this.getCurrentTexture());
    this.getSprite()
            .setPosition(this.getPosition().x, this.getPosition().y);
    this.getSprite().setRotation(this.getRotation());
    this.getSprite().draw(batch);
}

```

# Answer
> 1 votes
`SpriteBatch` has to be started before you can use it. First use:

```
batch.begin()

```

And at the end use:

```
batch.end()

```

---
Tags: libgdx
---


# Question
Title: What is a currently a good game stack for simple Javascript 2D multiplatform game?
I'm looking for advice from someone can help me avoid common pitfalls in developing light weight, quick-to-market games. Yeah, I've heard of Google ;-), but a trip down Google lane does not beat solid experience from someone who has been down this path. I'm looking for advice from someone who works alone, or in a small team, and has developed some 2D games for mobile.

My game ideas don't require intensive graphics, just simple arcade style glyphs and collision detection. My experience is mostly with Scala, Java and web technologies (Javascript, CSS, SVG, HTML, etc).

My question is: Is there a nice stack that someone can suggest that will be a good fit for my skillset?

I'm considering Javascript for simple 2D shooter games with simple multiplayer games being supported with a Scala server-side written on Spray. Is this silly? Should I rather look into things such as Unity 3D, and use it in 2D mode?

For the actual game engine, something like the Sparrow Framework would be great, but it needs to be multiplatform.

# Answer
> 3 votes
CreateJS is a Javascript library for working with Canvas and other HTML5 web stuff like audio. It's not a game engine but it can definitely be used to make games.

# Answer
> 0 votes
Take a look at Mosync. If you can work with HTML5 technologies (like Canvas), it may be just what you are looking for.

# Answer
> 0 votes
I didn't specify this in my last answer since the question explicitly mentions Javascript in the title. However, since you have Java development experience: playN would be the way to go! Take a look.

---
Tags: 2d, javascript, svg
---


# Question
Title: Spaceship interiors: How to approach, implementation-wise?
I'm creating a 3D space game using Ogre3D for graphics with C++ and one of the features is to be able to freely wander around spaceship interiors, but I am lost with how to implement it. Here is what I can think of so far:

* A single model of the spaceship that has an interior modelled too, but somehow double-sided and double-normalled? Not sure if this is possible!
* Two models, one of the spaceship outside and one of the interior with flipped normals, when in game the interior model is placed inside the spaceship mesh, but that wouldn't be very flexible (different spaceship sizes, hull thickness etc)
* Two models, when a player enters the space ship the screen fades and their view is switched to the inside model where the windows are live render textures of their respective place on the outside part of the spaceship, but it wouldn't be very optimised (rendering to several textures) and wouldn't have the gameplay aesthetic of smoothly entering or exiting (possibly via explosion) the ship

So, GameDev, how would you approach this?

# Answer
The first option is what I would use. One model for everything. It's totally possible to have an interior and exterior of a model. Just like it's possible to have concave shapes. There's no double normals or double sided faces. Imagine a slice out of a crappy ship like this:

*(I have no idea why the floor isn't flat, I only realized that after I posted it...)*

Black lines are faces, red lines are normals. The surfaces wrap around. This allows you to have different hull thicknesses, blocking off interiors where the engines are, stuff like that. The doors are easy to place as separate parts (since you'll probably want to be able to move them anyway).
> 13 votes

---
Tags: c++, game-mechanics, ogre
---


# Question
Title: Find the Contact Normal of Rectangle Collision
It seems a lot of people have asked similar questions on this site, and every time it seems like a whole bunch of answers that don't work are given. Basically, I have two rectangles (AABBs) that collide, and I want to find out on what side they collided with each other.

I know the velocities of each object before they collide, and of course their positions before and when they've actually collided (if I use discrete collision checking that is, currently I'm using speculative). Many people say find the lowest penetration distance or take the largest speed (either horizontal or vertical) and that will give you the answer. But the collision is dependent on both of those values, I just don't know how they fit together to tell me where the collision is coming from. I don't think I need an exception for corner collisions.

I do not want to do my horizontal and vertical collisions separately as that just opens up even more problems.

So, any suggestions?

# Answer
Instead of an AABB of size `(w,h)`, position `(x,y)` and velocity `v`, and an AABB of size `(w2,h2)`, position `(x2,y2)` and velocity `v2`, you could consider a fixed-position AABB of size `(w+w2,h+h2)`, position `(x,y)` and a point of position `(x2,y2)` moving at velocity `v2-v`.

Then use AABB/ray collision resolution. You can restrict yourself to the 2D case by removing the code for the 3rd dimension. If the final `t` value is smaller than your current timestep, there is a collision.

Finally, the following tests will tell you where the collision took place and let you compute the normal:

```
if (t == t1) return Vector2D(-1.f,  0.f); /* left */
if (t == t2) return Vector2D( 1.f,  0.f); /* right */
if (t == t3) return Vector2D( 0.f, -1.f); /* bottom */
if (t == t4) return Vector2D( 0.f,  1.f); /* top */

```
> 5 votes

# Answer
Check this

Use shorter compound.
> -1 votes

---
Tags: collision-detection, physics, collision-resolution, aabb
---


# Question
Title: Am I implimenting a sweep and prune broadphase correctly?
The code that I am using is:

```
    std::vector <PhysicsBody*> physicsChildren; //containing all objects

    ...

    std::sort(physicsChildren.begin(), physicsChildren.end(), sortByLeft);
    std::vector <PhysicsBody*> activeList;

    unsigned int one;
    unsigned int two;
    for(one = 0; one < physicsChildren.size(); ++one)
    {
        activeList.push_back(physicsChildren[one]);
        for(two = 0; two < activeList.size(); ++two)
        {
            if (physicsChildren[one]->m_position.x + physicsChildren[one]->m_radius > activeList[two]->m_position.x - activeList[two]->m_radius)
            {
                CheckIntersectionBetween(physicsChildren[one], activeList[two]);
            } else {
                activeList.pop_back();
            }
        }
    }

```

I think something is wrong because for 800 objects 309169 calls to `CheckIntersectionBetween`. A bruteforce would use 640000 calls, I didn't think this was much improvement (considering only objects close in the x-axis should test).

I wrote the code from reading Jitter-Physics article about SAP:

```
Create a new temporary list called “activeList”.
You begin on the left of your axisList, adding the first item to the activeList.

Now you have a look at the next item in the axisList and compare it with all items
 currently in the activeList (at the moment just one):
 - If the new item’s left is greater then the current activeList-item right, then remove
the activeList-item from the activeList
 - otherwise report a possible collision between the new axisList-item and the current
 activeList-item.

Add the new item itself to the activeList and continue with the next item in the axisList.

```

What have I done wrong?

# Answer
I misinterpreted `remove
the activeList-item from the activeList` to mean pop\_back the item just added(I had just been added an active item, it was logical! ;) ) when, because the activeList was being looped, meant remove that specific one. Hence:

```
activeList.erase(activeList.begin() + two);

```

has replaced that line. Now 11408 checks are being done for the 800 objects (55x less than brute) and this seams much more logical to me.
> 0 votes

---
Tags: collision-detection, physics
---


# Question
Title: Creating a png sequence in Flash? details?
I was wondering if someone could please explain the process and rules for turning an animation into a png sequence, in flash CS5.

I know you can go to export movie and chose png sequence but sometimes I only get 1 frame?

I don't know if my character (which was imported from illustrator) should be a graphic or a movie clip symbol and I also have animation within layers in the timeline, I don't know if they all have to be the immediate timeline??

Also my intention for the animation (png sequence) is to make a sprite sheet with texture packer and then to take it into cocos2d, and then use for my iphone game. If there is anything I need to keep in mind when animating for this purpose, please any advice would help.

One last thing does my animation need to be frame by frame (which is what I have been doing) or can I use classic / motion tweens in my animation and still export as a png sequence.

As I'm sure you can tell i'm pretty new to flash and iphone development so any help or advice would be greatly appreciated, sorry for all the questions.

# Answer
The "export movie" command exports the currently active timeline as a PNG sequence. You can export any kind of animation, that means frame-by-frame, tweens or shape-tweens. It also doesn't matter if you're animating bitmaps or vector objects... a good rule of thumb is: You'll get exported what you see when you play the timeline within the Flash IDE (hit `Enter`).

Animations within MovieClips won't work. If you have nested animations, your best bet would be to export to QuickTime (which would even allow you to export scripted animations). Make sure to tick "Ignore stage color (generate alpha channel)", choose a lossless codec (eg. Animation) and then convert from QuickTime to a PNG sequence.

Your further progress seems fine as it is. Drag the folder with your exported PNG frames into TexturePacker and let the tool handle the rest.

Most likely you'll want to support retina displays, so make sure your assets are double the screen-size in Flash or set the stage-size or DPI to double the original size in the export dialog.

Also be aware that the maximum texture size on iPhone 3G is 1024x1024 and 2048x2048 on iPhone 4 (since this will use retina assets, it basically translates to the same amount of screen-points for iPhone 4 and 3). Switching texture during animation can be cumbersome and also have an impact on performance, therefore I suggest you don't split up animations to multiple textures.
> 1 votes

# Answer
Your problem is probably that you had animations nested inside multiple objects; the "Export PNG Sequence" function only works on the base timeline.

Fortunately a variety of tools exist to make exporting Flash animations more robust. Many of these tools also turn the images into a spritesheet rather than a sequence of separate images. You'll want your animations in spritesheets (ie. all the frames are assembled into a single image that you display portions of) because that's a lot better for performance.

One such tool is Animo (formerly known as SpriteLoq) although that tool has gotten crazy expensive after some updates. The best free tool I know of is Zoe. Note that both tools say they are built for a specific development tool, but they simply output image files.
> 0 votes

---
Tags: animation, ios, flash-cs5, png
---


title: HLSL Circle all white

text:
# Question
Title: HLSL Circle all white
I have been trying to get my shader code (HLSL) to draw a simple circle but after a day and a half I am getting nowhere. It seems people are using $$x^2 + y^2 = r^2$$ and remap texcoords but I only get a white quad.

```
    struct VertexShaderStruct
{
    float4 Position : POSITION0;
    float2 Tex0 : TEXCOORD0;
};

VertexShaderStruct VertexShaderFunction(VertexShaderStruct input)
{
    VertexShaderStruct output;

    float4 worldPosition = mul(input.Position, World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);
    output.Tex0 = input.Tex0;

    return output;
}

float4 PixelShaderFunction(VertexShaderStruct input) : COLOR0
{
    float dx = 2 * input.Tex0.x - 1;
    float dy = 2 * input.Tex0.y - 1;
    float hyp = (dx * dx + dy * dy);

    return (hyp == 1)? circleColor : otherColor;
}

```

I define circleColor as blue and otherColor as white, so it seems `hyp==1` always fails.

# Answer
> 7 votes
The fragment shader is executed for each fragment with a single uv for this fragment which will probably never fall perfectly on 1.

You could map the target area roughly to the width of a render target fragment.

Eg something like:

```
abs(hyp - 1) * CircleRadiusInPixel < BorderWidthInPixel*0.5

```

**Further explanation:**

Your gpu rasterizes the triangles and executes the fragment shader for each fragment. A fragment is basically a pixel on your screen when MSAA is not active. For each of these fragments the input.Tex0 is filled by interpolating the values from the vertices. As the vertex values for Tex0 range from (0,0) to (1,1) the fragments get values between (0,0) and (1,1). Each fragment only gets one Tex0 representing the value at the center of the current fragment. So it is very unlikely that the fragment centers lie EXACTLY at distance 1 from the center of the circle. If you align everything perfectly, you could probably get 4 pixels (left-middle, right-middle, top-center and button-center) to get correctly colored but never the whole circle and it will probably look different on different vga's.

Even if you somehow could be sure that all pixels are aligned, never compare floats you calculated to an exact value. Floats are never exact as they have limited precision and are adjusted to it after each computation. Compare ranges instead.

You can get an even better looking circle adding some kind of fade out:

```
float nonBorder = saturate( abs(hyp - 1) * CircleRadiusInPixel / BorderWidthInPixel*0.5 );
nonBorder = pow( nonBorder, 2.0f );
float4 outColor = lerp( circleColor, otherColor, nonBorder );
return pow( outColor, 1.0f / 2.2f ); // gamma correction

```

---
Tags: shaders, hlsl
---


# Question
Title: Handling Origin/Anchor Points in a Scene Graph
I'm trying to implement a simple scene graph on iOS using GLKit but handling origin/anchor points is giving me fits. The requirements are pretty straightforward:

* There is a graph of nodes each with translation, rotation, scale and origin point.
* Each node combines the properties above into a single matrix (which is multiplied by it's parent's matrix if it has a parent).
* Nodes need to honor their parent's coordinate system - including the origin point (i.e. a child's origin should line up with the parent's origin)

So the question is:

What operations (e.g. scaleMatrix * rotationMatrix * translationMatrix, etc.) need to be performs and in what order so as to achieve the proper handling of origin/anchor points?

P.S. - If you are kind enough to post an answer please mention whether your answer is based on column or row major matrices - that's a perennial source of confusion for me.

# Answer
> 2 votes
You might not need an anchor point in each node. When you make the 3D model, you can place it so that the origin is at the anchor point. For example, if you're making a human model, and you want the anchor point to be between the feet, then just make sure the origin is between the feet when you export from Blender, or whatever you are using.

If you *do* want anchor points, then the matrix for each node must include an additional translation step, which comes before scaling/rotation/etc.

So, if you have a node that looks something like this:

```
struct Node {
    vec3 position;
    vec3 anchor; //in model coordinates, stored as an offset/displacement from the model's origin
    vec3 scale;
    matrix rotation; //could also be a quaternion, axis + angle, euler angles, etc.
};

```

Then you would calculate the matrix of each node like this:

```
Node n = whatever();
matrix m = translate(n.position) * scale(n.scale) * n.rotation * translate(-n.anchor)

```

Pretend that the `scale` and `translate` functions return a `matrix`. So the transformations, in order (right to left), are:

1. Translate by `-anchor`
2. Rotate
3. Scale
4. Translate by `position`

Because the translation by `-anchor` comes first, all subsequent transformations will treat the anchor as the origin.

When it comes to the parent node, it looks like you already know how to do this. Just multiply the matrix of the parent by the matrix of the child, which will put the child into the parent's coordinate system.

It doesn't really matter whether the matrices are column or row major. That is only important when you are handing off the matrices to a third party, such as using `glUniformMatrix4f` in OpenGL (which requires column-major order).

---
Tags: matrix, scene-graph
---


title: Objects being drawn on wrong layers

text:
# Question
Title: Objects being drawn on wrong layers
I have the main game (Game1.cs) draw the sprites like so:

```
        //Clear everything
        GraphicsDevice.Clear(Color.CornflowerBlue);

        //Begin drawing
        _spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);

        //Draw enemies
        for (int i = 0; i < ControlObj.EnemyList.Count; i++)
        {
            ControlObj.EnemyList[i].DrawObject(_spriteBatch);
        }

        //Draw powerups
        for (int i = 0; i < ControlObj.PowerupList.Count; i++)
        {
            ControlObj.PowerupList[i].DrawObject(_spriteBatch);
        }

        //Draw other stuff
        for (int i = 0; i < ControlObj.OtherStuffToDraw.Count; i++)
        {
            ControlObj.OtherStuffToDraw[i].DrawObject(_spriteBatch);
        }

        //Draw the player
        ControlObj.PlayerObj.DrawObject(_spriteBatch);

        //Finish drawing
        _spriteBatch.End();

```

DrawObjects method:

```
        public virtual void DrawObject(SpriteBatch sb)
    {
        int imgIndex = (int)Math.Floor(ImageIndex);

        //Draw the object!
        sb.Draw(Sprite[imgIndex],   //Sprite (Texture2D)
                Center,             //Location of object (Vector2)
                null,               //Source rectangle (USELESS)
                ColorBlend,         //Color blend (Color)
                Rotation,           //Rotation angle (in radians)
                CenterOffset,       //Offset (Vector2)
                ImageScale,         //Image scale (Vector2)
                SpriteEffects.None, //Flip sprite? (USELESS)
                Depth);             //Depth of the object
    }

```

The issue: Some objects draw other objects by overriding the DrawObject method like so:

```
        public override void DrawObject(SpriteBatch sb)
    {
        base.DrawObject(sb);

        for (int i = 0; i < OtherStuffList.Count; i++)
        {
            OtherStuffList[i].DrawObject(sb);
        }
    }

```

For some reason, objects drawn by other objects do not obey their depth property. How could I fix this?

# Answer
> 0 votes
Oops, I found the source of the issue... Turns out that having objects draw other objects works fine. The issue was that I initialized values to zero in objects' constructors like so:

```
    public GameObject(Game1 game) : base(game)
    {
        game.Components.Add(this); //ISSUE HERE
        //...
        Depth = 0;
    }

```

And I set their values per-object in Initialize():

```
        //Set the drawing depth
        Depth = _myGame.UtilitiesObj.GetDepth(Utilities.DrawingDepths.Missile);

```

The issue was that calling Game1.Components.Add() also called Initialize() immediately. So the values would be set to their correct values, and then "initialized" back to 0. I thought that Initialize() was always called AFTER the constructor, hence the bug.

# Answer
> 2 votes
To develop on what our fellow Xavier said, do not use that SpriteSortMode in your case. As it is right now, it doesn't matter the order objects are put to be drawn, they will be sorted by their layer value later, before being put on screen.

Use SpriteSortMode.Deferred (`_spriteBatch.Begin(SpriteSortMode.Deferred /*!!*/, BlendState.AlphaBlend);`) and this will most probably work. This one disables ordering, making it so that textures are drawn in the order they are called.

You can check out some more info on SpriteSortMode here, if you'd like.

# Answer
> 0 votes
To implement the concept of layers you could call Begin, draw the layer's content and call End on the spritebatch (note that more Begin/End calls means loosing performance!).

Make sure that there aren't any sprites trying to be drawn on the same depth value, as the draw order is not defined for 2 sprites with the same depth value (causing random flickering).

Since you're using some kind of object hierarchy to draw your game I'd recommend you to avoid using depth values and use the hierarchic model through all the game (cocos2d handles it this way).

This way you can have a screen object that draws all the screen, and the order of it's children will decide who draws first. This idea, used recursively, decides all the relative depths for your sprites.

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


title: How to implement in-game purchase?

text:
# Question
Title: How to implement in-game purchase?
I am currently developing an indie game using XNA/C#. I would like to give players the opportunity to try a free (but somewhat limited) demo version of the game. Nevertheless, the player should be able to purchase the full version of the game from within the demo version (after short download) immediately unlocking the full version.

The tricky part is that I would like to permanently remember this purchase as I would like to give players how purchased the game the opportunity to download additional content etc. for free later. Nevertheless, the user should be able to switch computers or reinstall the game without loosing that "purchased"-flag. One (maybe) possible way would be to give each user a serial number that can be checked once at gamestart. Is there a library etc. to support this or is there maybe another best-practice for these kinds of things.

I guess the well-known payment processors as BMC-Micro and Fastspring do not support this, do they.

PS: I would like to keep the game DRM-free.

# Answer
> 3 votes
> The tricky part is that I would like to permanently remember this purchase as I would like to give players how purchased the game the opportunity to download additional content etc. for free later. Nevertheless, the user should be able to switch computers or reinstall the game without loosing that "purchased"-flag.

If you make a website for the game, you can require people to create an account on your website in order to buy the full version. You can store every account in some sort of database.

Then the demo of the game can have a login option (only required for buying the game). When someone is logged in with their account, the option to buy your game can become available if they do not already own the full game. When players buy the game in this manner, you can simply add the "bought game" status to their account and unlock the full game on their computer.

Additionally, when a player who has bought the game redownloads the demo on another computer, the full game can immediately be unlocked after they login, since they have a "bought game" account.

This is similar to how Minecraft does it.

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


# Question
Title: Unity3d generating a file in iOS and saving it on a linux machine
I've done a little research and don't know if the following is possible.

At the moment I have created a small application in Unity that generates an XML file. This file will be used to help set up my game. It's done in Unity due to it being cross platform with no need to re-write a single line of code. Eventually this will run on an iPad.

However, my game will be running on a linux computer and I need to pass over the XML file to the computer that will be running the final game (please don't ask why I'm doing that, it's something I need to do). So what I want to know is the following:

Can I generate my XML file on an iPad and have that XML file be saved, and transmitted to a linux machine, without the need to manually copy the file over. If so, how is this possible?

# Answer
> 1 votes
You could open a socket from your iOS device to an app listening on your Linux box, or have your iOS app post to a web page or consume a web service that runs on your Linux PC. Another possibility would be to use a web API for something like Google Docs or DropBox to use the cloud as the middle-man.

---
Tags: c#, unity, ios, linux
---


title: Networking dynamic game worlds

text:
# Question
Title: Networking dynamic game worlds
I'm working on a 3D massively multiplayer space game in C++ and I'd like some advice from experienced game developers.

Essentially, the world (universe) simulated on the server is absolutely dynamic, which means the location, position, rotation of every single game object in the game is subject to change at any time, as the server is completely authoritive over this. *Entire planetary systems can be moved*. The server is persistent so movement of everything is simulated in real time. You could log in once, grab a spaceship, fly around a little, and log out again. Upon logging in the next day you log in to find yourself drifting towards a black hole!

So, GameDev, how would you approach sending every game object to the several clients that could be playing? This means loot on the floor, spaceships, space carriers, planets, stars, planetary systems, galaxies! I mean, how could I represent the game objects during travel to a client? As a 3D model name and associated attributes? Or maybe a single id that the client knows about, but then how would it handle users customizing their ships or adding other components to it? I am just unsure how I can replicate the game objects on the clients and allowing support of spaceship custimization and perhaps avoiding updating the game client for every new object added. Maybe it should actually send the model file over, Garrys Mod style?

Tips for network optimisations are welcome too but it isn't urgent this early in development.

# Answer
After I wrote my first answer, you edited your question and shifted the focus on how to handle the visual information about each object. That's a different aspect I would like to talk about in a separate answer.

It depends on how extensive your customization system is, but unless you go for something *extremely* flexible, you could certainly express the look of each ship with a bunch of variables (basic hull, list of attachment parts on the hull, color palette...). Sending the whole 3d mesh would certainly be overkill.

You, again, can use information hiding here to both conserve network traffic and to make your game more interesting. When an object is at the edge of sensor coverage, the player shouldn't even know all details about it yet. Just an approximate size and the movement vector would be enough. The client should also get an unique ID for each object, so that the server can refer to further information about this object by providing the ID. When the player gets close enough to realize that it's not a moon but a space station, they would get another message consisting of the same unique ID and the hull type ID so that they can render it with the correct model. When they get much closer, they could get a list of the attachments for that ID and how they look, but not what they actually do (color is red with yellow decorations, some gun on left wing, some gun on right wing, some equipment piece on top). To find out what these attachments actually are, they would have to use an advanced short range scanner on the ship (MK3 positron cannon on left wing, LV-300 heavy pulse laser with Level 2 accuracy upgrade on right wing, Class IV long range scanner on top - powered off).
> 2 votes

# Answer
To minimize network traffic it's important to minimize the number of updates. This has to be done by:

1. minimize the number of updates per object
2. minimize the number of objects a client needs to be updated about

**Regarding 1:** A common newbie mistake is to update the positions of objects at regular intervals. They send the same position of an object over and over again, even though the object hasn't moved. A much better strategy is to only update positions when they actually changed. When you have a lot of movement, it might be even better to not send changes in position, but only changes in movement vectors. In your case, when a ship is moving around, you would only send an update when it changes its course. No updates are required while it moves with a constant speed in a constant direction, because the clients can extrapolate the position themself. When your game is aiming for a very realistic simulation of space physics, you might even go a step further and only report changes in acceleration, because spacecrafts maneuver in frictionless space by switching accelerating trusters on and off.

**Regarding 2:** You didn't say much about your gameplay, but I assume that there are events a client doesn't need to know about (or even mustn't know about, like movement of stealthed ships or spawning of treasure which is supposed to be hidden). A fierce battle taking place on one end of the universe certainly doesn't concern someone who is mining for resources on the other. For that reason you should only update clients about events in their vicinity. In the context of your space simulation, "vicinity" might be different depending on the scale of the event. The movement vector of a small asteroid would only be reported to people within visual range. Updates about a ship would be sent to people in the same star system. When a whole star system is moved as you described, it certainly affects everyone in the galaxy, so everyone needs to know the new position of the star system. But do they also need to be informed about all the planets, moons and ships in that system? When they want to know what happened to them, they would have to travel there and find out.

These are only examples, of course. Who needs to know about what depends largely on your gameplay and the role of information hiding in it.
> 3 votes

---
Tags: c++, networking, mmo
---


# Question
Title: Can I develop a game on PC in Java and move it to Android?
I have fairly good experience with Java, but new to Android development. I would like to develop a 2D game which would have animations and online play.

Can I initially develop this game on my pc using Java and then implement in Android?

Will the canvas in Java be sufficient or should I use a game engine?

# Answer
> 15 votes
It sounds like your goal here is just to make games.

Use LibGDX. With this Library you can test it and deploy it to Windows/Linux/Android/HTML5. It's also free.

# Answer
> 3 votes
You would make it easier for yourself implementing a game framework. Also if you'd develop your game outside the android framework you might use libraries that don't exist on android.

I'd suggest you build and test it directly on android drom the first line of code you write while using a game framework. You can however build a big part of your game as a jar library so you can re-use parts of it. This library can then be imported in your android project and you can see if it runs (and your not missing libs etc)

# Answer
> 3 votes
LibGDX is my weapon of choice, note though that many of the tutorials out there are set up pre-0.9.6 and quite a lot got changed in that update, rendering most of them useless. https://www.youtube.com/user/doctoriley has a decent series of tutorials which should give you a starting point (not exactly best practice but you get to understand how it all hangs together) and the code can be found at https://bitbucket.org/GQGK/creating-a-game-in-java-youtube-series/overview if you want it.

LibGDX is excellent, a layer on top of lwjgl which provides support for Android, desktop (win/lin/mac) and html5 (though frankly I'd say just use an applet instead as it's quite limited) and I believe work-in-progress iOS support too.

The documentation is relatively solid (though the wiki is incomplete and outdated) and it has been used in commercial projects.

# Answer
> 2 votes
There is great blog just for you with number of tutorials for game development for Windows, Mac and Android with Java. Check out this tutorial: http://obviam.net/index.php/getting-started-in-android-game-development-with-libgdx-create-a-working-prototype-in-a-day-tutorial-part-1/

Unfortunately author of the blog stopped writing, but nevertheless it's a great start, and I've done most of tutorials in August and they were all valid.

# Answer
> 2 votes
Android does support the native Java API, but it is heavily reliant on the extended Android-specific API. If you really want to do this, then I would advise writing as much of the game logic completely independent of the platform interface (a good practice anyway).

I would recommend working directly with the Android API though.

# Answer
> -1 votes
Yes, you can make Android Game without the prior knowledge of JAVA and without Android SDK. It is a Hypernext Android creator which gives you complete environment to make an Android game.

---
Tags: 2d, java, android
---


# Question
Title: XNA 3D custom shader/effect gives shakey rendering in the distance
I am rendering a simple flat plane + texture to use as the floor for a game. I'm rendering it using a custom effect I've written.

The problem I have is that the ground in the distance gets a bit distorted and shakey when the camera moves forwards and backwards.

If I render the same model + texture using the BasicEffect instead of a custom shader it appears smooth and works correctly.

Here's the XNA code setting up the custom effect:

```
Matrix worldMatrix = Matrix.CreateScale(0.2f);
_floorEffect.CurrentTechnique = _floorEffect.Techniques["Textured"];
_floorEffect.Parameters["World"].SetValue(worldMatrix);
_floorEffect.Parameters["ViewProjection"].SetValue(camera.view * camera.projection);

_floorEffect.Parameters["diffuseTexture"].SetValue(_diffuseTexture);

foreach (EffectPass pass in _floorEffect.CurrentTechnique.Passes)
{
     pass.Apply();
     device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, meshPart.NumVertices, meshPart.StartIndex, meshPart.PrimitiveCount);
}

```

Here's the shader code:

```
float4x4 World;
float4x4 ViewProjection;
Texture diffuseTexture;

sampler TextureSampler = sampler_state { texture = <diffuseTexture>; magfilter = LINEAR; minfilter = LINEAR; mipfilter=LINEAR; AddressU = wrap; AddressV = wrap;};

struct TexturedVertexToPixel
{
    float4 position : POSITION0;
    float2 textureCoords : TEXCOORD0;
};

TexturedVertexToPixel TextureVertextShader(float4 inPos : POSITION, float2 inTextureCoords : TEXCOORD0)
{
    TexturedVertexToPixel output;
    float4x4 preWorldViewProjection = mul (World, ViewProjection);
    output.position = mul(inPos, preWorldViewProjection);
    output.textureCoords = inTextureCoords;

    return output;
}

float4 TexturePixelShader(TexturedVertexToPixel input) : COLOR0
{
    return tex2D(TextureSampler, input.textureCoords);
}

technique Textured
{
    pass Pass1
    {
        VertexShader = compile vs_2_0 TextureVertextShader();
        PixelShader = compile ps_2_0 TexturePixelShader();
    }
}

```

Videos to demonstrate what I mean:

Using the BasicEffect http://www.youtube.com/watch?v=matmrIZH-pU
Using the Custom Shader http://www.youtube.com/watch?v=Fu9P4D-UCTc (see it clearest in 1080p full screen)

Notice the difference when looking at the ground in the distance.

# Answer
I managed to fix the issue by enabling the generation of MipMaps for the texture used by the model. This is done within visual studio by finding the texture in the content project right clicking going to properties and then expanding "Content Processors" and enabling the option "Generate MipMaps"
> 0 votes

---
Tags: xna, shaders, hlsl
---


# Question
Title: How to implement scene changing in real-time?
I want to implement real-time scene changing effects to make my game could changing from spring to summer, summer to fall, fall to winter. And Chaning effects like this game. Giana Sisters.

I think Giana Sisters use animation to transit from two scenes, but I dont know how to make these animations.

Is any other suggestions could make this effects?

# Answer
> 1 votes
To do something like this you'll need an animation system being able to blend two different animations over each other (i.e. apply both at the same time).

Other than that, it's not that different from standard animations. The animation changing the appearance is just playing situational (i.e. during the "phase changes").

Something like this is trivial to do, if you're morphing different things (e.g. only switching colors).

The easiest way to do this would probably be some way to create some counter for the progress. For example - I'm using only two different states here - you could have summer and winter (ignore spring and fall for now).

Let's call this value `timeOfTheYear` with a valid range from `0` to `255` (i.e. a single byte).

To animate the time/change you just let the value alternate to/from the minimum and maximum values based on your game timing. E.g. the value starts at `0` (summer) and increases till it hits `255` (winter). It then goes back to `0`, back to `255`, etc. This change can happen with a specific velocity, e.g. `+-1` per millisecond.

You only do this change if you want to change time (e.g. when some special button is pushed).

Once this is implemented, you only have to animate the change as well.

As an example, you might be drawing leaves on trees. Set their transparency according to your `timeOfTheYear` value (e.g. 0 -\> 100%, 32 -\> 90%, 127 -\> 80%, 192 -\> 40%, etc.).

Instead of changing the opacity/transparency you could as well draw some animation frame based on this (which is what Giana Sisters is doing). For example, at 0 you draw the first frame, at 255 you draw the last frame - any other values in between draw steps between these.

---
Tags: animation
---


# Question
Title: What is technical specs for iOS platform for a game?
I would like to know when a contractor ask you for a technical specs for iOS platform of a game, what's the description that you should give back to him?

# Answer
> 1 votes
Usually technical specs for an iOS game should be something related to hardware generations. For eg:- game should support all devices from iPhone 3GS and above , should support iPad 2 and above etc , iPod touch 4th generation and above etc.

# Answer
> 1 votes
## Set concrete and measurable specs for as much as possible.

**\- List of supported device types and generations**

* iPhone
* iPod touch
* iPad

For the iPod touch **specifically** ask for guarantees regarding memory requirements. Even some high profile games can run out of memory on the iPod Touch. The developers usually use iPhones for development and don't bother with thorough testing, assuming the hardware is the same. But it has half the memory! Same for 1st gen iPad.

**\- List of device versions**

iPod touch 2nd generation and iPhone 3G are quite old and slow, so I'd suggest setting iPhone 3GS as minimum. List all devices that you want to be supported.

**\- iOS versions**

Example: it might be extra work to support iOS 4 and Game Center support will be disabled.

**\- Language support**

If you plan on ever adding more languages, the game should be setup to support it from the start - localization strings, support loading different artwork and audio for each language etc.

**\- Game Center integration**

**\- Retina-grade artwork**

(As opposed to blurry/jagged upscaled versions of low resolution artwork.)

**\- Support for iPhone 5's screen resolution**

It is taller, so artwork must be redone, game must be adjusted.

**\- Performance**

As with the memory requirements, get specific guarantees. For example: startup time is x seconds from tapping icon to main menu on iPhone 4, framerate never falls below 30fps on iPhone 4 or averages to at least 40fps during a typical gameplay session. IPA package size below 50MB. And of course: **no crashing**. You might ask them to integrate a crash reporter such as this one or this one.

**\- App store validation**

The deal is not done until it passes Apple's validation process.

**\- Special requests**

Support for iCade and other 3rd party controllers, TV output, Airplay support etc.

# Answer
> 1 votes
**IMPORTANT** technical specifications for iOS platform games

**OS Specification**

* Minimum iOS (5.1 or 4.3 etc)

**Hardware Specifications**

* iPhone & iPod Touch (Retina, 3.5 inch, 4 inch)
* iPad (1, 2, New)

App/Game device Family

* iPhone
* iPad
* Universal

**GPU Specification**

* OpenGL ES (v1.1 or v2.0)

**Others**

* iPod touch 2nd generation and iPhone 3G are quite old and slow, and OpenGL ES v1.1 does not support those versions. So would you add / remove those as technical spec.
* Memory requirements
* IPA size issue

# Answer
> 0 votes
just specify the target device and OS e.g

iPad1/iPad2/iPad3(Retina)/iPhone Retina including iPhone 5, iOS 6+

---
Tags: iphone, cocos2d-iphone, ios, objective-c, ipad
---


# Question
Title: Meaning of offset in pygame Mask.overlap methods
I have a situation in which two rectangles collide, and I have to detect how much did they collide so I can redraw the objects in a way that they are only touching each other's edges.

It's a situation in which a moving ball should hit a completely unmovable wall and instantly stop moving. Since the ball sometimes moves multiple pixels per screen refresh, it is possible that it enters the wall with more than half its surface when the collision is detected, in which case I want to shift its position back to the point where it only touches the edges of the wall.

Here is the conceptual image it:

I decided to implement this with masks, and thought that I could supply the masks of both objects (wall and ball) and get the surface (as a square) of their intersection. However, there is also the offset parameter which I don't understand.

Here are the docs for the method:

> ```
> Mask.overlap
>
>     Returns the point of intersection if the masks
>     overlap with the given offset - or None if it does not overlap.
>     Mask.overlap(othermask, offset) -> x,y
>
>     The overlap tests uses the following offsets (which may be negative):
>
>    +----+----------..
>    |A   | yoffset
>    |  +-+----------..
>    +--|B
>    |xoffset
>    |  |
>    :  :
>
> ```

# Answer
> 2 votes
The *offset* gets added to the coordinates of all parts of the mask that you pass into the function.

So, if you have mask *A*:

```
000
001
001

```

and mask *B*:

```
000
010
000

```

and you ask

```
A.overlap(B, (ofsx, ofsy))

```

then ofsx and ofsy are added to the coordinates of B.

Imagine both masks in the context of a large raster with the top-left corner of *A* at the origin. *B* is shifted (ofsx, ofsy) within that raster before its overlap with *A* is calculated.

For example if you ask

```
A.overlap(B, (3, 4))

```

Then the following raster is evaluated for overlaps:

```
X X X X X X X X X X X X X X X X
X X X X X X X X X X X X X X X X
X X X X X X X X X X X X X X X X
X X X X X X X X X X X X X X X X
X X X X X X X X X X X X X X X X
X X X X X X X|0 0 0|X X X X X X
X X X X X X X|0 0 1|X X X X X X
X X X X X X X|0 0 1|X X X X X X
X X X X X X X X X X X X X X X X
X X X X X X X X X X|0 0 0|X X X <-  B @ imaginary origin + (3, 4)
X X X X X X X X X X|0 1 0|X X X
X X X X X X X X X X|0 0 0|X X X
X X X X X X X X X X X X X X X X
             ^
             |
             A @ imaginary origin

```

if you put negative values into the *offset* parameter, it shifts *B* in the other direction.

---
Tags: collision-detection, pygame, collision-resolution
---


title: Skeletal Animation with UV seams

text:
# Question
Title: Skeletal Animation with UV seams
I have a UV-mapped model that I am about to animate and load into my game. Like most unwrapped models, I have several UV seams. In order to render the model correctly, I split each vertex along the seam into two vertices whose positions and normals are the same but whose UV coordinates differ. I do the same thing when I have more than one normal associated with a vertex.

This works fine for static models, but now I'm getting into the realm of animation. Technically since the two seam vertices occupy the same position in space they should use the same joint weights and joint IDs. Right now the simple way to do this is to just give them the same joint weights and joint IDs and then skin them separately. But to me this seems very wasteful because there are so many vertices along seams and so there will be many duplicate computations. It gets even worse since I need to render the animated model into the shadow map too.

Does anyone have any thoughts about improving this process? I've considered using something involving OpenGL transform feedback to save the results of the transformed vertices. This would at least help with computing transformed positions once and using the same results in the main render pass and shadow pass, but I still can't think of an elegant way to handle the duplicate computation along UV seams.

# Answer
That is the general way to do it. Since OpenGL only supports one index per vertex you have to split the vertices if their attributes differ in any way. The modeling tool or exporter you use should take care of this for you (like the edge split modifier in Blender). I would say not to worry about the amount of duplicated vertices, since they're unavoidable. The only thing you can really do is to use fewer UV seams.
> 2 votes

---
Tags: opengl, animation, skeletal-animation, uv-mapping, transformation
---


title: Java 2D tile map and rendering it

text:
# Question
Title: Java 2D tile map and rendering it
Please help me! I am thinking of generating different terrains environment every time the game loads again. But i am thinking of loading or drawing a image containing all the units like river, land and tree. Then the checking of obstacles against the units like boat, car and plane. I have done lots of research but i am struck on how to do it. Please help me.

# Answer
The question is a bit general so here's a general answer. http://code.google.com/p/libgdx/wiki/TiledMaps gives a tutorial on using a tilemap (http://www.mapeditor.org/) within your game. You can dynamically change tiles, etc. Each tile may have properties, such as which objects are stored within it, or whether it is water (in which case you'd only let a player swim or use a boat, but not drive a car) or whether it's a tree (in which case you can't walk through it) etc. If you want a more specific answer you'll have to provide a more specific question.
> 2 votes

---
Tags: java, maps, terrain-rendering
---


# Question
Title: What is a good way to load more than a million images for a collectible card game?
I'm using C# with MonoGame and I'm wondering what would be an efficient way to load more than a million card images for a collectible card game. More cards would be continuously added in future updates and what not. I'm sure there are some genius ways to go about this which are both elegant and efficient. I'm hoping to obtain some insight on how others would solve this problem.

**Added more details:**

The cards will all be on a client side application the user downloads. The server will make sure the players are not cheating. I'm trying to figure out what are efficient ways to manage a large amount of card images on the client side regarding the loading and unloading of the cards.

I understand the cards should loaded and shown only when necessary. However, there are points in the game where the user can look through their entire collection. I was thinking with a scrollbar or something along those lines. They can filter their cards based on certain properties of the cards. In this scenario, how would I manage the loading/unloading of the cards in real time to make it seamless and efficient.

Thank you for any help!

# Answer
A million images are obviously not going to fit in RAM at the same time, so you need some sort of caching and streaming mechanism to constantly load in the images you need.

An easily-implemented but slow solution is to load in the image as soon as it is needed and unload the image as soon as it is unneeded, i.e. when the face of the card becomes visible/invisible. This will involve a lot of file I/O and will be extremely slow.

An alternative and better solution is to have some sort of cache. The basic function of the cache is to retrieve a card image given an ID, be it a string, integer, or something else entirely. Internally, the cache will store a `Dictionary<ID, CardImage>` to map a loaded image to this ID. When the cache's `Retrieve(ID card)` function is invoked, it will first check to see if the image has been loaded, i.e. check if the dictionary has the key `card`. If so, that card image will be returned. If not, the card image will be loaded and then returned.

Of course, the cache doesn't have unlimited memory. You need to have some system in place to discard unneeded card images. The simplest way to do this is to sort the images by when they were last used. The most "stale" card image is then discarded to make room for a new one. You could also implement a more complex system that determines which image to discard based on the number of cards in play, how often the card is used, etc.

A side benefit of having a cache is that you can easily "prefetch" card images before they are needed so that the game doesn't appear to pause and load the image when the card comes into view. For example, if your game has decks, you can prefetch the images of the top few cards. Make sure that you have your images loading on a background thread so that the game doesn't stall if many images need to be loaded at once. Simply play an animation to delay the card being shown if its image is still pending.

The great thing about a cache like this is that it can be used for any kind of resource, like shaders, models, sounds, and even game object prototypes or blueprints. Just make sure you have a robust prefetching system for more real-time and demanding games, especially open-world games that shouldn't have loading screens :)

EDIT: Here's a simple, single-threaded implementation that only implements a time-based discard system. Card images can be prefetched simply by calling `CardImageCache.Retrieve("card name")` without worrying about the return value. Card images come in the form `card.png`, where `card` is the value passed into `Retrieve()`.

```
public static class CardImageCache
{
    public static CardImage Retrieve(string card)
    {
        if(_cards.ContainsKey(card))
        {
            // The image is already in memory
            return _cards[card];
        }
        else
        {
            if(_cards.Length() >= _size)
            {
                // Discard the oldest image
                string discard = _times.Dequeue();
                _cards.Remove(card);
            }

            // Load the new image
            CardImage image = CardImage.FromFile(card + ".png");
            _cards.Add(card, image);
            _times.Enqueue(card);
            return image;
        }
    }

    private static Dictionary<string, CardImage> _cards = new Dictionary<string, CardImage>();
    private static Queue<string> _times = new Queue<string>();

    // 100 card images can be stored at a time
    private static int _size = 100;
}

```

*There may be some errors, my C# is a little rusty...*

EDIT 2: In response to your edit:

Basically, just prefetch the images within a certain radius of the visible region of the collection. If you configure the system such that a CardImage that hasn't finished loading yet (in a background thread) can be "drawn" without any errors, the user won't care that the image is suddenly popping in as they scroll over the card. They're probably used to using the internet.
> 3 votes

# Answer
Don't load them all into memory at once, that's just a terrible idea. Load them in from the hard drive when they come into play (on another thread), unload them when they're removed from play.

If you've got a deck in-game, pre-load the next few cards to prevent the game from freezing up when you draw a card.
> 4 votes

# Answer
I suggest using some sort of asset\_manager (steal it or code it) and flyweight pattern for image itself, since it might be the case there two or more cards use the same image. Also you can load all cards you need during level load or match load, well if you know what card will be used.

```
// you can also use caching behind asset_manager
image = asset_manager.get_image("evil monster card");

```

Another solution could be lazy initialization, load image then its actually used, not then game starts. Main draw back with this is speed decrease.
> 2 votes

# Answer
I would consider looking into a procedural generation solution for these. this would include the 'stats',and could possibly include the image.

when loading up the cards you are not loading an image but loading up a 'seed' for the card which will allow you generate any information required on game load.

this would save significant amounts of hard drive space

how the seed looks and works would depend heavily on the implementation of the procedural generation

all the caching and threading answers would apply to this solution also
> 1 votes

---
Tags: c#, architecture, image, monogame
---


# Question
Title: Why does the lighting change the objects color?
I have a code that draws a sphere. Without lighting it is white, but if I enable lighting, it's drawn in gray.

I don't know why the sphere changed it's color

```
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

void init(void)
{
    GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
    GLfloat mat_shininess[] = { 50.0 };
    GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };
    glClearColor (0.0, 0.0, 0.0, 0.0);
    glShadeModel (GL_SMOOTH);

    glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
    glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
    glLightfv(GL_LIGHT0, GL_POSITION, light_position);

    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_DEPTH_TEST);
}

void display(void)
{
    glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glutSolidSphere (1.0, 20, 16);
    glFlush ();
}

void reshape (int w, int h)
{
    glViewport (0, 0, (GLsizei) w, (GLsizei) h);
    glMatrixMode (GL_PROJECTION);
    glLoadIdentity();
    if (w <= h)
        glOrtho (-1.5, 1.5, -1.5*(GLfloat)h/(GLfloat)w,
                 1.5*(GLfloat)h/(GLfloat)w, -10.0, 10.0);
    else
        glOrtho (-1.5*(GLfloat)w/(GLfloat)h,
                 1.5*(GLfloat)w/(GLfloat)h, -1.5, 1.5, -10.0, 10.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize (500, 500);
    glutInitWindowPosition (100, 100);
    glutCreateWindow (argv[0]);
    init ();
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMainLoop();
    return 0;
}

```

# Answer
You haven't set a diffuse colour for your light (via glMatrialfv (GL\_DIFFUSE, ...) and - according to the GL spec - the default diffuse colour is {0.8, 0.8, 0.8, 1.0} - i.e. light grey. You also haven't set an ambient colour (default {0.2, 0.2, 0.2, 1.0} - dark grey).

The default behaviour of lighting is that it multiplies by the current colour, so with an object that's coloured white, that's going to result in grey.

In other words, it's grey because you told it to be grey.
> 7 votes

---
Tags: opengl, c
---


# Question
Title: How do I get consistent Xbox360 Controller input across Linux, Mac, and Windows?
I'm developing a browser plugin to provide joystick access to all browsers on all platforms. The issue that I'm running into is that OS X doesn't seem to provide Xbox 360 joystick input without installing some extra drivers, and even when those drivers are installed they map the buttons and axes completely differently than Windows and Linux.

I'm using xboxdrv on Linux, which has a pretty decent mapping and is very similar to the standard Windows XBox driver mapping. On windows XP using the default XBox Controller driver the order of the x and y axes are swapped. Is there an alternative driver that can be installed?

On OS X using Colin Munro's OS X Driver, the mapping is totally different though. The d-pad is mapped to the first four buttons and the axes are all switched.

What I want to know is what drivers do I need to install on each OS to get XBox 360 Controllers to register exactly the same as the do under Linux with xboxdrv.

```
OS: DRIVER
Linux: xboxdrv
Windows: ?
OS X: ?

```

The reason why I prefer the xboxdrv style of controller mapping is that the mapping is pretty much the same for any other random USB controller. The two primary axes are the same and the first 5 buttons are the same. This way the XBox controller will behave like an "enhanced" generic USB controller and any game logic won't need to know anything about the specific controller type. I want to be able to assume the basic axes and buttons will be mapped correctly (or at least consistently) and then use the extra buttons and axes for extra functionality.

The newer versions of the standard Linux X11 input also match exactly the xboxdrv mappings which is another reason that I prefer it.

# Answer
> Is there an alternative driver that can be installed?

Let's assume there was; I have no idea one way or the other myself. But if there was, it would map the buttons differently. So installing a browser plugin would also install this driver, which would override the current driver and screw up the button settings in every program that uses the controller.

I don't see a lot of people appreciating you doing that to their systems.

It would be better for your plugin to simply detect what OS its running on and adjust the inputs accordingly. You should only install drivers if the device would not work at all without them.
> 5 votes

# Answer
On Linux, I believe the standard driver is the xpad one (which is part of the kernel):

http://www.kernel.org/doc/Documentation/input/xpad.txt
> 1 votes

---
Tags: input, cross-platform, joystick, xbox-controller
---