title: Loading resources in a portable manner

text:
# Question
Title: Loading resources in a portable manner
I've been looking at ways to load data into a game. I even asked a question on stack overflow about reading binary data in a portable manner. The gist of the answer seemed to be that you can use the int types header file to specify an particular integer byte amount, but there's nothing really useful for floats, etc.

I then thought that you could use fixed point, rather than floating point, but I wanted to see how other games did it. Here is one example, a md2 loader: http://tfc.duke.free.fr/old/models/md2.htm . However, it seemed to assume that the size of various types would just work, and that they would be the same on the platform that made the md2, and the one that read it. This seemed to be fairly common in the code that I've seen so far.

So is it really common to just ignore possible different size issues, or have I just been looking at bad (or old) samples? If it's not, could you also demonstrate a better way to do it, or at least link to one?

Thank you.

# Answer
Portable? It's common to use the same binary loading code across different platforms, **but** to have the data creation pipeline output different **data sets to match each platform**.
> 4 votes

# Answer
Well, the problem is that a binary format is specific for a certain (or several) platforms, otherwise it wouldn't be a 'binary' format!

A non binary, say CSV with values as ASCII numbers or why not XML, could be read by 'any' platform that can read a file and do some simple number crunching.
> 1 votes

# Answer
Floats can be dealt with in an almost platform independent way by assuming that they are IEEE standard representations, which almost all platforms use.

From there you'll have to do another potentially non-portable operation - treat the memory holding the float as an integer and write that integer out. While I believe the standard doesn't actually support doing that portably, most implementations do allow it. Code would look something like:

```
 void write_float(uint8_t *buf, float x)
 {
    union float_uint_32 { uint32_t i; float f; };
    float_uint_32 value;
    value.f = x;
    write_uint32_t(buf, value.i);
 }

```

However as said in other answers, most games have tools that output binary data in a format specific to each platform to maximize loading performance. The quantity of CPU work required for loading data should be almost zero when you do that. Making it more portable slows things down.
> 1 votes

---
Tags: assets, file-format
---


# Question
Title: My game is dull; how would you make it more exciting?
The game is Darts for the iPhone. It's OK but it's more like a simulation than anything I'd ever claim to be overtly "fun". I am looking for some ideas to spice up the gameplay. What are your thoughts?

# Answer
> 11 votes
Let other people play it while you watch. Consider their reactions. Ask for their comments, and listen to them - this is surprisingly difficult.

Not knowing much about your game, it's difficult to give any more specific suggestions, but here are some that may or may not apply;

* Eye-candy is always fun. Consider television-sports game like huge transitions, replays, particles (explosions or confetti), etc
* Various game modes may help. Invent new ones!
* Scoring can be tweaked to make things more interesting, like chains, trying to get certain patterns, etc
* And of course, achievements for managing to do specific things.

# Answer
> 0 votes
When I first looked at your game I immediately expected that I'd be able to hold my phone in my hand like I would a dart and make a throwing motion, in order to throw the virtual dart using the accelerometer. However, it doesn't look like you actually have that feature. I think that would be a pretty neat thing to add. Of course, not being able to see the screen when you're throwing would be something of an issue, and you might want to look into what liability you could be facing for basically encouraging people to almost throw their phones... Even so, I think it'd be a very novel and Wii-like way to play the game.

---
Tags: game-design
---


# Question
Title: Using a Viewpoint and a RenderTarget2D in XNA
I started using a RenderTarget2D in my project so I could use shaders more effectively, but when I went full screen I found that my center viewpoint was no longer centered. It still resizes correctly, but for widescreen monitors it should center the viewport to the middle of the screen. And that was working correctly until I started using a RenderTarget2D. Now, the viewport is being displayed on the left side of the screen instead.

```
        if (graphics.IsFullScreen)
        {
            // set the viewport to the whole screen
            GraphicsDevice.Viewport = new Viewport
            {
                X = 0,
                Y = 0,
                Width = GraphicsDevice.PresentationParameters.BackBufferWidth,
                Height = GraphicsDevice.PresentationParameters.BackBufferHeight,
                MinDepth = 0,
                MaxDepth = 1
            };

            // clear whole screen to black
            GraphicsDevice.Clear(Color.Black);

            // figure out the largest area that fits in this resolution at the desired aspect ratio
            int width = GraphicsDevice.PresentationParameters.BackBufferWidth;
            int height = (int)(width / targetAspectRatio + .5f);
            if (height > GraphicsDevice.PresentationParameters.BackBufferHeight)
            {
                height = GraphicsDevice.PresentationParameters.BackBufferHeight;
                width = (int)(height * targetAspectRatio + .5f);
            }
            scale = (float)width / (float)Game1.ScreenWidth;
            // set up the new viewport centered in the backbuffer
            GraphicsDevice.Viewport = new Viewport
            {
                X = GraphicsDevice.PresentationParameters.BackBufferWidth / 2 - width / 2,
                Y = GraphicsDevice.PresentationParameters.BackBufferHeight / 2 - height / 2,
                Width = width,
                Height = height,
                MinDepth = 0,
                MaxDepth = 1
            };

            GraphicsDevice.Clear(Color.Black);
        }

        GraphicsDevice.SetRenderTarget(rendertarget);
        spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);

....Draw All of the Game....

        GraphicsDevice.SetRenderTarget(null);
        spriteBatch.End();
        spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, brightnessShader, Matrix.CreateScale(scale));
        spriteBatch.Draw(rendertarget, Vector2.Zero, Color.White);

```

Any ideas as to why the viewport is displayed at the left instead of the center?

# Answer
I ended up moving the viewport code to right after I set the render target to null and it worked beautifully without me having to modify the position of every single thing I'd drawn so far.
> 1 votes

# Answer
Pretty sure every time you change rendertargets the Viewport defaults back to the client. Anyways I wouldn't alter the viewport at all. You don't show us how you create your rendertarget but if its the same size as the viewport you were using just draw everything to the rendertarget and then replace.

```
spriteBatch.Draw(rendertarget, Vector2.Zero, Color.White);

```

with

```
spriteBatch.Draw(rendertarget, new Vector2((ScreenWidth - RenderWidth) / 2, 0), Color.White);

```

or you can use the source and destination matrices and not have to worry about scaling.
> 1 votes

---
Tags: xna
---


# Question
Title: Textures do not render on ATI graphics cards?
I'm rendering textured quads to an orthographic view in XNA through hardware instancing. On Nvidia graphics cards, this all works, tested on 3 machines. On ATI cards, it doesn't work at all, tested on 2 machines.

How come? Culling perhaps?

My orthographic view is set up like this:

```
Matrix projection = Matrix.CreateOrthographicOffCenter(0, graphicsDevice.Viewport.Width, -graphicsDevice.Viewport.Height, 0, 0, 1);

```

And my elements are rendered with the Z-coordinate 0.

**Edit:**

I just figured out something weird.

If I do not call this spritebatch code above doing my textured quad rendering code, then it won't work on Nvidia cards either. Could that be due to culling information or something like that?

```
        Batch.Instance.SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone);
        ...
        spriteBatch.End();

```

**Edit 2:**

Here's the full code for my instancing call.

```
    public void DrawTextures()
    {

        Batch.Instance.SpriteBatch.Begin(SpriteSortMode.Texture, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone, textureEffect);
        while (texturesToDraw.Count > 0)
        {
            TextureJob texture = texturesToDraw.Dequeue();
            spriteBatch.Draw(texture.Texture, texture.DestinationRectangle, texture.TintingColor);
        }
        spriteBatch.End();

#if !NOTEXTUREINSTANCING
        // no work to do
        if (positionInBufferTextured > 0)
        {

            device.BlendState = BlendState.Opaque;

            textureEffect.CurrentTechnique = textureEffect.Techniques["Technique1"];
            textureEffect.Parameters["Texture"].SetValue(darkTexture);
            textureEffect.CurrentTechnique.Passes[0].Apply();

            if ((textureInstanceBuffer == null) ||
                (positionInBufferTextured > textureInstanceBuffer.VertexCount))
            {
                if (textureInstanceBuffer != null)
                    textureInstanceBuffer.Dispose();

                textureInstanceBuffer = new DynamicVertexBuffer(device, texturedInstanceVertexDeclaration, positionInBufferTextured, BufferUsage.WriteOnly);
            }

            if (positionInBufferTextured > 0)
            {
                textureInstanceBuffer.SetData(texturedInstances, 0, positionInBufferTextured, SetDataOptions.Discard);
            }

            device.Indices = textureIndexBuffer;
            device.SetVertexBuffers(textureGeometryBuffer, new VertexBufferBinding(textureInstanceBuffer, 0, 1));

            device.DrawInstancedPrimitives(PrimitiveType.TriangleStrip, 0, 0, textureGeometryBuffer.VertexCount, 0, 2, positionInBufferTextured);

            // now that we've drawn, it's ok to reset positionInBuffer back to zero,
            // and write over any vertices that may have been set previously.
            positionInBufferTextured = 0;

        }
#endif
    }

```

# Answer
`SpriteSortMode.Immediate` is setting the device state "immediately" you call `Begin`. You shouldn't use it unless you actually want the `Immediate` behaviour. Using `Immediate` turns off batching (slower) but allows you to directly manipulate states on the `GraphicsDevice` object between sprites. (Prefer `Deferred` instead.)

You are setting `DepthStencilState.Default` (depth reads and writes enabled), which is the default for `GraphicsDevice`, but the default for `SpriteBatch` is actually `None` (depth reads and writes disabled).

Now here's the bit where I have to **guess** (because you haven't provided enough code, and this is a tricky hardware-dependent problem):

You've set your near plane to `0`, and you're drawing things at a Z-position of 0, which is right on the border of the valid region of the depth buffer. I would hazard a guess it has something to do with this. You might try moving your near plane back, moving your Z-position forward, and/or disabling the depth buffer.
> 4 votes

# Answer
Be careful, NVIDIA silently upgrades your incorrect set pixelshader/vertexshader versions. ATI will fail. Use the DirectX SDK to check for warnings. My pixelshader was set to 3.0 and my (spriteBatch) Vertex shader to 2.0...
> 2 votes

---
Tags: xna, hlsl
---


# Question
Title: What is involved in creating a real-time multiplayer platformer game?
I'm creating a platformer game that has a "co-operative" feature which I'd like to work over networks / the internet.

Now I've read up on network game programming including articles like What every programmer needs to know about game networking and so I understand the difference between techniques like Peer-to-Peer lockstep and Server-Client prediction architectures:

* I've concluded that for any real-time game that is going to be played over the internet, Peer-to-Peer lockstep simply isn't an option.
* I'm also concerned that even for a platformer a simple client-server architecture (without some sort of client prediction) would result in degraded gameplay due to the delay between action and reaction caused by a round-trip to a server. (Having said that I want to eliminate the need for a central server, and so only one of the players, the client, will actually experience this lag).

This leaves client prediction, but even for a simple game like a platformer this still sounds pretty complex.

How would I go about creating a working client predictive system for a multiplayer platformer game?

# Answer
> 6 votes
I don't think that half of your code base will turn into network code if you decide to implement a feature such as this.

In my opinion, the most simple way to do this, is to setup a "central" server (even if that means that one player "hosts" the game and then connects to his own server) that accepts all user input as fast as possible, and sends it back out to each client.

On the client, you implement this no differently than if you were doing a co-op game for two players locally, except you read P1 from keyboard, and P2 from network.

You'll need to have the server send out a full game state every once in a while, and both clients can either snap to the new authoratitave state from the server, or they can slide into the new state (over a few seconds). Unless you have horrible packet loss or tons of clients per server, this approach should suffice for the situation you outline.

# Answer
> 2 votes
I have a fully functionnal mMORPG style game with client prediction (the game is far from finished but it runs 'OK') and I have something along 40.000 lines of code for the server and the double for the client (add same amount for tools etc.). The Prediction is probably not more than a few hundred lines (if even that) and the whole network part a couple of thousand lines but not more than say 5.000 (it depends a bit where you draw the line).

Fuzzy question fuzzy answer ;-)

# Answer
> 2 votes
A significant proportion of the networking code can be independent of the game that you're playing. Because of that, and because you're new to networking, the first thing I'd suggest you do is to find libraries that will do that work for you. RakNet for example.

One thing you will want in your game code is the ability to handle multiple different game states, which you can use for interpolation and prediction. That's fairly simple to design in up front, but can be a significant quantity of work if you're modifying an existing single player game.

Also note that if you want to get strangers to play a peer to peer game over the internet, you will probably need at least one server somewhere that handles the lobby / matchmaking.

---
Tags: networking, multiplayer, platformer
---


# Question
Title: How to design player attribute updates in persistent game worlds?
Take a game with a persistent state that can continue even when players are not online. E.g. your player enters into a fight and loses some health points which are replenished 1 point every five minutes. There are a number of ways to implement this "update stuff even when the player isn't logged in" scenario. E.g. run a server-side background worker that performs scheduled updates (e.g. +1 to health) once a second.

Or, forgo the background worker and store the next-update-time for an attribute (e.g. health) in your Player model. Then, anywhere you fetch/get a Player, perform any attribute updates lazily. That is, if the next-update-time is earlier than the fetch/get time (e.g. "now"), update the attribute and then return the updated Player.

My goal is to make this system as simple as possible.

What are your thoughts? How would you do this?

# Answer
> 4 votes
If these things are occurring while the player is offline, then simply use calculations to determine what the values should be when they're logged on next (and do the same whenever another player in the game accesses their publicly viewable statistics that would be effected by this).

For example, a player sustains a sickness that can be half-way recovered after 5 minutes, and fully recovered after 10 minutes, regardless of whether they're logged in -- you could implement this with a special table in the database for tracking such updates, and then when various players or login events occur, the calculation is run accordingly:

* 08:28 Player sustains sickness, record is added to the tracking table which includes the relevant calculation details and player ID number
* 08:29 Player logs out
* 08:31 Another player views this player's statistics, and the game checks the table to determine that the player is sick because not even 5 minutes have passed
* 08:35 Another player views this player's statistics, and the game checks the table to determine that the player is half-recovered from their sickness because more than 5 minutes have passed, but 10 minutes have not yet
* 08:37 Player logs back in and the game calculates the statistics, and the player can see that their character is 50% sick (and will be recovered after approximately one more minute)
* 08:38 Player's client software automatically queries the server and the server determines that a full recovery occurred, sends the update to the client and deletes the record from the table

There are other ways to do this as well, and this probably isn't the most efficient solution (I look forward to seeing other answers with different solutions). Of course, if the player logged in after 10 minutes, or another player checked the player after 10 minutes, then the server would automatically take care of deleting that record and none of the players would know that there was any sickness.

One advantage is that there is less work for the server due to being player-event driven rather than cron-tick driven (which could result in more work for the server).

# Answer
> 2 votes
These updates typically take place in "game time," not real time. Slipstream the code to update statistics and effects that should change over time right before the sequence that inserts the character into the world. At that point you know how long it has been since the character logged out and now when he's about to log back into the game environment, your calculations can be done using that delta instead of a cron like tick.

The only time you would need to tick when someone is offline is if their character were left active in the game world, in which case the normal game logic would handle all the updates so nothing special needs doing.

---
Tags: rpg, world-design
---


# Question
Title: How to form a concave shape out of convex shapes?
I'm trying to get around the rule of only being able to form convex shapes in the SFML C++ library.

> To do this I'm planning on testing given vertices, and if concave, splitting the vertices into groups, testing each groups' concaveness, and repeating until a full set of convex shapes results that look just like the original shape when put together

What I would like to know is...

* **What the equation for testing a shapes concaveness is: what is it and how does it work?**
* **How would I split up the vertices of the concave shape so in the end the shape is formed out of as few convex shapes as possible?**
* **Whats the best practice for achieving my goal?**

Thanks!

# Answer
Rather than a top down approach, try a bottom up one. I.e., grow convex regions out of sets of vertices (starting with a tetrahedron), then grow these by adding adjacent (in terms of triangle connectivity). When you cannot find another vertex to add, find an unadded tetrahedron (easily started from 2 adjacent triangles with non-reflexive angle on the interior shared edge), and repeat.

Detecting if adding the vertex will maintain convexity is relatively easy (note that you are not just adding to a convex hull - effectively, if adding a vertex to the convex hull you are growing results in one of the surface vertices becoming interior to the hull, it is not a valid point to add). The tricky bit is determining which vertices should be added to minimize the number of convex volumes. In practice this is a hard optimization problem, and heuristics are likely good enough to get a "good enough" decomposition.

Incidentally, if you want to read up more on this, the term you want to search for is "3D Convex Decomposition". FYI, a BSP tree will also give you a convex decomposition of a non-convex object, but it will be far from minimal.
> 0 votes

---
Tags: mathematics, graphics, box2d, sfml
---


# Question
Title: Which 3D Authoring Application to Decide for
I have read a lot individual information about three key 3D Graphics Authoring Applications: **Softimage, 3DS Max, Maya**.

To me, it looks like each of them has its own way to accomplish the same goal, which brings me to the question, **is any of them better than the other ones?**

In other words, if am free to decide which one of the three tools to use as my primary graphics development tool (for games graphics, web, commercials, animations..) and if I depend to nobody, **which application** should I decide for? **What criteria should I evaluate** those three applications in accordance to?

As I have read a lot about Softimage, which is so far the most attractive to me because of its user interface and ICE, I came to question: **Is the future of Softimage bright?** is it not going to be merged or vanished over time? Lastly I checked, Autodesk offered Softimage as part of its key two packages: Maya, Max. It was not offered as standalone and competitive package to Max and Maya anymore.

# Answer
> 4 votes
*The Pragmatic Programmer* devoted a section to this:

> We think it is better to know one editor very well, and to use it for all editing tasks.... Without a single editor, you face a potential modern day Babel of confusion... Choose an editor, know it thoroughly, and use it for all editing tasks. If you use a single editor (or set of keybindings) across all \[model\] editing activities, you don't have to stop and think to accomplish \[geometry\] manipulation: the necessary keystrokes will be a reflex. The editor will be an extension of your hand; the keys will sing as they slice their way through the \[models\] and thought. That's our goal.

Actually they were talking about text editors, but it's not different. All the tools you have named are fine tools - none of them are the Windows Notepad of 3D asset creation (nor is Blender).

Pick one, use it, learn it well enough you don't need to think about it. One day you'll probably find yourself in another program, and you won't use it as well, but that's OK - time spent not mastering ten editors is time spent learning the task at hand, and that will pay off far more when your next job is using the eleventh one anyway.

# Answer
> 1 votes
This question doesn't have any direct answer. It depends a lot on other parameters.

You can google to sort out something, but other then that, either this is gonna be a huge comparison among features(which wont make any sense at all) or a straight forward answer to pick x or y. But, in short, XSI's ICE is very tempting for VFX but other then that 3ds Max and Maya is vastly superior. 3ds dominated gaming industry and Maya the movie industry. *From my experience its easy to do easy things in 3ds max and easier to do hard things in maya.*

You can even try out Blender & see if it fits your need. Houdini offers procedural modeling solution. Which is awesome too!

Another thing is that you are trying to find out the best solution for almost everything, but differnt situation demands different solutions. For gaming blender can provide an excellent all around solution. The latest installment of Duke Nukem, the developers are using blender(don't know on how extent) for rigging & animation.

The basic functionality remains same across all the applications.For modeling you need some basic tool like extrusion, beveling, splitting edges etc etc. All this features are available in all tools. It's just a matter to get used to then. Unless you become a high level user the output wont different for using different software.

Its all vague, but if you ask which one is best to start with, I would say Maya. You can switch to anything later on, depending on what the time and situation demands.

# Answer
> 1 votes
It depends on what kind of assets you want to create. Some 3D packages excel at low-poly modelling, while others provide sculpting and other sophisticated high-poly modelling tools.

It's quite common that artists use different modelling packages for different jobs. ZBrush is widely used to sculpt high-poly models that are then imported in other 3D packages (where you bake the high-poly model to a normal-map of a low-poly model). Some people like Wings3D because it has excellent (low) polygon modelling tools.

Blender has very good UV unwrapping features. I already heard of people that take their models to blender just for unwrapping.

So what I'm trying to say is: People tend to use the right tool for the job. They don't pick a modelling package and stick with it. If you're new to 3D modelling, then basically any 3d-modelling software will do to get you started. All the packages you mentioned provide excellent modelling and animation tools, where Maya and 3DS Max are probably the most popular packages.

The underlying basics of 3D modelling packages are all the same so it doesn't matter that much which package you decide to choose. Once you know one software, it shouldn't be that hard to learn another tool (much like learning a new programming language isn't that hard if you have experience in another programming language).

---
Tags: 3d, animation, 3dsmax, maya
---


title: Java or Flash for MMO Game?

text:
# Question
Title: Java or Flash for MMO Game?
I hope this question hasn't been asked before.

I'm thinking of creating an MMO game, perhaps for Facebook. I've investigated the options of using Java or Flash/Flex. But I'm still not sure which to go with. Does anyone have any advice on which language to use?

Which language has more open source or free tools/libraries? Which one has better performance for a database transaction-heavy game?

A few notes: I'm intending it to be a 2D, isometric game with cartoony graphics. Nothing necessarily intense on the graphics front. I've heard of JMonkeyEngine, but that's 3D. The only other thing I've found that's good for 2D is LWJGL. One thing I don't like about Flash/Flex is that it can't create a direct connection to the database. Is that also true for a Java-based game?

Essentially, I would like to know how to approach the development of an MMO. What tools/libraries should I use? I'm hoping that there are open source/free options.

Thank you for your time.

# Answer
You'll have to write client- and a server-software for an MMO. Your client won't establish a direct database connection (which would be *way* too risky), but rather communicate with the server-software that handles all DB transactions.

You can program your backend in Java, Rails, Python, PHP or similar. For the client I suggest you use Flash. It is ubiquitous (except iOS devices, but Java won't run there either) and you'll find lots of libraries/tools for Flash. You can also develop Flash games using free software. See this question.

If your client is going to be rather simple, you could also look into a pure HTML/JavaScript client.
> 4 votes

---
Tags: java, flash, mmo
---


title: How to manage shaders?

text:
# Question
Title: How to manage shaders?
I've done some shader programming some time ago but only simple stuff. I'm especially interested in how do you manage shaders? Do you just write one of each kind, or do you need more of them? If so, how exactly do you split and managed them?

Also I've recently read that all the transformation matrix operations I used in OpenGL(glPushMatrix, etc) are now deprecated and you need to manage your own matrices.Is that something you do in a vertex shader and how would I go about doing it correctly?

Suggestions for books about this topic will be highly appreciated.

Thank you.

# Answer
I'll answer your second querstion first: both vertex and pixel shaders can treat part of (4 constants) their assigned constant memory (basically an array of 4D vectors, which can also be interpreted as integers or booleans with more modern shader versions) as a matrix in row-major format. It's up to you to upload the "right" transformation matrix for a job. So for example, for a standard 3D transform you'd upload this: Matrix mFullTransform = mProj * mView * mWorld, to transform a rigid vertex from object space. Get a basic (may just as well be dated) book about programming the post-fixed-pipe graphics pipeline. I have an old nVidia book called the CG tutorial lying around that covers this quite well.

As for multiple shaders, depending on your application design it might be a good idea to split up vertex and pixel shaders. From there on a common challenge is to write a shader that transforms/renders geometry based on a material. The material likely imposes small differences in the shader code. Now you can choose to upload these parameters (for a modern model) to constants and branch at runtime. This is not a very speedy approach though so it might be a good idea to take a different one. An often used strategy is to 'build' (or splice) and compile shaders at compiletime (or, in some simpler or runtime cases on initialization) and pair them up with the corresponding (material) data. Tailor your solution to your needs: for simple games and graphics demos it usually suffices to write all the shaders by hand and perhaps take a small hit left or right for a runtime parameter or 2.

Anyway hope it helps, been out of this game for a while.

\[EDIT\] Look at the first comment as well, has a good point about an important difference between D3D (which I mistakenly assumed, force of habit..) and OpenGL.
> 3 votes

---
Tags: opengl, shaders, resource-management
---


title: 2d top-down map: normalisation or not?

text:
# Question
Title: 2d top-down map: normalisation or not?
I am an absolute beginner with game programming, should this question be poorly formulated, be aware it was not sloppiness by my side, but lack of game programming experience.

The game I am planning to code will use a top-down 2D map as "world". The world might be larger than the window (the window can zoom in or out) and the vehicles can be located at any point of the world (= it's not a tiled map, the space is "continuous").

To clarify with an example: if the world is a terrain of 1000x1000 metres, a vehicle could be at location (327.31, 720.4) metres.

My question is: **what is the most convenient way to represent the world internally?** I could think to these possibilities:

* do nothing and **use metres** as if I were working with the physical object,
* **normalise to pixels** defining the world size as the number of pixels for representing 1000 metres at maximum zoom,
* **normalise to 1** defining the word as a square of size 1

...but I am sure there might be some other ones / some of mine could make no sense. It's just that being my first game I don't have a clear pictures of the problems ahead of me, and I would like some guidance in making a reasonably correct initial choice.

Thank you for your time.

# Answer
I agree with using a real-world value (meters, feet, etc.) as your basis for distance. The problem with your other two suggestions is that they are both variables. Working with a world size of `1` will cause all of your arithmetic to be floating-point between -1 and 1, which may lead to more floating-point errors. Also, should you ever decide to make variable world sizes ("Large" worlds for longer games, etc.) you will introduce many problems to your code. Likewise, if you use pixels, even at a maximum/minimum zoom level, you will run into confusion as well as problems should you decide to increase or decrease zoom levels.
> 10 votes

# Answer
Of the three options you suggested, using meters will probably be best. As you create other data, dealing with length in meters will make you life much easier. Among other reasons, you may decide to change your world size, or different levels may need different sized maps.

You may also decide to use feet (or possibly inches). Part of this decision may depend on what middleware packages you use - some physics engines prefer one unit type or another (though it's almost always configurable). For the most part, you can just choose a unit and go with it.
> 7 votes

# Answer
Normalize to '1' is really not the way to go (what if you have a world not square? or several worlds with different size...).

Using pixels as ... NEVER Mix up gameplay and graphic measures!! Don't lock yourself up so you can't change the graphics without having to change the code.

So meters (feet or whatever measurement you like the most) is the way to go. You will feel much better to code your missile launcher to move at 50 km/h than 0.00076 units/second...
> 5 votes

---
Tags: 2d, maps
---


# Question
Title: Line at edge of transparent texture on XNA mesh
I have a mesh that is computer generated with a texture on top of it with transparancy on one side. The SamplerState is set to LinearWrap because I would like the texture to wrap. The problem I have is that this transparent edge has some weird aliasing. This does not occur when I set the SamplerState to LinearClamp.

I found that when letting the U coordinate go from 0.1 to 0.9 this does not happen. Probably on the transparent side it interpolates U coordinate 1 with U coordinate 0.

What could be the solution to prevent aside from not letting the U coordinate go all the way to 1?

# Answer
Create a new SamplerState of your own and set it like this:

```
mySampler.Filter = TextureFilter.Linear;
mySampler.AddressU = TextureAddressMode.Clamp;
mySampler.AddressV = TextureAddressMode.Wrap;
mySampler.AddressW = TextureAddressMode.Wrap;

```

The V coordinate will be wrapped (since you want horizontal repeat) and the U will be clamped.
> 6 votes

---
Tags: xna, textures, transparency, antialiasing
---


# Question
Title: How can you meaningfully market test microtransactions?
For a number of reasons I have chosen to use Microtransactions to monetize my current project. However, like all make or break features I am concerned about how they are received in-game.

Microtransactions seem to present a unique problem in my mind though. I believe that just giving people currency will skew my results, and it wouldn't actually represent how people feel about how things are priced (in the same way that I am more apt to waste money when I didn't have to earn it).

With that in mind, how can I effectively, and meaningfully market test the implementation of Microtransactions in my game?

# Answer
> 6 votes
You'll have to do some market research, dirty words I know in tech circles, but there it is =)

Have you personally, or your design staff anyways, ever played any free to play titles? And by played I mean having spent a couple months on both sides of the "I paid for some things" divide.

**Find** all the FtoP games you can, not limited to your genre but not ignoring your focus either. **Categorize** how they implement the microtrans in the game, how do the designs work, when you **read their forums** (and fan forums) feel stressful or simply involved in the game? Lots of work ahead of you since there are a lot of FtoP games lately.

Find the other free to play games that started life as traditional, monthly subscriptions and changed. There are some high profile success stories out there.

See if you can find information on conversion rates; I've heard that maybe 10% of players will buy *something* while maybe 1% will over-buy and be your backbone. I am *not* a reliable resource for information, however =)

In the end, without a living ecosystem (ie. a launched title) to experiment with you can't effectively test *your* game but you can research how similar titles have fared and maybe discover why, and adapt that information to your own use.

---
Tags: game-design, testing, microtransactions
---


# Question
Title: What is the best mechanism for controlling a character in a 2D Android game?
Im developing a 2D RPG for Android where the character can move up, down, left, and right like in top-down RPGs like Pokemon.

What is the best input mechanism to use to control the character? A virtual joystick seems a bit to complicated for just straight movement.

# Answer
> 3 votes
The most responsive and familiar mechanism is the physical D-Pad on the Xperia Play device; you could follow Mojang's example and target your game at that device. This would additionally provide support to any devices with a physical D-Pad, since the Play's D-Pad uses the standard D-Pad key codes. This includes trackballs like the one found on the Nexus One; for those devices you may want to provide an option to keep walking in the last direction they pressed until told otherwise.

If your goal is broad device compatibility, the equivalent would be a virtual joystick, since all Android devices are required to have a touch screen before they can install apps from the Android Market. If you're relying on a touch screen, however, I recommend you move the character to whichever point the user touches on the screen.

As Zoot mentioned in the comments, there is another option you may wish to support: bluetooth gamepads such as the iControlPad. That gamepad in particular maps the D-Pad controls to WASD key inputs, though others may vary.

---
Tags: 2d, android, rpg, movement, control
---


# Question
Title: Where can I publish my Windows Indie game?
I've just finished an XNA game for the Windows Phone 7 and XBLIG. At the moment, the game is a 'lite' version, so is free, but the next version will have a small price-tag.

I also did a Windows version. Where's the best place to publish it?

# Answer
Post it everywhere you can; Steam, Desura... Head over to the Business section of http://tigsource.com forum. Send to this page too to also publish it on cover. Send also to http://indiegames.com/index.html

It is a good way to advertise.
> 11 votes

# Answer
The most thriving indie marketplace on Windows right now has got to be Steam. Not every successful indie game is there, bu most indie games do very well there compared to independently.
> 6 votes

# Answer
I think steam is your best bet; I've seen a lot of XNA games doing fairly well there lately. Read through the following page and if you're still interested, send Valve an email.

http://www.steampowered.com/steamworks/FAQ.php
> 2 votes

# Answer
Obviously Steam is the best place to be, if you can get in.

If not, take a look at IndieCity - http://www.indiecity.com \- another distribution platform for indie PC games, which hasn't yet launched but seems to be getting closer - maybe you can get your game on it in time for it's launch?
> 2 votes

---
Tags: xna, xbox360
---


# Question
Title: Can flixel or a similar engine be used with reddwarf server?
I like the sgs/projectdarkstar or now known as reddwarf server for a back end game server. However I am looking for a good front end, preferably 2D. I was thinking of something such as flixel. I know there is an AS3 library available for reddwarf, so I am hoping someone already has connected up flixel or a similar engine? Or if you have a recommendation for another easy client side engine that will connect to reddwarf?

# Answer
Flixel and your client engine don't 'connect' to each other. They are both libraries YOU have to integrate into your flash.

Think of flixel more like a box of pencil crayons, and your client library like a phone cord. Alone they don't do anything. It's how you use them that makes your game what it it.

Also judging by the rough bounds of this question I might recommend you scale down your first project of this nature. Server/Client interactions are a hefty challenge on their own, without any graphics ever being involved. But before you ever try that, make a full game, start to finish with flixel, *then* add new technologies. If you can't be patient enough to take the time to do that, you will have serious trouble ever finishing this project.
> 1 votes

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


title: Game Classes design

text:
# Question
Title: Game Classes design
I'm trying to create a simple 2D sprite game. The problem I'm having now is how to design my game. I was thinking of using a Sprite class that will be my base class for all the different types of Sprites I will use. The problem in my design is wheter to let every Inherited Sprite class draw itself, having a Draw method or should I have a centralized DrawEngine that handles all the drawing for me. Which method is the preferred one to use?

If I use the DrawEngine method how do I go about sending Textures to it? All the different Sprites will have different textures and the DrawEngine doesn't really know about the sprites. Could someone please help me out how to solve this problem how to handle textures in a DrawEngine class?

# Answer
> 8 votes
The very first question you need to ask yourself about the "class" Sprite is this: what is a sprite?

Is it the image? Is it an entity in the game world that has gameplay properties on it? Is it a collision box? Etc.

If a "Sprite" represents only the position and orientation of an image (possibly selected from a sheet of images), then you don't really have different "kinds" of sprites. You have a Sprite, which can be rendered. There's no need for inheritance here. You can have sprites that have different images and so forth, but that's just the data stored in the sprite.

Let's call the class for this "SpriteImage."

If a "Sprite" is fundamentally a gameplay entity, then this entity would *contain* an object that represents how it gets drawn. You don't draw entities; entities don't draw themselves either. Entities contain one or more objects that they will give a position and orientation to, which represents how the visual representation of the entity is presented.

Let us call this class "SpriteEntity". This class might *contain* one or more of the SpriteImage objects, and it would be responsible for providing the position and orientation of these objects. It would also handle animating them (selecting which image to show). However, it would not draw them; the drawing of these images would be handled by an object that also holds a reference to these SpriteImage objects. Here, you should employ smart pointer usage; SpiteEntitys would contain shared\_ptr's to their SpriteImages, while the SpriteImageDrawer would have a list of weak\_ptrs to every SpriteImage that is created.

Of course, this is just one way of structuring things. You can choose your own, but the separation of "entity" from "image" is a very good idea. For example, the above architecture would allow some "SpriteEntity" objects to have *no* visual representation at all. This is useful to create collision areas (since entities would have collision areas, even if you don't see them), so that you can detect when another entity touches that area and do something based on that. It would also allow some "SpriteEntity" objects to have *multiple* sprites, possibly hierarchically layered. This would be for doing things like drawing weapons on characters, etc.

# Answer
> 2 votes
It really depends on a couple of factors such as

* how much functionality you want to put into your sprite class
* how complicated it is to actually draw the sprites on screen
* how many sprites you're drawing at once using the same texture

Letting each Sprite draw itself is nice from an object oriented design perspective but then it's hard to optimize your rendering code. In general it's always good to put rendering/drawing code in a separate module (such as the DrawEngine you proposed). So if you're drawing lots and lots of Sprites with the same texture you can batch draw those together.

Concerning the actual implementation, you could create a special drawing interface which the Sprite class implements, that supplies the DrawEngine with everything needed to draw the Sprite (bounding box, texture, alpha, etc.). You then hold a list (or scene graph for more complex games) with all your Sprites and let the DrawEngine iterate over it, either drawing the Sprites immediately or sort them by texture and draw afterwards.

# Answer
> 2 votes
Currently the way I'm implementing the process of drawing is to have a Sprite class that is just an image, where it needs to be drawn (incl. rotation and Z-depth), alpha levels, and which frame to draw. Then I have a separate SpriteHandler class that contains all of the methods as static methods that perform all of the actual drawing. The user can then either use the methods individually or register it with the handler and it will sort by z-depth and draw in the correct order.

---
Tags: 2d, architecture, rendering
---


# Question
Title: Mods for Minecraft Server - how does it work?
Minecraft server comes as a single jar. How are mods developed? How do they interact with the original jar? What is there under the hood?

What technologies are involved there? I'm mostly a C++/Python guy, but I'd like to learn something about mods development.

# Answer
A JAR is simply a ZIP file, containing the various class files and other metadata used - it's a completely standardized format.

ZIP files can be extracted, and the class files can be edited as necessary for the modification. The modified files are then added back into the archive, which makes the server use the modified files instead of the original ones.

Technically, Minecraft mods are really "hacked" versions of the original code: the actual binary class files have to be modified to let the game know about the new stuff; there's no official mod support yet (although Notch has stated that they'll work on it during Beta).

Of course, that isn't a very nice way of doing things if you actively design for mods. Instead, you would design some sort of plugin architecture which allows custom code to be run where appropriate. Exactly how you would go about this depends on what you want your mods to be able to do - e.g., if security is a concern, you probably want to design the mod interface to use some sort of scripting, so you can restrict mods from doing all sorts of things to the user's computer.
> 11 votes

# Answer
Single player mods are hacked versions of the original code. Multiplayer mods are different right now. They almost all use hey0's server wrapper, which links in the minecraft\_server.jar (or whatever the term is in Java land) but defines its own functions classes, overloads some of the core functions, and runs its own main()

Hey0 provides a mod API. See
> 6 votes

# Answer
For your information, Mojang will be releasing a "Mod API" some time in the near future (during beta, so before its official release which will be around november 2011).

In fact, it will be the full source code, as mentioned on Notch's blog

http://notch.tumblr.com/post/4955141617/the-plan-for-mods

but for now, you have to "decompile" the jars, to see a partially obfuscated code and recompiling it for later use/debugging.

To do this, I highly recommend Minecraft Coder's Pack http://mcp.ocean-labs.de/index.php/MCP\_Releases

there is a couple of modding tutorials on the forums too, like this one : http://www.minecraftforum.net/topic/96862-creating-mods-modding-tutorials-21511/
> 1 votes

---
Tags: java, modding, minecraft-modding
---


# Question
Title: How to make name of your trademark-game-clone findable
I know you can't copyright gameplay, so I can clone a succesful game. I'm not completely sure if you can completely take over all the rules (when rephrasing them to go around copyrights on text).

But my biggest problem is, how do I make my game findable for users? Should I use a name that looks like the original trademarked game, like e.g. iRisk (for iOS), or R7sk (for WP7) ? Should I go for another game that grasps what it's about (e.g. Conquer the world) and add 'RISK' (or a similar reference) to the game description?

*Edit on Tetrad's comment:* People are free to propose an alternative solution to name the game as implied in my question. I'd even like to alternative solutions of close to the border trademark names, to prevent any problems on that part.

Cloning games and certainly puzzles (like sudoku) has been used a lot and sometimes it's even good to bring it to a new platform (mobile, ...). I'm mainly looking for a way to make the game **findable** for users, because as for now it's not available yet on the 2-3 platforms I'm looking to develop it for. I want users on these platforms to be able to play the game, without having problems with the trademarked name.

# Answer
As always, legal questions should be addressed to intellectual property attorneys in your local area, and not to random folks on the Internet.

This stuff is important. And it varies from state to state and country to country. Even if the people providing answers on the Internet are experts and are giving correct answers for their own location (which is unlikely), their answers do not necessarily apply to you in yours.

If you get this wrong, you face substantial fines and/or jail time. I strongly advise you to either ask a qualified attorney in your area, or else not to play the "how closely can I rip off someone else's works without stepping over the line" game.

It's simply too risky to even consider taking answers from random anonymous strangers on the Internet for this type of matter.
> 3 votes

# Answer
* see this GamePlay Patent, for first question.
* regarding your second question, Pro Evolution Soccer used this same approach that you mentioned. They didn't have the license to use real names of the Football players. So, they changed them slightly.

For example, *Wim Suurbier* is named *Slowbear* in the Classic Netherlands squad.

So, when a commercial title can do that, you wouldn't have any problem doing that either.
> 1 votes

# Answer
If you are sure of your legal footing, and you want your game to be recognizable, then be blatant in your name. Be in your face about what you are doing.

"Counter Clone: If you like CS, you'll like my game better because it's cheaper and I added rocket launchers!"

"MineClone. Get it? Great. Then get it 'cause it's only $1!"

Not only is this "in your face" open and honest, it tells people exactly what they are going to get from your game. Additionally, you will get press just for being so brazenly obvious. That kind of press can be gold for you, as all it takes is one well placed mention in the NYT to get you a lot of eyeballs on your game.

This approach is like being the Duke Nukem Forever of clones. You're not apologizing for what you are. Hell no, you're proud of it, so say it!

Good luck.
> 0 votes

---
Tags: legal
---


# Question
Title: Is Unity3D (free) sufficient to publish to the Mac App Store?
Is Unity3 (free) + dev account sufficient to get an app on the MAC app store? Or, do I require the pro version?

# Answer
> 7 votes
It should be fine. You'll have to do some command line stuff to get it to sign appropriately regardless of pro or free, and that's all documented here: http://technology.blurst.com/unity-games-and-mac-app-store/

# Answer
> -4 votes
I think you need Unity3D Pro + iOS to actually compile any game for iOS

---
Tags: unity
---


# Question
Title: Casting a shadow over a whole scene with GLSL in 2D?
I'm making a (non-isometric) side scrolling 2D game and I want each fragment that I draw to cast a small drop shadow when it is near another object. What sort of algorithms are used in fragment shaders to cast shadows in 2D games?

# Answer
you need to provide much better information to get a very useful answer, you are vague. (what does near mean in 2d? that doesn'f fit with how shadows work at all...)

the lazy, easy solution is to not use shaders at all - draw everything twice, a first pass with flat colour offset down and to the left/right - this is the drop shadow, then render everything normally over the top. you can combine this with a blur (using a shader if you must) in between the two passes for a bit of polish, and unless you are on a mobile platform or pushing lots of triangles the expense should be fine.

if you have depth to your scene (you really need to clarify this, it is easily the most important point) then you might want to use depth testing to not cast shadows onto "nothing". If that is not quite enough then maybe vary brightness and blur depending on the depth of the existing scene fragments vs. the current object fragments being drawn. varying shadows based on depth is fairly complicated, and you typically need to resolve and sample a render target to do this, as well as writing some vertex + fragment program - in which case you might as well just use shadow mapping (which is well researched and documented - you should Google that if you decide it is appropriate)
> 2 votes

# Answer
It really depends on how your game graphics are set up and how you want this effect to work. In 2d "shadows" aren't really uniquely defined so you need to decide what sort of behaviour you want from them.

If you're looking for something like drop-shadows in Photoshop then you first need the relative depths of objects to be defined somehow, either individually or in bins (i.e foreground, middle, background).

To actually cast a drop-shadow a simple method would be to render all onscreen shadow-casting objects to a texture w/ a simple shader that outputs opaque black (for solid pixels) or transparent/0-alpha (for empty pixels); then use this "shadow buffer" w/ multiply blending on the shadow-receiving objects -- you can offset the shadow buffer to make the drop-shadow fall e.g to the left and down.

If you want objects to both cast and receive shadows (i.e object-by-object shadows instead of layer-by-layer) you could try a similar approach where you iterate over all objects from front to back, rendering the object w/ the current shadow-buffer applied and then adding the object to the shadow buffer. This would involve a lot of texture binding/unbinding though (assuming you have hundreds of objects) so I'm not sure if it's a good solution.
> 0 votes

---
Tags: c++, 2d, shaders, glsl, shadows
---


# Question
Title: Turning a sprite such that it rotates in the direction that's most efficient
I have a sprite that moves from waypoint to waypoint. It turns to face its velocity vector, but not instantly (there's a rotation speed).

The problem I'm having is, from one direction to another, the sprite will often turn in wild, unnecessary ways instead of appearing like you might expect a car to appear (turn such that the minimum delta in angle occurs).

Right now I'm using the following formula to calculate the rotation float for the current velocity:

```
MathHelper.PiOver2 + -Math.Atan2(anotherVector.Y - vector.Y, -(anotherVector.X - vector.X));

```

And then I lerp the current rotation by the new rotation by the rotation speed (10f):

```
rotation = MathHelper.Lerp(rotation, targetRotation, 10f * (float)gameTime.ElapsedGameTime.TotalSeconds);

```

But unfortunately, it's causing the sprite to spin in wild directions before reaching the correct angle. Any suggestions?

# Answer
> 6 votes
This is due to the angle wrapping. For example, lerping from 1 degree to 359 degrees is not what is wanted, instead the equivalent lerp from 1 degree to -1 degree should be used. If the angles are in the same range, then adding or subtracting 2\*pi to the target will work, e.g.

```
if (targetRotation > rotation+Pi)
    targetRotation -= 2*Pi;
else if (targetRotation < rotation-Pi)
    targetRotation += 2*Pi;

```

It's important that the angles are in the same range. The \[-pi,pi\] range returned by atan2 is the most standard, so I'd recommend using that for all angles if possible. Whatever range is chosen, wrap the rotation back into that range after lerping.

---
Tags: xna, c#, sprites, rotation
---


# Question
Title: AI control for a ship with physics model
I am looking for ideas how to implement following in 2D space. Unfortunately I don't know much about AI/path finding/autonomous control yet.

Let's say this ship can move freely but it has mass and momentum. Also, external forces might affect it (explosions etc). The player can set a target for the ship at any time and it should reach that spot and stop.

Without physics this would be simple, just point to the direction and go. But how to deal with existing momentum and then stopping on the spot? I don't want to modify ship's placement directly.

edit: Just to make clear, the physics related math of the ship itself is not the problem.

# Answer
> 15 votes
Have a look at steering behaviors. Especially seek and arrival might be interesting for your needs. These behaviors will also work when some other influences like an explosion changes the ships position temporarily.

# Answer
> 5 votes
It's not an easy problem to get exactly right. You have two choices, although the specifics of each solution vary:

A mathmatical solution. If your physics system is simple enough you can create the closed form for your motion and calculate when you need to start applying a braking force to stop at a point. If your braking force is a constant and you have no air resistence, this should decompose to a quadratic.

An emperical solution. You can use a hand-tuned PID controller or actually record the braking distances for your ship in your physics system: in a testbed, brake the ship from max speed down to a stop, recording the distance travelled and speed every small timestep. Store the resultant distance/speed graph in a data directory.

At run time, reconstruct the graph and plug in your current speed and target speed to get out a distance. At this distance from your target point you need to be at full brake.

The advantage of this approach is that you can use it to brake exactly to any speed. The disadvantage is that if your brakes have to ramp on or off, you'll never be exactly on the curve.

# Answer
> 1 votes
As said before this situation is perfect for steering behaviours, but I'd just like to extend on it slightly. The Arrive behaviour would be perfect for this scenario. You might also want to take obstacles into account as well. You can make use of the Obstacle Avoidance behaviour here as well.

Unfortunately, http://www.red3d.com/cwr/steer/ doesn't provide source code for the behaviours. However, Programming Game AI by Example does and explains the behaviours in easy to understand chunks. If you can't get the book you can always get the source code here: http://www.wordware.com/files/ai/

Furthermore, if you want to extend your movement to include pathfinding, you can have a pathfinder class that calculates the path (perhaps as a collection of 2D vectors) and use the Path Follow steering behaviour to add that into the mix too.

The source code I've linked to also provides three different methods of combining these steering behaviours together as well.

Hope that helps.

# Answer
> 1 votes
Steering towards a position is not too difficult, but I personally struggled for a while with the problem of steering towards a position and reaching it at a specific speed, or following a path with speed constraints.

I solved the problem using a Hermite curve. Set p0 and m0 to the position and velocities of your ship, p1 and m1 to your target position and speeds. This assumes you want the ship to follow one second after the target. Compute the second derivative of p(0), that will give you the acceleration to apply to your ship.

Here is the code for the second derivative (in F#, I hope you can adapt it to your language of choice; sq() computes the square, single quotes not interpreted as quotes but as characters, they are part of the identifier):

```
    let h'' t =
        let h00'' t = 12.0 * t - 6.0
        let h10'' t = 6.0 * t - 4.0
        let h01'' t = -12.0 * t + 6.0
        let h11'' t = 6.0 * t - 2.0

        let t = (t - t0) / diff_t

        (sq (1.0 / diff_t)) *
        ((h00'' t * p0) +
         (h10'' t * diff_t * v0) +
         (h01'' t * p1) +
         (h11'' t * diff_t * v1))

```

Note that if your ship is subject to external forces (e.g. gravity from planets), you will have to account for that when calculating the thrust from the acceleration.

# Answer
> 0 votes
Found this recently - steering behaviors in JavaScript & Processing:

http://shawnldoria.com/works/steering-behaviors.html

# Answer
> -3 votes
I think your ship should have parameters like: position and velocity.

Velocity is in each frame sum of all forces (like gravity, explosions, user input etc) and can also have some kind of damp.

Position is calculated from last position plus velocity * time\_step.

However, with this it can be difficult to implement stopping on target.

---
Tags: physics, ai, path-finding, movement
---


# Question
Title: Is it possible to batch draw sprites that use different textures without using an atlas?
I've implemented a sprite batch class that uses a sampler array so that I can select a texture to use based on the gl\_PrimitiveID. The idea was to be able to draw sprites that use different textures in a single draw call. I've managed to get it to compile the shaders and run, but the sampler indexing part does not seem to work, although I did not get any OpenGL error. I've done a bit of research and found out that it doesn't seem possible to index into a sampler array with an index that is not a compile-time constant or uniform variable.

Am I doing something wrong or is building a texture atlas the only way to draw sprites that use different textures at once?

# Answer
> 3 votes
You can use multitexturing to do this - because you can bind a different texture to each texture unit you can then use your uniforms to select which one. The limit is hardware dependent, but usually no less than 8 and very occasionally as small as 4.

http://www.opengl.org/resources/code/samples/sig99/advanced99/notes/node60.html

Multitexturing predates shaders so support is fairly global.

This does mean not using a sampler array and instead using your own logic - "just" unroll a binary search, or even better use some bit magic.

It is however fastest to use one texture for all calls and for it to be an atlas of some kind.

# Answer
> 2 votes
> Am I doing something wrong or is building a texture atlas the only way to draw sprites that use different textures at once?

It is not necessarily the "only" way, but it is the *best* way. It is the way that works on anything, from the lowly Voodoo 1 all the way to the Radeon 6990. It doesn't require shaders (though they can be useful with this).

All it requires is a bit of pre-processing on your end to put all of the images in one large image. This is hardly an onerous burden.

That being said, how many sprites do you intend to draw per frame? If it's less than a couple of hundred, an atlas isn't that important to your rendering performance. Texture atlases matter most for things like particle systems and fonts, because you're drawing lots of them.

# Answer
> 0 votes
The MSDN documentation for HLSL seems to think that you can only do this in Direct3D 10. Of course, OpenGL and Direct3D don't always exactly match their functionality, but it's usually pretty close, since the same cards target OpenGL and DirectX.

It could be that it is legal- just not for a target of the version that you are using.

---
Tags: opengl, textures, glsl
---


# Question
Title: Should the engine for an eventual web-based game start as a web-service?
I've recently decided to start writing an engine for a card game. I'm not a big "cards" player, but a friend introduced me to the game (it's a spin on the game Danish), and I fell in love.

I want to develop the game in 3 segments:

1. The basic engine, handles cards/decks/gamestate, etc.
2. A user interface (in the form of a mobile/desktop web app.)
3. An artificial intelligence with various strategies/difficulties, etc.

These are very distinct projects, in my mind... and I'm struggling with seeing how they'll all fit together in the long run. At first, I don't even want to be able to "play" the game using the engine. The engine will primarily be tested by its unit tests. Play testing won't start until a client exists. So there's something of a client-server relationship here.

The engine is a very large piece of the puzzle. What I'd like to know is: how would you go about developing the "public API" for this engine?

I was thinking the engine could be a very basic web service, that returns its state via queries to a RESTful API, but I'm worried that developing the engine itself as a web app may lead to poor programming decisions. (For instance, if I chose an MVC micro-framework, well, this API wouldn't really have views... it's just returning serialized objects via JSON, or something to that effect. Is it bad to use MVC for a service like this? )

My other idea was that the engine would just be a console app, and I would later write a bridge of some kind to pipe data between it and the web-app. (The bridge could really be anything. I mean, the web server and the game engine could both idle in an IRC server and share their state in channels.)

What approach would you take (develop as a web service, or develop as a standalone app and bridge it later), and why?

Thanks, Robbie.

EDIT: So I guess this belongs in Game Development. To clarify, I'm going to write a card game engine. I'm trying to figure out the best way to expose the engine's API so it can be integrated *in the future* with a web client, and an AI client.

I didn't even have an account here, so howdy :)

# Answer
The web service route is probably the best and most scalable.

I also see absolutely **NO** problem using an MVC framework to return JSON (asp.net mvc is great at this). If your controllers only return JSON at first that is fine, you can unit test without any views. When you are ready to add your game interface, you can add views. If their plain html/css or flash/silverlight, it doesn't matter because, as you've stated, you have already built the underlying engine.

I'm not sure what your development or hosting environments look like but I would not over engineer it. A simple set of php files that return JSON may be all you need. I am not familiar with the game you're building, so I am not sure how complex it will be.

In my opinion, if you're new to game development, and you're going it yourself, I highly recommend that you get something that is playable as soon as possible, because it will help keep you motivated to complete the game and polish it to a good level.
> 5 votes

# Answer
A view is an entity that registers to a model to be notified when changes occour.

If your model resides to a web server, you have a problem because the HTTP does not implement an explicit way to let the server start a communication. You can use websocket to handle this but you will sacrifice some of your "RESTfulness"... I think that a good solution can be to let your web URL to identify a model and use the HTTP server push to let your views to be notified when needed.

Lets say you have a running game in

```
/games/cd073ac6-c37e-431f-9a5e-7b61bfacf9be/

```

you can use the URL

```
/games/cd073ac6-c37e-431f-9a5e-7b61bfacf9be/playCard?id=3&place=stack

```

to modify the model and

```
/games/cd073ac6-c37e-431f-9a5e-7b61bfacf9be/notify

```

to wait for notifications.

Notify will wait - for some amount of time - to get news by the model: if something happends a message will be sent (what data are changed or what kind of event happends or whatever).

The client can do a long ajax request to /games/cd073ac6-c37e-431f-9a5e-7b61bfacf9be/notify and register a notification callback that will both update the view and repost the next notify request.

If games/cd073ac6-c37e-431f-9a5e-7b61bfacf9be/notify timeouts on the client, a new request is done, if it timeouts on the server, the allocated resources are freed.

You can build a quite generic notification system on your server and a notification library on your clients so you can build up a consistent MVC over a transparent notification layer.

If you are looking for a technology, you can consider to build your game engine upon the Couchdb server. Couchdb is a non-relational REST DBMS that uses HTTP as protocol and JSON as document format. It can also PUT and GET binary or HTML files as attachments so it is possible to write a full webApp using only the DBMS (a couchApp).

There exist a javascript library that make it possible to react to database updates among other things. A couchdbApp is simply a database so you can copy an application to another server by syncronization: your clients can copy your app to their local server and then playing over a offlined LAN.
> 1 votes

---
Tags: architecture, web, client-server, planning
---


# Question
Title: Bitmap to a custom coordinate pair when touched
I am completely lost and needed some help. I have a ontouchListener for a bitmap and know how to check if the touch was within the boundaries of the bitmap. But say I want the center of the image to be at a custom coordinate like \[0,0\] and the entire image to be in the range of \[-319...319\] and \[-239...239\] . Does any one have any thoughts on how to best implement an eventX and eventY to a custom coordinate pair?

# Answer
> 1 votes
If you need just to take into account a displacement, you simply have to know where your origin is in standard coordinate system (the one the listener returns).

Say that your (0,0) is at (150,322), this means that when you get P = (x,y) you can get P' = (x-150,y-322) to get the point in your coordinate system.

To make it clean try to transform your origin P = (x=150,y=322) =\> P' = (150-150,322-322) = (0,0); lets take a point that is 100 pixel on the right to your origin: P = (250,322) =\> P' = (250-150,322-322) = (100,0), that is what you need.

If your coordinate system is not simply a displacement of the one your system provides (rotation, shear, scale involved), a change of homogeneus coordinate system is required.

**EDIT:**

As pointed out, the requirement is that the coordinate system has to produce the same range coordinate even if the view area resizes.

I assume that the aspect-ratio of the view and the scaled coordinate system is not an issue.

Let say that the dimensions of your view area size is W x H and your system gives you values for x and y so x: \[0,W\] and y: \[0,H\]; we want that the transformed value to be x: \[-w,w\] and y: \[-h,h\]. Let start by computing the transformed x:

x' = x/W =\> x : \[0,1\];

x' = x/W · (2w) =\> x : \[0,2w\];

x' = ( x/W · (2w) ) - w =\> x' : \[-w,w\] and hence

y' = (y/H · (2h) ) - h =\> y' : \[-h,h\].

You have to know - or ask the view for - W and H and set w = 319 and h = 239.

---
Tags: android
---


# Question
Title: Whats the most efficient method for controlling entities?
I'm creating a tower defense game and I'm having logistical issues trying to figure out how to best have all of the enitites do their apporiate task.

I have considered just constantly looping through a list of all the game entities calling a onAction() method, but I'm not sure if that is effective.

I have also considered having each entity be a thread, but when I am dealing with hundreds of entities, some of which don't need thread time, I'm back to square one.

Can I get any suggestions on a solid approach? Am I on the correct track with my first idea?

Thanks for any help ~Aedon

# Answer
> 9 votes
First of all, using a thread per entity (talking about OS threads here, not language specific cheap co-routines) is insane. A thread is expensive, for example it needs a stack which by default uses 1MB of address space. Thread switching is expensive costing thousands of CPU cycles.

I wouldn't use multi threading at all in your main game logic. It adds *a lot* of complexity. First write it single-threaded and later perhaps multi-thread some hot-spots like path-finding and collision detection.

> Tim Sweeney\[The Unreal Engine guy\]: For multithreading optimizations, we're focusing on physics, animation updates, the renderer's scene traversal loop, sound updates, and content streaming. We are **not attempting to multithread systems that are highly sequential and object-oriented, such as the gameplay**.
>
> Implementing a multithreaded system **requires two to three times the development and testing effort** of implementing a comparable non-multithreaded system
>
> From http://www.anandtech.com/show/1645/3

---

Just iterating over all entities is usually fast enough. You'll have a few thousand of them, so iterating over them by itself takes fractions of a millisecond. Benchmark first before worrying about such stuff.

When I wrote an RTS (which from the technical side is not that far from a tower defense game) the top performance killers with a naive implementation were:

* Collision detection, you need to use some spatial partitioning to make this fast.
* Pathing can be very difficult, depends on your demands and the topology of your level
* Finding opponents in firing-range. Once again needs spatial partitioning. And in my experience separate partitions for different factions are a must(you have many friendly units in firing range typically, but few hostiles). Locking on to a target, once you found one, until it get out of range/dies saves a lot too, since you don't need to search again all the time.

The cost of simple looping and local entity behavior typically pales compared to these few expensive tasks.

# Answer
> 6 votes
First steps: write something and **measure the performance**.

If the performance is not good enough then use the measurements you made to drive your optimization.

Naively threading hundreds of entities is probably not the way to go. A scheduling queue might be, but only if you determined by your measurements above that the big OnAction() loop is tying you down.

So yes you are on the right track with the action loop and that is, in fact, how many titles work.

# Answer
> 2 votes
Most games use scripts for controlling much of their entities' logic. That should tell you how much the game's overall performance will be coming from the basic entity loop (ie: precious little).

The entity loop is not the low-hanging fruit of performance. Use whatever makes making your game easier.

# Answer
> 1 votes
> I'm creating a tower defense game

If this is your game you shouldn't have performance problems with entity updates unless something else is wrong. If you have a performance problem and you've **measured** it to be coming from your entity loop you need to cull the number of entities being updated, either by simply having less or by looking at architectural/algorithmic optimisation e.g. if projectiles are entities make them something else, and make them in a nice, flat, array or ring buffer you can iterate over quickly instead of instances scattered in memory, inline their updates, or if they must be function calls make sure they aren't virtual

> I have considered just constantly looping through a list of all the game entities calling a onAction() method, but I'm not sure if that is effective.

This is how all of the fastest and best solutions I have seen work fundamentally. There is lots of micro optimisation and threading potential for this approach, but even without it all its fine - you can ship a AAA FPS with something like this at its core, iterating over instances scattered in memory by using virtual calls and have 1000s of entities just fine (in C/C++ at least).

> I have also considered having each entity be a thread

That is fairly insane - stay single threaded until you are comfortable and experienced enough with threading to not have such ideas

# Answer
> 0 votes
This came up on Stack Overflow a while back.

---
Tags: entity-system, logic
---


title: Organizing platformer game into classes

text:
# Question
Title: Organizing platformer game into classes
I'm making a platformer game and I'm having some trouble wrapping my head around how to organize my classes. I'm wondering what the best way to have everything interact would be without passing parameters all over the place. I've heard of MVC, but does this apply? Should I look into it more?

Thanks in advance

# Answer
There are no special rules for a platformer vs. any other game in this respect. I suggest that you just start making your game. You'll make a lot of mistakes, but hacking the game together while staying conscious of what one can do better is how I learned to create clean, organized code.

Here are some patterns that you should be aware of when making your game: http://gameprogrammingpatterns.com/introduction.html

Two or three games from now, you'll be applying the principles that I linked to, and you'll be organizing your code better as a result of seeing how it all ties together from experience.

Another important point is that many people developing a game in their spare time do not finish it. Hacking your platformer together at the cost of a less than perfect code base might actually allow you to create a finished product. Then you can clean up the engine in version 2.0.
> 3 votes

---
Tags: architecture, software-engineering, platformer
---


title: Underlying skills and knowledge

text:
# Question
Title: Underlying skills and knowledge
I am trying to expand my knowledge on gaming and programming and I was wondering what underlying skills people think they one should learn to be a great programmer, or developer. What are some important patterns or practices that you use frequently?

Thanks.

# Answer
> 3 votes
**Make games**

I can't stress it enough. Make anything. It could be Tetris, it could be SuperMario. Then add feature to it. Try to implement different algorithms(pathfinding, al etc etc) into your game. Find out how things are turning out. Which is the bad part of your code. Then refactor it. You will face some problems. Then look for solution. You will find things like design patterns. Learn it. Then make another game. Use the experience that you have learnt from your past game. When you have some experience you can even start working with some open source game development teams(like 0 AD). If you feel its too hard for you, then go for modding. Don't stand still, do anything related to game development. It could be modeling, texturing, rigging, animation, programming. You don't have to be a jack of all trades. Just have a basic understand on every aspect.

The bottom line is try to have a reasonable amount of experience on different aspects on game development. At the end of the day a people pick one from many that suits himself. But, you need to know them first.

# Answer
> 3 votes
Of course it depends on the particular position you are aiming for, there is no general answer, but here is my list about most important skills for programmers as I see it (I should mention my area is Console & Performance):

1. **Debugging** \- analyzing crash dumps and learn the language of your CPU and how it communicates with other components of the system
2. **Profiling** \- not much to say here, here you really learn about your code and that there are so many wrong assumtions about code that can become critical
3. **Shipping Mentality** \- think in "Shipping Solutions" rather than "Great and perfect Designs"

All those sound simple and ovbious, but really mastering them is an art and pretty rare.

# Answer
> 2 votes
**Problem solving** is probably one of the most important skills to programmer, as is the ability **think and reason critically**. Both of these are skills that apply to all levels of developer and can almost always be improved upon.

The ability to work through and understand the root cause of a particular bug or other issue, and the ability to understand and reason about the implications of potential changes to the program in order to fix the bug is a key aspect of a good programmer's job.

# Answer
> 0 votes
There is no generic answer, as today, a developper usually is specialised on one or other field, may it be AI, low level optimisation, rendering engine, physic engine, shaders, ... So basically, everything depends on what you know already, and what your specialty is (are?).

After that, there are lots of best practices depending on which language / game engine you're working with, and each company will also have there own standards in terms of skills and / or methods.

To improve your skills, I suggest working with multiple fields mentionned above, and work with open source game engines to see how they are made.

# Answer
> 0 votes
As a web developer forming a game development group I have found that one of the biggest aspects which set the field apart from normal programming is how game development is not just coding. In the development process you need to work with coders, projects managers, writers, musicians, animation experts, and the like, all throughout the process to get your thing out.

That said, for what I'm doing now, typically I'll focus exclusively on coding specific parts of the game that I'm familiar with (such as an interface) while another developer will handle the physics -- because since game development is so complex, it's more of a team effort where it's best to stick to something that interests you rather than being a jack of all trades.

---
Tags: education
---


# Question
Title: Can I reuse the name of an old arcade game?
I've done an indie remake of an old arcade game from 1980.

Can I use its name? I thought copyright expired after 25 years but I could be wrong, hence this question.

# Answer
> 16 votes
You're asking about more than the *name*, if you re-made the actual *game* (rhyme unintended). In the US, copyright has been constantly extended, and is now the author's life + 75 years - so no, the game is still copyrighted.

And the name is covered by *trademark*, not copyright (which also would not have expired - I don't think it does expire). If your name is *identical*, then yes it's a trademark violation. If it's *similar*, then it depends - some companies are more litigious than others (See Edge Games, who sued anyone that had a game with the word *edge* in it, like "Mirror's Edge" by EA.

Activision had to license the name Civilization from Avalon Hill, maker of a board game with the same name.

# Answer
> 3 votes
The only safe way to do this is to buy or license the rights for the game from the current owner. This can be expensive and time-consuming. The rights holder might ask for a fixed fee plus royalties, and as an indie game developer, that's likely going to be more than you expect to earn.

On the other hand, if the original game was produced by a very small company or an individual, you can probably contact them and get permission to do the remake pretty easily.

If you do a remake of a classic game, the rights holder can sue you and has a reasonable chance of winning. Tetris Holding is renowned for this.

If you just use the name in an unrelated game whose name is not currently being used for any commercial purpose, the rights holder can still sue you to bankruptcy.

It's slightly safer if you are not selling the game, I think. More likely to avoid notice, and the potential fines might be smaller. But you're only safe if you get an agreement with the rights holder.

---
Tags: legal, copyright
---


title: How do particle systems work?

text:
# Question
Title: How do particle systems work?
I want to implement a particle system in my game, but I've never programmed a particle system and don't know where to start.

I only want to display pixels (`GL_POINT`s) with different sizes in different places, something like Terraria or Minecraft when you hit a block, without the texture. Just a dead simple example.

Google search results for this tend to be very complex, or don't explain the concepts, or are written in hard-to-read C without OOP…

I'm using Java and OpenGL.

# Answer
I think the key phrase is particle **system** so most of the samples out in the wild are going to be more complex than you would think a simple demonstration should be. OOP doesn't really enter into the low level part of particle systems and C is very straight forward to convert to other languages so I wouldn't worry about that.

The trick to particles is that you want to display a LOT and as fast as possible, that colors the kinds of code you'll see since everything is optimized in one way or another.

In its simplest form a particle system for a quick splash effect would have the following elements:

1. A manager both to keep track of all your systems and to give global control to all effects.
2. Array of "points" where each has position, velocity, life time, display size.
3. A function to create that array with a starting position and (probably) random velocities and life times.
4. A function to run a simulation on that array, this probably takes a delta time since the last simulation call.
5. A function to take the positions and display sizes and display then in OpenGL.
6. And lastly, an overseer to stop that system from playing when all the points are dead.

Organizing the functions can be OOP at the higher levels as long as the inner loops keep to themselves in the quest for speed. Super lax pseudo code sequence below, leaving out a lot of detail and mixing and matching straight C concepts with a cheesy OOP thrown in but I hope it makes sense. The class design for this would be an entire other discussion =)

For your example, you hit a brick at world location (10,20,30). You then call the manager and ask it to start up a new points particle system at that location. The manager then asks the PointsClass to create itself at position (10,20,30). The class allocates and randomizes the life times, etc... The manager then calls all the active particle systems it controls each frame with a simulation call. Later that frame it asks the PointsClass to draw itself into a GL context. Loop until done.
> 9 votes

---
Tags: opengl, java, architecture, particles
---


# Question
Title: Where do I store strings? What's an efficient way of loading them?
I'm making a top-down RPG for iPhone. I'm using tilemaps (CCTMXTileMap) and the cocos2d-iphone engine.

I've made a class that can handle loading maps and NPCs onto the screen, a class that handles input, and, a class that is supposed to display dialog. The dialog class takes a single string, or an array, and displays it onscreen inside a neat dialog box, hiding the controls until the user taps on the screen, when it cycles to the next message, or if it's the last/only message, hides the dialog.

My NPCs are currently stored in Core Data. Their strings will need to be updated based on quest progress. Also, there are other bits of dialog, like signposts and other messages.

So, where do I put my game's textual content? I don't think Core Data is the right place, because of three reasons:

1. If my strings are stored in Core Data, I will probably have a harder time translating them.
2. If my strings are in Core Data, that only leaves me with strings for NPCs (which would be attached to the NPCs in Core Data). Where does that leave everything else?
3. If I leave my strings in Core Data, it's a bit heavy on the loading operations, no?

Given all of this background information, where do I put my strings and dialog in my game?

---

**tl;dr**

What's an efficient way to store strings for an iOS game so that they can be easily accessed, translated and referenced at various parts of the game?

# Answer
Unless you have some particular requirements for portability, formatting, or speed, Apple's standard string resources should be fine.
> 7 votes

# Answer
I would create an external file or files for all strings. then load it once when the program begins into some global object. in run time every object that needs to display some string will have to ask that global object for the proper string. you can use keys for every string or you can use an array. if you don't like the global object idea, you can load every string whenever you need directly from file, but that may cause low fps when loading dialogues. using this approach you can easily change the language whenever you want, just you have to start reading from a different file.
> 0 votes

---
Tags: iphone, cocos2d-iphone, data-structure
---


title: 3ds Max - How to Cross Edges

text:
# Question
Title: 3ds Max - How to Cross Edges
I' relatively new to modeling, so this might be a simple question to answer. I'm having trouble trying to cross edges. I've placed a screenshot below of what I'm trying to accomplish (made in SketchUp). It's a box with to edges along the diagonals of each face. Is there a simple way to do this in 3ds Max? Thanks in advance.

# Answer
Two ways I can think of, neither of which are particularly clever but will do it:

1. Apply the 'Subdivide' modifier and just increase/reduce the 'Size' parameter (very roughly) until your polys have been split correctly.
2. Convert to Editable Poly (or the selected faces will be triangles), select the face(s) and use 'Insert Vertex' to split them.

These of course work well for creating the box you describe but perhaps you could explain what the end goal of crossing the edges is (e.g. add detail?) as there might be a better solution for a more complex model.
> 1 votes

# Answer
Here is how I would do it, this method takes approximately 1 minute when you know the steps by memory.

1. Create a box using keyboard entry.
2. Set the X,Y,Z all to 0.
3. Set the width, length, height all to 2.
4. Set the length, width, height segments all to 1.
5. Turn on the move snap toggle. (The icon in the top bar with the number "3" and a magnet on it.)
6. Now convert the box to editable poly and go to polygon selection mode.
7. Click "Insert vertex" in the modify pane with polygon selection mode set.
8. Now using the top/left/front orthographic views, click to add a vertex at the center of each cube face (which is easy because you have snapping turned on).

The desired edges are automatically added when you add these vertices.
> 0 votes

---
Tags: 3dsmax
---


title: Procedural star field generator

text:
# Question
Title: Procedural star field generator
Is anyone aware of any code to procedurally generate star fields?

Ideally I'd like it to be physics-based so I can have realistic planets and moons. Best would be in C++, open source, and workable with Ogre3d.

I'm not afraid of coding something from a university paper if there's nothing available.

# Answer
I believe that producing a star field (long range) and planets and moons ("short range") should be two different layers. As for the star field, I've found this to be useful for my game: http://alexcpeterson.com/spacescape. That can take care of your long range, static star field. It's written in C++ and open source.

As for the "short range" stuff. I've found some sources for solar system simulators, but from my shallow glance, they don't look very generic, if you're wanting to create a different solar system than our own. I put the links at the end.

In reality this shouldn't be too difficult of a task to create a generic system for planets. Study up on your Kepler and you can get some good estimations of planet positions. http://en.wikipedia.org/wiki/Kepler%27s\_laws\_of\_planetary\_motion. Probably just stick with simple non-eccentric orbits to start :)

Here's some links for solar system simulators I found.

http://astro.berkeley.edu/~dperley/programs/ssms.html

http://code.google.com/p/solar-system-cpp/
> 10 votes

---
Tags: c++, ogre, procedural-generation
---


# Question
Title: How can I incorporate physics into a procedurally generated world from a geometry shader?
Essentially I want to remove the need for generating coherent noise from the CPU to the GPU. From there, I also want to generate the terrain for a three dimensional world using this noise as densities in voxel points. After this, I want to take those densities and polygonize (generate vertices) them representing the world's terrain.

This is fine and all. But, I also want to dynamically deform the world in real-time. Once I get to this point, I have a problem trying to get the vertices back to the CPU to do things like collision detection and all of the game computations that I want to involve on the CPU and not the GPU.

So the question is: how can I get a subset of the vertices back to the CPU for dealing with collisions among other things?

And one more question: is there an easy way to take a set of vertices and generate indices from them on the GPU?

I'm confused as well as to what kinds of shaders I should be using for these different things. I hear of people using a pixel shader for gathering densities and then using a geometry shader for dealing with the terrain generation from the vertices and then somehow incorporating a vertex shader to do the dynamic deformations.

I'm using C# 4.0, .NET 4.0, and XNA Game Studio 4.0.

# Answer
Since XNA doesn't support geometry shaders, I'll answer it as if you were using DX 10. You essentially have three options.

**Geometry shaders** Geometry shaders can actually modify and add vertices to a vertex buffer. You could read this back into the CPU. I haven't looked into it, but it's definitely possible.

**Just use the CPU** Secondly, why don't you just calculate it on the CPU? The fact that it runs on the GPU in shaders suggests that your deformation algorithm is localizable, i.e. you can easily generate just the relavent parts for your collision checking.

For example, I made a sailing game a while ago. The ocean used the vertex and geometry shaders to deform the water with waves. I used the same algorithm calculated on the CPU on just a few points under the boat for the boat's movement in the waves. I'm sure you could do something similar for your voxel map.

**Pixel shaders** The last option, you mentioned this in your question too: generate the densities in the pixel shader and write it to a 3D texture. You can access this from the CPU and the shaders fairly harmlessly. The pixel shader is perfect for this task, but this method has a lot of overhead. Rendering the volume texture, as well as sampling from in in the vertex and geo. shaders, and having to read the texture onto the CPU.

I don't know the specifics of your project, but I would always use the CPU for this. By all means calculate the densities on the shaders as well, but stick to using the graphics card for rendering.
> 3 votes

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


title: Mesh to world vector translation

text:
# Question
Title: Mesh to world vector translation
Suppose I have a world defined in typical OpenGL coords.. then the up vector defined for this space is (0,1,0).

Now, if I load a model that is defined with (0,0,1) as its up vector, what are the matrix operation(s) that I need to carry out here to arrive at the 4x4 transformation matrix for the model?

Many thanks.

# Answer
> 2 votes
The up vector being different basically means that the model is in a different space, where Z inwards represents that what you regard as Y up. To compensate for this, rotate the model vertices 90 degrees over the X-axis (in the right direction). Draw the axes on paper, it'll be clear in a jiffy.

Think of it as this: if you were to rotate the up vector 0, 0, 1 -- how would you do it to make it 0, 1, 0?

Use Google for all about building rotation matrices. Or use glRotate() for a quick test.

---
Tags: 3d, matrix, vector
---


title: create a simple tilemap programatically

text:
# Question
Title: create a simple tilemap programatically
i am working on a tile roguelike i got some of the basics working using this tutorial http://www.raywenderlich.com/1163/how-to-make-a-tile-based-game-with-cocos2d

but i want to be able to create a map programatically instead of using the tiled editor

just add a NSArray of sprites/tiles to my CCLayer derived class or something, or should i make use of the CCTMXTiledMap class?

can anyone gimme some hints about how to do this? or know of a tutorial or sample code somewhere?

thanks a lot

# Answer
> 4 votes
You only need a CCTMXLayer, there is no need for any thing else. but you'll need to initialize it properly. for that reason I suggest you use some TMX file generated with Tiled editor and then load it into your program. there is a GID value for each tile in TMXLayer and you can easily edit it. by changing that value the tile for that position will change. if you set a tile's GID to 0 TMXLayer will automatically delete tile at that position otherwise, it'll change(or create) the ccSprite instance at that position.

---
Tags: iphone, tiles, cocos2d-iphone, roguelikes
---


# Question
Title: How can I make an movieclip move in a circular path with GTween?
How can I make an movieclip move in a circular path with GTween? it's straightforward to have something move with various easing effects in a line or a curve, but I would need a complete circular path.

# Answer
> 2 votes
Most animation libraries aren't made to support that sort of thing. I wrote a small library for exactly this problem; it's built upon a foundation of spatial path-based animation, rather than generic property interpolation.

You can check it out here: http://blog.generalrelativity.org/actionscript-30/grape-animation-library/

If you're required to use GTween, and it supports curves (probably bezier), you can approximate a circle with multiple curves: http://www.tinaja.com/glib/ellipse4.pdf

---
Tags: actionscript-3
---