# Question
Title: How can I make grid tiles/plane transparent
I have made a grid using multiple planes. Now I want to place a image on this grid so that user cant see the grid I have made and I ll have access of all points of the image using grid.

The problem is I am unable to place image on it, it shows me grid that I made before. I have tried Materials/Shader -\> Transparent/Diffuse, but some blocks are still visible. How can I make grid tiles transparent ?

# Answer
> 1 votes
Without an image of the problem it is fairly hard to answer, but if it is a rendering problem then add the image render after the grid render or just skip rendering the grid.

# Answer
> 1 votes
As Gajet mentioned, you can simply remove or disable the MeshRenderer Component off all the tiles/planes you not want to show. (They still exist for collisions, but will not be visible.)

---
Tags: unity, tower-defense, grid
---


title: How can I embed music in my XNA .exe?

text:
# Question
Title: How can I embed music in my XNA .exe?
I'm trying to embed music in my XNA game's .exe (with resources) but compiling them as a sound effect stores the music in uncompressed form, which results in a 16 MB .exe.

I can compress my music with wma, and compile it as a song, which unfortunately (in my case) leaves the music as a plain .wma file.

Basically, I want a single standalone .exe, with my content stored as resources. If I could compile a wma song to a single .xnb content file, I could embed that file. I don't know how to do that without uncompressing the music. It might be possible to keep the wma file separate and store it in the resources, but I haven't figured out how to get the .xnb content file to work with it.

In order of preference:

* Can I compile a wma to a xnb without decompressing it?
* Can I store the wma in the exe resources and load it into a song?
* Is there any other way to decrease the size of an exe with embedded music?

EDIT: The comments mentioned using XACT. This seems like a good solution. I have another question. Since the XACT sounds are not loaded with Content.Load, it will not automatically look in the application resources (I have Content set up to do so). Is there a way to load XACT sounds from resources? If not, I will accept having to load content from separate files.

# Answer
> 2 votes
> Can I compile a wma to a xnb without decompressing it?

Don't think so. Unless there is drop down option in the properties when you select is in the content project.

> Can I store the wma in the exe resources and load it into a song?

Yes this project creates .xnbs from what ever during runtime. I'm sure you could do something similar or even use the project directly feeding in your file instead of the selection box.

> Is there any other way to decrease the size of an exe with embedded music?

Assuming the library is small enough to be worth the gain you could use a generic compression algorithm to compress the .xnb then uncompress it at load time.

---
Tags: xna, xna-4.0, music, assets
---


# Question
Title: Easiest, most fun way to program 2D games? Flash? XNA? Some other engine?
this is a post detailing my search for the most enjoyable way for a hobbyist game programmer to sweeten his free time with making a game.

**My requirements:** I looked at Flash first, I made a couple of small games but I'm doubtful of the performance. I would like to make a fairly large strategy game, with several hundred units fighting simultaneously, explosions and animations included. Also zoomable maps. I saw that Adobe has a new 3D API for Flash, but I don't know if that improves 2D performance aswell, I couldn't find anything related to that question on their MAX10 sessions. Would you say that Flash is a good technology for making large 2D games easily? I really like Actionscript, and I love how easy everything is in Flash. There are several engines available which make it even easier.

I just do this for fun, and it would be even better if there were proper animation/particle editors available and if the engine I were to use, would be available for multiple platforms. (so more people can play my game once finished). I'd like to have it available on many mobile platforms aswell. (because I love touch input for some reason)

I do know the XNA framework pretty well, but there are no good engines available for it, and it will only run on Windows, which is a huge turn off. Even bigger is, that you need to install the XNA redistributable each time you want to give the game to someone. If I use XNA, I would have to make all the tools myself, and I'd probably have to make them with WPF. (I'd love to make tools with Adobe AIR, but unfortunately the API's for image manipulation etc. are far worse in Flash, than they are in XNA/WPF.) Now, I'm aware that I could make my own engine that supports each of those platforms, but quite frankly, that would be too much work plowing through APIs. After all, I want to make a game, not an engine.

So the question becomes: **Is there maybe a cross platform (free or free to develop?) engine available that I could use for 2D development?** I prefer: C#, Actionscript. I don't mind using c++ if the toolset is above average, but I highly doubt that there is something out there like that. Please prove me wrong :) So summary: I'd like to use Flash, but I don't know if it scales well enough. I'm not a scripter, I want some real APIs that I can work with inside a proper IDE.

Just for information, I looked at several alternatives, I'm actually looking for a long time already. You'd help me a lot to make a decision finally.

* Feature-wise the Flatredball engine would be ideal. But I tried their tools, and quite frankly, they are horrible. Absolutely unusable, I'd need to make my own for sure. I didn't look at their API, but if their tools are so bad, I'm not inclined to look further.
* Unity3D. This one is quite nice, but I really *don't need 3D*, and it is quite ...a lot of work to learn. I also don't like that it is so expensive to use for different platforms and that I can only code for it through scripting. You have to buy each platform separately. The editor usability is average, the product overall is good enough for most purposes, but learning it myself would be overkill.
* Shiva 3D. It looks good enough, but again: I don't really need 3D. The editor usability is a little worse than Unity3D in my opinion and it wasn't clear to me how to start programming. I think it requires C++ for coding, so that's a negative too. I want to have fun, and c# is fun ;)
* SDL. Quite frankly, I'd still need to port to all those different SDL implementations. And I don't like OpenGL style programming, it's just plain ugly. And it needs c++, I know that there might be some wrappers available, but I don't like to use wrappers, because...
* Irrlicht. A lot of features, but support seems to be low and it is aimed at enthusiasts. C# bindings get dropped repeatedly. I'm not an engine enthusiast, I just want to make a game. I don't see this happening with Irrlicht.
* Ogre3D. Way too much work, it's just a graphics engine. Also no multiple platform support and c++.
* Torque2D. Costs something to use, and I didn't hear a lot of good things about support and documentation. Also costs extra for each platform.

# Answer
I've been using LÖVE for some time now and I like it a lot. You would have to learn Lua, but it is a fun little language to learn anyway. The people at the forum are extremely helpful.
> 9 votes

# Answer
Pygame is by far my favorite. Since programming in python means you will program fast and since 2D things are fast to do, pygame will be fun...
> 9 votes

# Answer
I decided to go with Flash. The new Molehill 3D API can be used to draw 2D sprites in 3D space a lot faster as well. I see no reason why Flash shouldn't be fast enough for the game I described earlier. I'll have to build the tools myself, but I would have probably needed to do that anyway. Using AIR to build tools is also pretty neat in my opinion. Flash also has the widest reach with platforms, which is cool.
> 5 votes

# Answer
Try SFML
> 4 votes

# Answer
Try Cocos2d-x. It's what I'm using for my indie game development.

It's a tried and true OpenGL (ES) platform which has sound, physics, and even a little 3D that has been out for the iPhone for a while now, and is just coming to other platforms.
> 2 votes

# Answer
Since you said you like Actionscript but are looking for cross platform, take a look at HaXe + NME. HaXe is a language similar to Actionscript, but can compile to Flash, Javascript, PHP, or C++. NME is a library similar to Flash's graphics library, but runs on other platforms too. This combination allows you to compile to many different platforms.

I've not used NME yet but my first test with HaXe+Molehill (just a few days ago) produced 60fps when rendering 10,000 16x16 rotating sprites on my laptop. I've only been using HaXe for a few days and don't have enough experience with it to be sure it's the right thing for you, but it's worth a look.
> 2 votes

# Answer
I'm personally a huge fan of Allegro 5, but it is a C API. Still and all, it's a simple API that get's out of your way and provides access to:

* 2D graphics (backed by OpenGL or D3D, depending upon platfom)
* Sound
* Fonts (including both bitmap and TTF)
* Input (mouse & keyboard)
* PhysicsFS (file system virtualization)
* Image loading

5.1 will be adding shader support, as well.

SDL 1.3 is also shaping up quite well. Sam seems to be done making the major API changes, and what is already in is pretty stable already. Still ... it's not even beta yet, and Allegro 5.0 is released.

Granted, for more complex and advanced games you'd probably want to pair Allegro 5 with some sort of physics library (Box2D, for example). Still, you can get a very long way, and have a pile of fun, with nothing more than what Allegro 5, the C or C++ standard library, and your own code.
> 1 votes

---
Tags: c#, 2d, actionscript-3
---


# Question
Title: How can cooperation be encouraged in and after a game jam?
The trouble is that with game jams sometimes loads of people participate, but at the end they say "Right! Bye!" and you never hear from them again. If a cooperative element was introduced, the reward from the jam would not only be a game, but a new friend to create games with.

How do you go around implementing such a design without causing lots of people to drop out?

# Answer
> 1 votes
Basically, you're not going to be able to force people to stick together after a game jam, but there's a few ways you can help. Some of these suggestions are for local jams, and some are for online only jams (and some are both)

First, get the participants to exchange contact information (names, emails, phone numbers, social security numbers (not actually social security numbers)). This will at least allow people to look up their teammates in the future if they want to collaborate again. This is also pretty easy to do.

Second, if it's a local Jam, organize game developer meetings in the future, so people can keep those connections fresh, and hopefully gain even more of them.

Finally, if it's an online Jam, establishing a year-round presence through a website, forum, and/or chat room will help keep those connections alive. For instance, Ludum Dare has an IRC chat room that is active all through the year, though it becomes filled with tons of new people during each event.

---
Tags: project-management
---


# Question
Title: How to resolve penetration of two colliding bodies
I've implemented simple 3D game physics engine. I already have decent collision detection in place, now I'm trying to figure out the collision response part. I'm using impulse based method to calculate the post-collision velocities. This works pretty well, however, it does not completely prevent the bodies to keep interpenetrating. So I have additional piece of code to resolve the penetration. Currently, I just move the bodies along the contact normal by half the penetration depth - first body in the direction of the contact normal, second body in the opposite direction.

This is ok most of the time, but there are some undesirable effects. For example, imagine a narrow corridor and an object moving through it. If the object hits one of the walls of the corridor, the penetration resolution moves it into the opposite wall, then in the next frame back into the first wall and so on. The effect is the object is kind of vibrating really fast between the walls which is not pretty.

So my question is whether there is a better way to resolve the penetration? Perhaps not move the bodies, just somehow adjust their velocities (in addition to the impulse computation) so they stop moving toward each other and the penetration resolves itself in the next couple of frames. I'm just guessing here. Any ideas?

# Answer
> 3 votes
When you detect a collision, determine at what time / point the bodies first started colliding, and treat the collision at this point. You may still have a slight penetration to resolve at this point, but it will be much smaller and \[typically\] won't yield the oscillation issues you're having.

Lets say that you have 100ms simulation steps and that in some frame, you have two balls that collide half way (50ms) into the frame. First, you'll detect that they collided at any point in the frame (which I trust you're already doing effectively). They you'll determine at what point during the frame they collided. Now handle the collision, including the first 50ms of the frame in which they didn't collide. You'll now have the balls' new velocities, and you can also take steps now to ensure that they aren't penetrating (these should be very small since it "just happened.") Finally, you'll simulate the next 50s of the frame. Note that during this period, there may very well be another collision with one or both of these balls.

# Answer
> 2 votes
Check out this article -- which has been posted here many times before, just search through the collision-detection tagged Q&As -- it shows you how to do the "continuous" collision resolution that stephelton was talking about:

http://www.gamasutra.com/view/feature/3383/simple\_intersection\_tests\_for\_games.php?page=3

Basically, you solve some basic kinematics equations for the exact timepoint when your two bounding boxes began to intersect. You resolve your collisions at that exact moment, and then proceed with the remaining time in your frame. You might have to re-simulate what happens after the moment of collision, since the velocities/accelerations of your objects will have changed. But there is your starting point, anyway... cheers!

---
Tags: 3d, physics, collision-resolution
---


# Question
Title: How to encapsulate game objects (entities) in Box2d
I am currently learning Box2d, a 2D physics engine within libgdx. But Box2d seems to be in every game framework these days so I am not really talking about libgdx.

I understand Box2d comes with lots of new concepts such as shape, bodydef, body, fixture, sprite, joint. But I think I can slowly but surely manage to learn about them.

My question, however, is how to organize them into a game object for better maintenance of code. Naturally, I am thinking about following fields in the game object class.

* GameArea gameArea
* Body body
* BodyDef bodyDef;
* FixtureDef fixtureDef
* Shape shape;
* Sprite sprite;

As for its methods, it has constructor, update, and display. But I am talking without experience. For example, I don't know how I can organize joints - maybe in GameArea. Any thought from experienced would be appreciated.

# Answer
The answer is based on the as3 port of Box2D, but I believe, the concepts are the same.

I think, you're complicating things. bodyDef, fixtureDef and shapes are used for instantiating a body and don't need to be stored after that. Sometimes having a pointer to a specific fixture might come in handy, but not in a generic Game Object.

The same applies to joints. Sometimes you need to control them from your class - for example, you need to destroy a joint when a player steps on a trigger, or to move a platform along a joint. In that case, you'd want to put a joint field into the Trigger/Platform class.

So, what a game object needs is just a body and a sprite. GameArea reference (what ever that is) might be useful to. You might also want to store a reference to a b2World, but I prefer to store it in a static ("global") variable in a separate Physics class.

Constructor, update and display is a good base. Box2D body initialization is pretty complex, so you could add some helper methods for creating bodies and shapes.
> 3 votes

---
Tags: box2d, design-patterns
---


# Question
Title: How can I extend this graphics code to draw more vectors of vertices?
I want to include the drawing of other vectors of vertices in the following code, in a number of places it seems easy enough to simply add or multiply `size()`s of the two vectors, for instance in the first check. But then it gets a bit fuzzy simply because of a lack of understanding.

Should I add them together to create a bigger buffer description and copy everything together? Or should I do it all separately?

Basically how would I extend this code to include more vectors of vertices?

```
if (temporary2DVerts.size() > 0)
{
    // create the vertex buffer and store the pointer into pBuffer, which is created globally
    D3D10_BUFFER_DESC bd;
    bd.Usage = D3D10_USAGE_DYNAMIC;
    bd.ByteWidth = sizeof(VERTEX) * temporary2DVerts.size();// this breaks the create buffer line : temp2DVerts.size();
    bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
    bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
    bd.MiscFlags = 0;

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

    void* pVoid;    // the void pointer

    pBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &pVoid);    // map the vertex buffer
    memcpy(pVoid, &temporary2DVerts[0], sizeof(temporary2DVerts[0]) * temporary2DVerts.size());
    pBuffer->Unmap();

    // select which input layout we are using
    device->IASetInputLayout(screenVertexLayout);

    // select which primtive type we are using
    device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_LINELIST);

    // select which vertex buffer to display
    UINT stride = sizeof(VERTEX);
    UINT offset = 0;
    device->IASetVertexBuffers(0, 1, &pBuffer, &stride, &offset);

    // apply the appropriate pass
    screenPass->Apply(0);

    // draw the vertex buffer to the back buffer
    device->Draw(temporary2DVerts.size(), 0);

    temporary2DVerts.clear();
}

```

EDIT - just to be clearer - there are 4 vectors of vertices. two that don't change and two that constantly change. permanent 2D and permanent 3D and a temporary version of both. This is so the permanent ones can just be loaded in and are always drawn, and the temporary ones only get drawn for a frame. This way I can create moving lines for debugging, like line of sight cones etc.

EDIT - the naive approach would be to duplicate this code 4 times for each vector, but surely there is a better way? I don't think this is a hard thing to do, but trying to do it has exposed a basic gap in my knowledge about what some of these lines of code do. should I just populate one big list from all the vectors and push that through?

some need to be drawn with different passes, and some don't need to be changed each frame. for example, the permanent ones can just stay on the gpu. right?

# Answer
First of all, you shouldn't create buffers at rendering time as it is a costly operation, putting pressure on the GPU memory (it is also not clear that you are actually releasing the vertex buffer). It is better to allocate buffers at the beginning of your application.

If I understand your use case, you have a set of non-moving vertices-lines and a set of moving vertices-lines: It is better to allocate two buffers for each usage, one that is not declared as dynamic and the other dynamic.

You should first draw your buffer of constant vertices. Then for the moving lines, you just have to update the other specific dynamic buffer on each frame. This buffer should be allocated with enough space for the maximum number of expected vertices to move. If number of vertices could change heavily between the calls (ranging from 10 to 10000), you could create 2-3 dynamic buffers for the right maximum size (for example 10, 1000, 10000) and select the right dynamic buffer according to your temporary2DVerts.size();.
> 3 votes

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


title: How to unpack tileset or image atlas

text:
# Question
Title: How to unpack tileset or image atlas
In order to define boundary of each tile, I need to have individual image of the tile. Is there any way to extract each image of tiles from a tileset?

# Answer
If all your tiles are the same size, then you can use TileMage Image Splitter.

I've used it before, and it works fine, even for 10000xN pixel tilesets.
> 2 votes

---
Tags: tiles
---


# Question
Title: When animating sprites, why subtract frametime when switching between sprites instead of resetting elapsed time to zero?
I am currently on chapter 3 of the book "Learning XNA 4.0". At the end of this chapter is a section on changing the animation speed of sprites.

```
timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
   if (timeSinceLastFrame > millisecondsperFrame)
   {
       timeSinceLastFrame -= millisecondsperFrame;
       //code for cycling through sprite sheet here.

```

This code is in the Update method. It iterates timeSinceLastFrame until it's greater than millisecondsperFrame (which I have specified as 20), and then it resets by subtracting millisecondsperFrame from timeSinceLastFrame.

If I instead reset it by writing timeSinceLastFrame = 0, the animation is noticeably slower. From what I can tell, this is due to the fact that XNA updates at 60 frames per second, so timeSinceLastFrame iterates by several milliseconds each time, and likely won't have the same value as millisecondsperFrame once the if statement compares the two.

Despite this, is there anything particularly bad about writing timeSinceLastFrame = 0? Or is timeSinceLastFrame -= millisecondsperFrame safer?

# Answer
> 6 votes
The reason why timeSinceLastFrame -= millisecondsperFrame works better is it accommodates for the bleed-over time from the animation. Let me explain:

So your game is running and the Update method is firing. When it reaches a point where it advances to the next frame, it will reset using the form mentioned above. Say your animation advances every .3 seconds, and the update method has fired at the .32 second mark. Therefore, .02 seconds are carried over to the next frame.

So what happens when you set timeSinceLastFrame to 0? Well then at .32 seconds when the frame advances, it resets the timer meaning you just spent an extra .02 seconds on a frame. If this happens say 30 times, you have just created a lag time of over half a second. The accumulation of lag time slows down the animation, and that causes the effect you see there.

Generally, if you want more accurate animation, I would go with the method that's currently there in your code.

Happy Coding!

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


title: Efficient Sprite Batching

text:
# Question
Title: Efficient Sprite Batching
Am considering porting over from XNA to the Stage3D API's (Molehill). So as a performance examination I've implemented sprite-batching, but the performance is not all that great, while with XNA i can easily draw up to 500 000 quads but with my Molehill implementation i can draw around a measly 1000 quads and while a rather dramatic performance difference was expected on the CPU side this is due to being GPU bound.

So currently the implementation is as follows.

```
set render states

let texture be null
let batchSize be arbitrary

for each sprite in queue
    if texture is not sprite texture
    or buffers are full

        upload vertex data to index buffer
        upload index data to vertex buffer

        bind texture
        draw triangles

        flush vertex data
        flush index data

    add sprite vertices to vertex data
    add sprite indices to index data
end

upload remaining vertex data to vertex buffer
upload remaining index data to index buffer
draw remaining triangles

flush data

```

The bottleneck is uploading the buffers, but as for a better implementation I'm hoping for a discussion here.

Cheers.

Revision:

> One optimization that comes to mind is to persist the index buffer, since the indices are predictable and will always follow the same format. Am going to benchmark that now.

---

> Caching the index buffer had no noticeable performance gains, so in an effort to try to understand where the bottleneck is, I ported it over to C#/XNA, ever so slightly slower than Microsoft's implementation but still has a GPU capacity over 500 times more than the Molehill implementation.
>
> Is Molehill simply an extremely bad abstraction layer?

# Answer
> 2 votes
You could have a multi-map of sprites in which their key is the texture, then when rendering, go through each key in the map and render each group of sprites that are associated with that texture. If sprites all share the same texture then you can represent every sprite with two triangles and texture coordinates, which means you can draw all sprites that use the same texture in a single pass, with a single vertex buffer and index buffer.

Although I'm using XNA, I've rolled my own rendering and batching process rather than using sprite batch, and I'm rendering about 3000 sprites at a time and currently getting about 600 fps on an Nvidia GTX 275, using the process I described above. When I was just passing the sprites to the spritebatch method XNA gives it was about 25 fps.

In my case, rather than a multimap I have a class (SpriteData) that contains the texture and a list of vertices. Whenever a sprite registers with the renderer, the renderer goes through a List of SpriteData until it finds a matching texture type, and adds that sprite to vertex list.

I'm also doing spatial partitioning to make sure that only sprites in view are being considered.

---
Tags: actionscript-3, gpu, molehill
---


# Question
Title: Which is better for a beginner, UDK or Unity?
I am just getting into game development and I would like to know which engine would be best to learn first.

In terms of my current skills, I know a good deal of javascript, but not much beyond that. This is all a learning experience for me (I am an extremely fast learner).

I am using HTML5 canvas right now as that's mostly what I was hinting at when i said javascript. I probably should have made it a bit more clear.

# Answer
Definitely Unity. Its really kind to beginners, and has a really nice, "just-works" API. Also, It'll give you good experience in working with proprietary game engines, which will help if you ever think of getting into the game industry. It also supports more freedom in game design than UDK which (as much as they claim to the contrary,) is geared (no pun intended :P) completely towards FPS style games.

However like what Twitchy said, eventually you will want to use custom libraries like XNA, or MOGRE; it is the natural next step in game development (in my opinion).

Good luck, and have fun :)
> 4 votes

# Answer
Based on my experience.. Neither.

The reason for this, is that when learning game development I find it alot better to be looking at the back end of the code, and learn from the ground up.

I started back in the day with Game Maker, and while some people may disregard that, it allowed me to learn how programming languages work, and gave me a simple look at OOP.

About a year ago, I started to learn C#, and soon after started to mess around with XNA. The great thing about XNA is that is managed code, and takes out most of the really hard stuff, but at the same time, you can develop games really quickly without having to learn how engines like UDK and Unity work. From what I hear Unity and UDK are mostly 3D, and personally that is not a good place to start for a new game developer.

With XNA you have SpriteBatch and the Content Pipeline, which makes drawing sprites to the screen really simple. You have the Draw and Update method, which are handled by the backend of XNA to keep timing values, and the rest can be designed by you.

Once you understand how DirectX works on a very simple level, you could try looking at using Unity or UDK. But, by then, I think you would find it gives you much more control to use a framework, and much more enjoyable too.
> 3 votes

# Answer
Why don't you try HTML 5 canvas? It is much more like Javascript and will enable you to develop some cool 2D videogames playable in a web browser.

UDK and Unity are better if you don't want to write your own 3D graphical engine: I would suggest UDK to start because it is well documented and easier to start with. Visit this link: http://udn.epicgames.com/Three/DevelopmentKitProgramming.html.
> 0 votes

# Answer
Since you already know javascript and you're at a beginner level, I'd certainly recommend Unity. In Unity you can write you're scripts in javascript and it is a bit easier than Unreal.
> 0 votes

# Answer
i would also recommend Unity but only for beginning. The good thing about Unity is that you get allot of free cool stuff you can build from their website, defenently check that out.

have fun!
> 0 votes

---
Tags: unity, udk
---


title: Multi texturing in XNA

text:
# Question
Title: Multi texturing in XNA
I am attempting to make a map editor for my game, just so I can visualize how the end result would be.

To my world I can add cubes (2 triangles) or corners (1 triangle), which are then added to a list of the vertices to draw, and the indices are added to a list of indices. Everything draws fine here, and I can set different colours for each vertex.

I would like to implement texturing, so that when you add a primitive to the scene it will let you choose a texture (that, I can handle), but then also blend with other primitive's of different textures if they are touching (everything is on a grid).

I would guess that I would have to store the texture name for each primitive, and somehow set that texture when drawing it. But I fail to see how you can set the effects texture when you are using one `DrawUserIndexedPrimitives<>` to draw the entire scene.

If anyone has a work around for this, or ideas on other ways of doing this, you help would be greatly appreciated.

---

**Edit 1**

I have incorporated the technique from this website here - http://toyfactorygame.com/wp.php/2010/05/06/simple-fast-gpu-driven-multi-textured-terrain/ (similar to Blau's answer below), and have the current working result...

Which maps to this...

Using each color channel as a texture..

```
Output = tex2D(TextureSampler0, input.TexCoords) * input.Color.r;
Output += tex2D(TextureSampler1, input.TexCoords) * input.Color.g;
Output += tex2D(TextureSampler2, input.TexCoords) * input.Color.b;
Output += tex2D(TextureSampler3, input.TexCoords) * input.Color.a;

```

But doing it this way means I can only be setting 4 textures to blend together each DrawPrimitives call.

Is there another way I can achieve multi texturing with more than 4 (preferably unlimited) textures? I know this is possible, as games like C&C generals allow you to set textures anywhere you want on the map.

---

Thanks.

Twitchy

# Answer
> 2 votes
You can add to your vertex these arrays:

```
   int[4] TextureId;
   float[4] TextureWeight;

```

and in your shader you can do the blend,

```
  finalTexColor = tex0sample * TextureWeight[0] + tex1sample * TextureWeight[1] +tex2sample * TextureWeight[2] + tex3sample * TextureWeight[3]

```

you can see this article to know how.

---
Tags: xna, c#, uv-mapping
---


title: What's a pre-multiplied 4x4 matrix?

text:
# Question
Title: What's a pre-multiplied 4x4 matrix?
I'm using a 3d game engine, that uses a 4x4 matrix to modify the camera projection.

The matrix is in the regular 4x4 format:

```
 r r r  x
 r r r  y
 r r r  z
 - - -  zoom

```

The description for the matrix class says:

> A transformation matrix. Matrices are pre-multiplication, as in: x' = M\*x.

What does this mean?

# Answer
> 4 votes
It's not saying the matrices are *pre-multiplied* but rather that they are (read use) *pre-multiplication*.

This basically specifies the correct order of multiplication when using them, such that when multiplying a matrix by a vector, the matrix needs comes first.

In other words, this:

```
result = matrix * vector

```

Instead of:

```
result = vector * matrix

```

# Answer
> 6 votes
Pre- or post-multiplication just defines the order of operations how the member of that matrix and vector are multiplied, its purely a notational convention.

The common operations in 3D graphics are post-multiplying a row-vector with column-major matrices (OpenGL) and pre-multiplying a column-vector with row-major matrices (DirectX).

Both are basically the same operations with the same results, just the notational convention is different.

---
Tags: 3d, mathematics, camera, matrix, projection
---


# Question
Title: How to save the 3D surface to bitmap in Flash 11 Stage3D
I have been using Stage3D to create some 3D app in Flash. One of the items on my list is the ability to take a screen shot. Flash makes it easy to grab the stage content, but I can't find a way to grab the stage3D content. In DX I just used D3DXSaveSurfaceToFile. Anyone know of a way to do it in as3 and flash 11?

# Answer
> 2 votes
The `drawToBitmapData` method of your 3d context (`Context3D`) should do what you want. Here are the API docs for said method.

---
Tags: flash, rendering
---


# Question
Title: What does `FPSManager.lastticks` stand for in SDL_gfx?
I'm having trouble finding documentation on SDL\_gfx, and I can't figure this out. I've managed to use SDL\_gfx to automatically cap the framerate, and I it's working a lot better than my manual attempt (combining `SDL_Delay` and `SDL_Getticks`).

Now I've been trying to learn more about it, and I stumbled onto something.
Here's the whole struct:

```
typedef struct {
             Uint32 framecount;
             float rateticks;
             Uint32 lastticks;
             Uint32 rate;
     } FPSmanager;

```

Most variables in this struct are pretty straightforward, but I have no idea of what `lastticks` stands for. Does anyone know?

# Answer
To put it simply, `lastticks` is used to to store the result of calling `SDL_GetTicks()`, or in other words, the number of miliseconds that have passed since the SDL library was initialized.

This is supported by looking at the `SDL_framerate.cpp` implementation file, and noticing that every assignment to `lastticks` is as follows:

```
manager->lastticks = SDL_GetTicks();       // Lines 23 and 81

```
> 2 votes

---
Tags: sdl, sdl-gfx
---


# Question
Title: How portal 2 can be so cross-platform? (pc,osx,xbox,ps3)
I mean: i don't think they made 4 differnet game for each platform.

How they achived such huge cross-platform? (Did they use a graphic engine that already supports all of them?)

Thanks

# Answer
> 15 votes
They utilized their proprietary Source engine. Many game engines and libraries are cross platform, it's nothing new. Portability is typically built into most contemporary engines.

The simple answer: their engine supports all of those platforms. The gameplay code isn't rewritten for each. Only necessary platform-specific systems are re-written to an API specified by the engine.

Unreal is another example of a cross-platform FPS engine, as is the Infinity Ward engine. You'd be hard pressed to find a contemporary game engine that isn't cross platform.

# Answer
> 9 votes
As A.A Grapsas (that's a tongue-twister) said, their underlying library/engine was created to be cross-platform.

One of the reasons that things like the Unreal engine are so expensive is that they've (mostly) conquered the cross-platform challenge, allowing games based on it to run on the Xbox/PS3/Windows/etc. Since cross-platform means working with different platform-specific compilers, different target processors (X86, ARM, PowerPC, Cell, etc), different GPUs (NVidia, ATI, though this is handled quite well by the drivers these days), etc. Implementing a new engine that provides that capability is non-trivial, as is maintaining it and keeping up with new platforms, especially mobile devices. Poorly implemented code will rapidly mire a project in bugs and maintenance challenges.

From a development standpoint, the key is to use a *native, compiled* language that's pretty well standardized and available on all target platforms, which today means C++. Platform-specific methods are placed in pluggable libraries, and the entire code base is compiled using each platform-native compiler. g++ is a good baseline - unfortunately, "good baseline" also means lowest common denominator. I'm not sure which compilers are used for the Xbox and PS3, but I'd bet that the professional Xbox kit uses Visual C++. VC is an *amazing* tool, and offers one of the best compilers and most advanced debugging environments available in the world.

If you're interested in more detail, check out Brian Hook's book, Write Portable Code. It's pretty inexpensive and an easy read. He's been around the game industry for quite awhile and, though the book doesn't focus on games per se, the advice it provides definitely applies.

# Answer
> 6 votes
A while back I did a GDC talk on how we built Source to be cross-platform, and best practices for cross-platform development generally:

# Answer
> 1 votes
As already stated their Source engine is written to be cross platform. Writing a cross platform engine is no trivial task (if you want it to work well on all hardware) which is why may companies license engines rather than develop them from scratch.

The trickiest part of making a performant cross-platform engine is no longer differences between processors. Less than 0.1% of the engine code will likely be in assembly - usually just the lowest level vector/matrix math libraries. C++ is fairly portable these days, especially if you are doing Continuous Integration and testing/building on all targets - the STL is typically the sticking point - which is why games companies either have their own alternative (slimmer) template libraries or have their own custom versions of STL (eg EASTL).

The biggest problems these days are down to hardware differences between the various target platforms. ..

You need to support some modern version of DirectX for the PC build, a variant of DirectX 9 on the 360, a variant of OpenGL (or Sony's proprietary libraries) on PS3, and OpenGL ES on mobile. You then have to deal with each platform having it's own audio libraries (although many companies just go with middleware these days), their own game load/save systems, different filesystems and different requirements for streaming/caching assets. Each platform have different balances between pixel and vertex processing speeds and available features.

On top of that you have completely different multi-processing approaches on each machine - 360 has 3 identical multithreaded CPUs, PS3 has one main CPU and then a bunch of self contained SPU processors to keep fed, Wii and iOS are single processor machines, PCs have a varying number of identical cores to keep running.

Oh and the memory models of each machine require you to handle how textures/vertices are loaded differently - PS3 has it's memory split between the CPU and the GPU, 360 has unified memory, PCs have the gfx card memory to keep filled. You also have very differing memory sizes from iPhone up to PC. So not only does your runtime need to be organizing memory differently on each platform but your tools pipeline needs to be able to target these different machines also (ideally with the same source art assets).

So yeah, to answer the original question - they have a cross platform engine. And it was likely a non trivial undertaking.

---
Tags: cross-platform, porting
---


# Question
Title: Version control with game development - When should I branch?
I recently started using Version Control with my projects (even though I'm working alone on them). I find that it gives a nice way to keep history of the whole development process (with issue tracking) and allows me to keep backups for my projects along the way.

As I slowly discover the features and advantages of using version control, I am stuck around the idea of branching. When should I do it?

Should it be every single time I go and develop a new feature, or only once in a while when I reach a certain milestone?

Obviously, branching is pretty useless when working alone, but I'd rather pick up good habits now and get used to it.

As I was reading the book Game Coding Complete by Mike McShaffry (which is a great book by the way), I got totally lost when the author recommended keeping three branches, something along the lines of:

* **Main**: Main development branch where regular changes are made.
* **Gold**: Gold branch where the last milestone reached is kept.
* **Research**: Branch for testing stuff that could badly impact the Main branch (modifying important components of the game engine, etc.).

Is that how it is supposed to be? How does it really work in the world of game development with big teams of developers?

Basically: **When does one usually branch (and merge) in game development?**

# Answer
Branching depends a little on VCS support for the feature (ie: whether the VCS makes it easy or difficult).

But at a minimum, you want a branch for each independently supported release of your project. That is, if you have "Game 2", and "Game 2 + Expansion" which are separate products built from the same codebase, and which you need to be able to patch and issue updates to, then you want to have each of these exist in their own branch off of the main codebase, so that fixes to the core codebase can be merged into each of these products independently. (Typically, these branches are created when each product is released, or perhaps a few days/weeks before, if you have people working on things in the codebase which you don't wish to go out with the initial release)

When working with a VCS which makes the use of branches tricky or painful (SourceSafe, svn, etc), then you'll probably be happiest maintaining a "release" branch for each released product, and doing your main development in "trunk", merging changes from "trunk" into the "release" branches if and when you need to release hotfixes for those releases.

If, on the other hand, you're working with one of the newer VCS systems which are built around branching and merging (git, Bazaar, Mercurial, etc), then you'll probably be happiest doing your development in a lot of short-lived "feature" branches. For example, if you're working on AI pathfinding, you can make a "pathfinding" branch and implement the code in there. When you finish, you merge that branch back into your main trunk of development, and (optionally) delete the branch you were working in. The benefit of this approach is that it lets you work on multiple tasks simultaneously, instead of needing to complete one task before starting on the next.

In my current home project (using git), I have five different feature branches active right now, working on various different features. Two of them are alternate approaches to doing the same thing (for profiling), two are experimental game mechanic ideas, and one is a big refactor of my AI systems, and is actually broken in such a way that the code won't compile right now. But it's committed in its feature branch for reference and for backup, and it being broken doesn't stop me from working on the other features; Those other feature branches (and the main development trunk as well) still compile and run correctly.

In my experience of big-team professional game development, we're still mostly stuck with older (and commercially supported) version control systems. Perforce is probably the most commonly used, followed by Subversion. Everywhere I've worked, we've had a 'trunk' branch, and then a separate 'release' branch for every deliverable (milestone/demo/release/etc). Occasionally someone will make a personal branch for some huge change they're making or testing, but this is extremely rare, and is usually for things like "converting the game to run with this different physics library" which may not actually go through to the released product.
> 32 votes

# Answer
Already an excellent answer above but one thing to to note is when you want to branch and when you want to tag.

Most vcs will allow you to tag (sometimes they call it labeling). You should apply a tag every time you make a major build (either for a playtest, or a beta test, or for a feature going in). If you are using some kind of Continuous Integration (and you should) then the CI system should tag successful builds. Basically any time you do something that you might want to go back to (either to create a branch or to check back how you did something in that version) make a tag/label. They are usually low cost and simple to add.

The other thing I would very strongly advise is to keep your assets and code in the same versioning system. Having a branch (or tag) of code is completely useless if you cant match up (and then branch) the assets. This is one of the main reasons game companies love Perforce - it is equally happy storing binary art files as it is storing code, and (unlike git) it is understandable to non-technical types!

Oh and any time you feel like you want to check compiled files into your VCS stop and think about how you can avoid doing so. In my experience it almost always leads to mismatched data, missing source (where for instance a compressed DDS texture gets checked in but not the source png), and chaos down the line. If you have an asset pipeline that is better served by exported files being cached somewhere (so everyone is not re-generating the same set of files) by all means have a process building the source assets in your VCS and placing the exported files into a cache (or shared drive, or even a separate VCS). But don't check those exported files in by hand - it will bite you (especially if you are working in as part of a team).
> 8 votes

# Answer
I loved that book, and I recommend it to everyone with relevant interests. For one man indie projects, there's no real need to branch at all unless you need or want to create separate versions; like one for Android and one for PC, or something along those lines.

As you said, if you want to pick up good habits, I would go with Mike's approach. It makes a lot of sense and its the approach I use in my two man indie projects.
> 1 votes

# Answer
Anything you need to be able to go back and do more work on, should be *branchable* (but not necessarily branched... yet).

The reason for this is simple. You need to be able to issue a fixed version of that code, not any other code, so at that time you need to work on a branch.

VCS'es are different. Some - like git - is very easy to branch from any commit at any later time, others - like CVS - is very cumbersome to work with later.

Perhaps you want to open a question on stackoverflow, asking how to work the best with the version control system you've chosen? If you have not *really* started yet with a lot of history, you may want to open a question describing the way you work and ask for a recommendation of the best version control system for you?
> 1 votes

---
Tags: game-industry, version-control
---


# Question
Title: JiglibX addition to existing project questions
Got a **very** simple existing project, that basically contains a lot of cubes. Now I am wanting to add a physics system to it and JiglibX seemed like the simplest one with some tutorials out there.

My main problem is that the physics don't seem to be working how I imagined, I expected my tower of cubes to come crashing down, but they dont seem to do anything.

I think my problem is that my cubes do not inherit `DrawableGameComponent`, they are managed by a world object that will update and render them. So they are at no point put into the games component list. I am not sure if this means that JiglibX will not be able to interact with them as in all the tutorials there are no explicit calls to add the Body objects to the physics system, so I can only presume that they are using a static/singleton under the hood which automatically hooks in all things, or they use the game objects component list somehow.

I also noticed that in alot of the tutorials they use the following when setting up the physics system:

```
float timeStep = (float)gameTime.ElapsedGameTime.Ticks / TimeSpan.TicksPerSecond;
PhysicsSystem.CurrentPhysicsSystem.Integrate(timeStep);

```

Would it not be better to keep a local instance of the created `PhysicsSystem` object and just call `myPhysicsSystem.Integrate(timeStep)`?

# Answer
You need to make sure that your physics bodies are dynamic. Set 'Body.Immovable' to false. And as @Neil Knight said, you need to enable the body: 'Body.EnableBody()'
> 1 votes

---
Tags: xna, xna-4.0, physics-engine, jiglibx
---


# Question
Title: How do I make a pointer point to the current running level if each level is its own class?
I'm hard-coding my levels and coding each level in its own class...The problem is that I need to have a pointer that points to the class of the current level. I don't know how I would go about doing this. I ideally want to have a vector that stores the levels, and I'm working on a level managing class to load, update, draw, and unload the levels in.

# Answer
> 4 votes
If your level classes have a common Base class you can just create a pointers to it:

```
class Level {
    virtual void func1()
    //...
    virtual void funcN()
}

class Level1: public Level {
    virtual void func1()
    //...
    virtual void funcN()
}

class Level2: public Level {
    virtual void func1()
    //...
    virtual void funcN()
}

Vector<*Level> levels;
levels.append(new Level1())
//...
levels.append(new LevelN())

```

# Answer
> 6 votes
It would be a bad design to have separate classes for each of the level and will also duplicate your code. Why can't you change the level specific values before starting a new level (have them stored in as some constant or in text file).

---
Tags: c++, levels, objects
---


# Question
Title: How do I get the alpha level at a specific pixel with Slick 2D?
I know that there is the `Texture.getTextureData()` method, and that it returns a `byte[]`, but I have no idea how I could use this data to find the color data at a specific pixel.

# Answer
I'm not too familiar with Slick2D, but assuming it's sending back uncompressed data like most other methods of this type are, the byte array just represents color channel data packed together. Each color consists of a Red, Green, Blue, and sometimes Alpha channel. Typically the order of these channels are `RGBA`, but it's possible that the orders are flipped, I've seen `ARGB` and `BGRA` before. So the byte array is going to look something like `R, G, B, A, R, G, B, A...`. If you wanted to figure out which order it returns (a quick search of Slick2D documentaiton doesn't find any mention of channel order), you could create an all-red or gradient transparency image and read the first few values of the byte array from the debugger.

Also note that the 2d texture has it's data unrolled so that the `byte[]` is a single-dimensional array. You can access the `A` channel of a pixel at a given location like this:

```
//pixel locations to look up, assume initialized and checked to be in texture bounds.
int px, py;
byte[] texData = tex.getTextureData();
byte alpha = texData[4 * (py * tex.getTextureWidth() + px) + 3];

```

Breaking down the last line of the example in order of operation:

`py * tex.getTextureWidth() + px` is the standard way of looking up a 2d index in a 1d array. This is the location of the pixel were this an array of pixels.

`4 *` takes the pixel location and scales it to represent the color channels. This gets you the location of the first channel of the selected pixel. (Assuming RGBA layout, this would be the red channel)

`+ 3` offsets the red channel location to the alpha channel. This is assuming `RGBA` ordering. If it were `ARGB` this part isn't necessary.
> 3 votes

---
Tags: java, textures, lwjgl, slick
---


title: Simple example of 3D world in OpenGl

text:
# Question
Title: Simple example of 3D world in OpenGl
I'm writing a simulation program and now I'd like to visualize the results in 3D.

All I need is N tetrahedrons moving inside rectangular cuboid. I have already calculated coordinates of tetrahedrons at each step. Possibility to move camera would be nice :)

So, I'm searching for a code sample I can adopt or docs.

# Answer
Assuming you know how to draw to the OpenGL, I'll just give you the relevant parts:

Make a tetrahedron class, to build up the vertices, use this info to construct the class:

vertices:

```
v0 = 0, 1, 0
v1 = 0, 0, 1
v2 = 1, 0, 0
v3 = -1, 0, 0

```

triangles:

```
t0 = v1, v2, v3
t1 = v1, v2, v0
t2 = v1, v3, v0
t3 = v2, v3, v0

```

and in the draw method does something like this pseudo-code:

```
draw()
{
    glPushMatrix();
        glTranslatef(x, y);
        glScale(scalefactor, scalefactor, scalefactor);
        glSomeMethodToDraw();
    glPopMatrix();
}

```

Well, you can actually draw with a lot of methods, there are `glBegin`~`glEnd`, `glDrawArrays`, `glDrawElements`, choose yours.

And i don't mentioned rotation because it can be done in a lot of ways too, you haven't cited it in your question, so i let it out.

For your camera, take this simple as example:

```
class Camera
{
    float x, y, z;
    void draw()
    {
        glMatrixMode(GL10.GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(-x, -y, -z);
    }
}

```

Simple huh? If you dont know yet, the basis of a camera in OpenGL(and maybe in every lowlevel GPU API) is just move your world in the opposite direction. May look strange, but if you think hard on it, it will look fine!

Outside, you can make a linked list of tetrahedrons to initialize your code.

I dont know how you'll get your input(as i dont know your platform, language, you should cite those to help on answers), but here's a simple pseudo code to move the camera:

```
void keyPress(keyCode key, boolean pressed)
{
    switch(key)
    {
        case DOWNKEY:
            yacceleration = (pressed ? -15 : 0)
        break;
        case UPKEY:
            yacceleration = (pressed ? +15 : 0)
        break;
        case LEFTKEY:
            xacceleration = (pressed ? -15 : 0)
        break;
        case RIGHTKEY:
            xacceleration = (pressed ? +15 : 0)
        break;
        case PAGEUPKEY:
            zacceleration = (pressed ? +15 : 0)
        break;
        case PAGEDOWNKEY:
            zacceleration = (pressed ? -15 : 0)
        break;
    }
}

```

Tedious and simple camera movement.

for your update method, do this:

```
update()
{
    camera.x += xacceleration;
    camera.y += yacceleration;
    camera.z += zacceleration;
}

```

(:

The fun part, the main draw code!

```
draw()
{
    camera.draw();
    foreach(Tetrahedron t in tetralist)
    {
        t.draw();
    }
}

```

Very simple, but functional.

Just to mention, i haven't tested any of this, just theory to make you find your way.
> 3 votes

---
Tags: opengl, 3d
---


# Question
Title: What can be done to recover from an exploit-related PR disaster?
Let say company x makes massively multiplayer online strategy games. The game y is updated adding a feature z, but developers forgot to add server-side verification or it was bypassed (using alternative UI). Update allowed users to double their units as many times as they like. After about a day this bug was fixed. A lot of members had abused this bug - some by accident(?), others as much as possible. Damage has been done and extra units still remain.

The game has a cash shop where speedups, elite units, etc can be bought. Some members have spent hundreds of dollars to be among the best and played this game for several months if not years.

I want to know : what can be done, if rollback is not possible?

# Answer
> 8 votes
In this situation, after fixing the bug, the company has three options:

1. Ignore the problem. If it's a low-impact problem, just ignore that it's happened. Ill-gotten gains remain ill-gotten. This is by far the easiest option (and in practice, the one which is used the most frequently), but if customers are really upset about the problem, it might not be the best one.
2. Roll-back the game state to before the exploit happened. This can be extremely unpopular, and it can often be difficult to pinpoint exactly when the exploit started. The further in the past the exploit began, the more painful this option will be for the customer base. But if it's only a few hours, then this is probably a reasonable option.
3. Try to fix the problem on a case-by-case basis, using server log analysis. In this approach, you analyse your server logs to figure out where exploits happened, and undo those exploits in a post-hoc manner. This is the approach that customers are usually happiest with, as long as your server logs allow you to do it accurately and fairly. (This is just one reason why verbose and detailed server logs are critically important for online multiplayer games!)

Note that if your game is commercial, there are potentially legal issues with both #2 and #3 above; accidentally wiping out goods which were purchased with real money can get you in a lot of real-world trouble. So check with lawyers in your jurisdiction in that situation.

As Michael Madsen mentions, Warnings and bans are an option for punishing users who engage in exploits. But they don't actually fix the problem introduced into the game by the exploit; they just punish the people responsible.

# Answer
> 3 votes
This will inherently depend on the exact situation, but usually, TOSes include something about exploitation of bugs being a bannable offense.

Whether or not the company bans everyone who ever did it, or only those where they are certain that they're deliberately exploiting (e.g. people who did it more than once) depends on the company and exact scenario.

For example, if it can be argued that it is quite easy to stumble across the bug by accident, then you may well make the situation worse by banning *everyone* who has done it - because it stands to reason that not everyone did it on purpose, and if you ban those accidental violators, it comes off as a bastard move.

If you can't reasonably figure out who to ban, the best choice may be to just admit it and apologize profusely to your player base, possibly offering some sort of compensation for the screw up, and just leave it at that.

Regardless, you should then figure out how it came to this situation, and then take steps to avoid that in the future. You don't want this sort of thing happening again.

---
Tags: security
---


# Question
Title: How can I get the texture color data from GLEED2D's level file?
I've hit a little snag in my game. It's a 2D platform game and I need to check for collisions against the level. I'm using GLEED2D to create the map.

I'd like to do per-pixel collision checking, but I don't know how to get the texture color values out of the Level.cs file provided by GLEED2D.

If any one can point me in the right direction that be great -- or if they're are any better level mapping programs with similar features as GLEED2D that would be better to use for this type of game, that would be helpful as well.

# Answer
**Step 1 - Making the Textures accessible from Level.cs**

The texture for each item is being stored inside the `TextureItem` class inside `Level.cs`. You should be able find something like this on your file:

```
public partial class TextureItem : Item
{
    Texture2D texture;

    public override void load(ContentManager cm)
    {
        // Your load implementation
    }
}

```

Now, start by making it public:

```
public partial class TextureItem : Item
{
    public Texture2D Texture;

    public override void load(ContentManager cm)
    {
        // Your load implementation
    }
}

```

And then it's simply a matter of acessing the texture directly. Example:

```
Level level = Level.FromFile("map.xml", Content);

foreach(Layer layer in level.Layers)
{
    foreach(Item item in layer.Items)
    {
        ImageItem imageItem = item as ImageItem;
        if(imageItem != null)
        {
            Texture2D texture = imageItem.Texture;
            // Do something with texture, such as per pixel collision detection
        }
    }
}

```

**Step 2 - Handling per-pixel collision detection in XNA**

In case you're not familiar with this process, here's two good references on the topic:

1. Collision Series 2: 2D Per-Pixel Collision to learn how to implement the basics in XNA. The core feature needed is pretty much the Texture.GetData() method which allows you to get back pixel color information from any texture.
2. Sonic Physics Guide which describes physics in Sonic games. They also used per-pixel collision detection with the terrain so you might be able to get some tips out of it.
> 1 votes

---
Tags: xna, c#, textures, color
---


title: objective-c iphone sdk side scrolling

text:
# Question
Title: objective-c iphone sdk side scrolling
I was making a game and I did the side scrolling like this: if the player get past 150, the player stops moving and the background starts moving. But thats very annoying with placing objects in the game. Isn't there a better way to do this? I do not want to use cocos2D.

Thanks!

# Answer
Why not just have a utility function to get a "absolute" position from a given "player-relative" position, and have the best of both worlds?

So, the player is standing still and the background moves instead, then the player can be said to always be at origin point (0,0). So, if you wanted to place an enemy 50 units ahead of the player, you place them at (50,0). However, if you wanted to place them at an absolute world positions, then you'd want to place them relative to the background's position (since it's been moving backwards the entire time, its position is indicative of how far into the level the player is), so, you'd write a function such as: GetAbsolutePos(x,y){absX = x-background.x; ...}. That way, you can do either.
> 1 votes

---
Tags: 2d, iphone, objective-c, platformer
---


# Question
Title: How can I convert an OBJ model into arrays of vertices and indices?
I'm writing a simple model loader just to learn how models are loaded. I wrote a program to convert .OBJ files in a custom format. (It's virtually exactly the same as .OBJ, I wrote it once again just for learning). I can load all the data into `std::vector`s but I don't know how to put it into an array of vertices and indices, so it's rendering wrong. Here's how it turns out with no culling and wireframe enabled (it's supposed to be a sphere, and that L shape in the middle isn't part of the model):

When I tell it to render a point list, all the vertices are there in the right places. However, they don't seem to form faces correctly...

This is the code that renders them:

```
    //=========================================================
    // CONVERT THE DATA INTO SOMETHING USABLE
    //=========================================================

    bool isDuplicate;
    for(int i = 0; i < polygonCount; i++)
    {
        for(int i2 = 0; i2 < 3; i2++)
        {
            isDuplicate = false;
            isCreated = false;
            selectedVertex = faceDefinitions[i].vertexIndexes[i2];

            for(int i3 = 0; i3 < vertexCount; i3++)
            {
                if(modelData->vertices[i3].position == vertexPositions[selectedVertex])
                {
                    if(modelData->vertices[i3].texture == D3DXVECTOR2(0,0))
                    {
                        indices[selectedVertex] = i3;
                        isDuplicate = true;
                        break;
                    }
                }
            }

            if(isDuplicate)
                continue;

            indices[selectedVertex] = selectedVertex;

            modelData->vertices[selectedVertex].position = vertexPositions[selectedVertex];
            modelData->vertices[selectedVertex].normal = vertexNormals[faceDefinitions[i].normalIndexes[i2]];
            modelData->vertices[selectedVertex].texture = D3DXVECTOR2(0,0);
        }
    }

    modelData->indices = indices;

```

I know there's a way to do it but I can't seem to wrap my head around it. I've rewritten it probably 5 times, but I always get the same result.

Here's the ModelData structure:

```
struct ModelData
{
    int vertexCount;
    int normalCount;
    int faceCount;
    unsigned long* indices;
    EntityBase::VertexType* vertices;
    int errorCode;
};

```

The FaceDefinition structure contains the the indices of the vertices positions, normals, and texture coords. I haven't implemented texture coords yet, though.

```
struct FaceDefinition
{
    int vertexIndexes[3];
    int textureIndexes[3];
    int normalIndexes[3];
};

```

Here is the entire function, just for clarity:

```
ModelData* CModelLoader::LoadModel(WCHAR* modelName)
{
    ifstream loaderStream(Application::FileSystem::GetFileLocation(FILE_TYPE_MODEL,modelName));

    ModelData* modelData = new ModelData;

    vector<D3DXVECTOR3> vertexPositions;
    vector<D3DXVECTOR3> vertexNormals;
    vector<D3DXVECTOR3> vertexTextureCoords;
    vector<int> setVertices;
    vector<FaceDefinition> faceDefinitions;
    vector<string> tokens;
    vector<string> faceToken;
    int vertexCount = 0, normalCount = 0, polygonCount = 0;
    unsigned long *indices;
    int selectedVertex;
    bool isCreated;

    string input;
    string currentToken;
    string currentFaceToken;
    std::istringstream streamReader;
    std::istringstream faceReader;
    D3DXVECTOR3 tempVector;
    FaceDefinition tempFace;

    modelData->errorCode = ERR_NO_ERROR;

    if(!loaderStream)
        modelData->errorCode = ERR_COULD_NOT_OPEN;
    else
    {
        while(std::getline(loaderStream, input))
        {
            streamReader.clear();
            streamReader.str(input);
            tokens.clear();
            while(std::getline(streamReader, currentToken, ' '))
            {
                tokens.push_back(currentToken);
            }
            if(tokens.size() < 1)
                continue;

            if(tokens[0] == "VERTEX")
            {
                vertexCount++;
                if(tokens.size() >= 4)
                {
                    tempVector = D3DXVECTOR3(0,0,0);
                    tempVector.x = (float) atof(tokens[1].c_str());
                    tempVector.y = (float) atof(tokens[2].c_str());
                    tempVector.z = (float) atof(tokens[3].c_str());
                    vertexPositions.push_back(tempVector);
                    continue;
                }
                else
                {
                    vertexPositions.push_back(D3DXVECTOR3(0,0,0)); //give it a bad vertex, because we received a bad vertex
                }
            }
            if(tokens[0] == "VERTEX_NORMAL")
            {
                normalCount++;
                if(tokens.size() >= 4)
                {
                    tempVector = D3DXVECTOR3(0,0,0);
                    tempVector.x = (float) atof(tokens[1].c_str());
                    tempVector.y = (float) atof(tokens[2].c_str());
                    tempVector.z = (float) atof(tokens[3].c_str());
                    vertexNormals.push_back(tempVector);
                    continue;
                }
                else
                {
                    vertexNormals.push_back(D3DXVECTOR3(0,0,0)); //give it a bad normal, because we received a bad normal
                }
            }
            if(tokens[0] == "FACE")
            {
                polygonCount++;
                if(tokens.size() == 4) //sorry, but non triangles aren't worth the time
                {
                    tempFace = FaceDefinition();

                    //vertex 1
                    faceReader.clear();
                    faceReader.str(tokens[1]);
                    faceToken.clear();
                    while(std::getline(faceReader, currentFaceToken, ','))
                    {
                        faceToken.push_back(currentFaceToken);
                    }
                    if(faceToken.size() == 3) //should have all the info, or, same as above, its not worth the time
                    {
                        tempFace.vertexIndexes[0]  = atoi(faceToken[0].c_str()) - 1;
                        tempFace.textureIndexes[0] = atoi(faceToken[1].c_str()) - 1;
                        tempFace.normalIndexes[0]  = atoi(faceToken[2].c_str()) - 1;
                    }

                    //vertex 2
                    faceReader.clear();
                    faceReader.str(tokens[2]);
                    faceToken.clear();
                    while(std::getline(faceReader, currentFaceToken, ','))
                    {
                        faceToken.push_back(currentFaceToken);
                    }
                    if(faceToken.size() == 3) //should have all the info, or, same as above, its not worth the time
                    {
                        tempFace.vertexIndexes[1]  = atoi(faceToken[0].c_str()) - 1;
                        tempFace.textureIndexes[1] = atoi(faceToken[1].c_str()) - 1;
                        tempFace.normalIndexes[1]  = atoi(faceToken[2].c_str()) - 1;
                    }

                    //vertex 3
                    faceReader.clear();
                    faceReader.str(tokens[3]);
                    faceToken.clear();
                    while(std::getline(faceReader, currentFaceToken, ','))
                    {
                        faceToken.push_back(currentFaceToken);
                    }
                    if(faceToken.size() == 3) //should have all the info, or, same as above, its not worth the time
                    {
                        tempFace.vertexIndexes[2]  = atoi(faceToken[0].c_str()) - 1;
                        tempFace.textureIndexes[2] = atoi(faceToken[1].c_str()) - 1;
                        tempFace.normalIndexes[2]  = atoi(faceToken[2].c_str()) - 1;
                    }

                    faceDefinitions.push_back(tempFace);
                }
                //if we receive a bad face, we just wont read it
            }
        }
    }

    indices = new unsigned long[vertexCount];

    modelData->faceCount = polygonCount;
    modelData->normalCount = normalCount;
    modelData->vertexCount = vertexCount;
    modelData->vertices = new EntityBase::VertexType[vertexCount];

    //< ^^everything up here works^^ >
    //=========================================================
    // CONVERT THE DATA INTO SOMETHING USABLE
    //=========================================================

    //now is the boring part, creating the vertex list...

    bool isDuplicate;
    for(int i = 0; i < polygonCount; i++)
    {
        for(int i2 = 0; i2 < 3; i2++)
        {
            isDuplicate = false;
            isCreated = false;
            selectedVertex = faceDefinitions[i].vertexIndexes[i2];

            for(int i3 = 0; i3 < vertexCount; i3++)
            {
                if(modelData->vertices[i3].position == vertexPositions[selectedVertex])
                {
                    if(modelData->vertices[i3].texture == D3DXVECTOR2(0,0))
                    {
                        indices[selectedVertex] = i3;
                        isDuplicate = true;
                        break;
                    }
                }
            }

            if(isDuplicate)
                continue;

            indices[selectedVertex] = selectedVertex;

            modelData->vertices[selectedVertex].position = vertexPositions[selectedVertex];
            modelData->vertices[selectedVertex].normal = vertexNormals[faceDefinitions[i].normalIndexes[i2]];
            modelData->vertices[selectedVertex].texture = D3DXVECTOR2(0,0);
        }
    }

    modelData->indices = indices;

    return modelData;
}

```

This is there sphere models file:

```
#Vertex Info

VERTEX_COUNT:62
NORMAL_COUNT:62
FACE_COUNT:120

VERTEX 0 19.5 0
VERTEX 0 -19.5 0
VERTEX 9.75 -16.887495 0
VERTEX 8.443748 -16.887495 4.875
VERTEX 4.875 -16.887495 8.443748
VERTEX 0 -16.887495 9.75
VERTEX -4.875 -16.887495 8.443748
VERTEX -8.443748 -16.887495 4.875
VERTEX -9.75 -16.887495 0
VERTEX -8.443748 -16.887495 -4.875
VERTEX -4.875 -16.887495 -8.443748
VERTEX 0 -16.887495 -9.75
VERTEX 4.875 -16.887495 -8.443748
VERTEX 8.443748 -16.887495 -4.875
VERTEX 16.887497 -9.75 0
VERTEX 14.625001 -9.75 8.443748
VERTEX 8.443748 -9.75 14.625
VERTEX 0 -9.75 16.887497
VERTEX -8.443748 -9.75 14.625
VERTEX -14.625001 -9.75 8.443748
VERTEX -16.887497 -9.75 0
VERTEX -14.625001 -9.75 -8.443748
VERTEX -8.443748 -9.75 -14.625
VERTEX 0 -9.75 -16.887497
VERTEX 8.443748 -9.75 -14.625
VERTEX 14.625001 -9.75 -8.443748
VERTEX 19.5 1E-06 0
VERTEX 16.887495 1E-06 9.75
VERTEX 9.75 1E-06 16.887495
VERTEX 0 1E-06 19.5
VERTEX -9.75 1E-06 16.887495
VERTEX -16.887495 1E-06 9.75
VERTEX -19.5 1E-06 0
VERTEX -16.887495 1E-06 -9.75
VERTEX -9.75 1E-06 -16.887497
VERTEX 0 1E-06 -19.5
VERTEX 9.75 1E-06 -16.887497
VERTEX 16.887495 1E-06 -9.75
VERTEX 16.887495 9.750001 0
VERTEX 14.624999 9.750001 8.443748
VERTEX 8.443748 9.750001 14.625
VERTEX 0 9.750001 16.887495
VERTEX -8.443748 9.750001 14.625
VERTEX -14.624999 9.750001 8.443748
VERTEX -16.887495 9.750001 0
VERTEX -14.624999 9.750001 -8.443748
VERTEX -8.443748 9.750001 -14.625
VERTEX 0 9.750001 -16.887497
VERTEX 8.443748 9.750001 -14.625
VERTEX 14.624999 9.750001 -8.443748
VERTEX 9.750001 16.887495 0
VERTEX 8.443748 16.887495 4.875
VERTEX 4.875 16.887495 8.443748
VERTEX 0 16.887495 9.750001
VERTEX -4.875 16.887495 8.443748
VERTEX -8.443748 16.887495 4.875
VERTEX -9.750001 16.887495 0
VERTEX -8.443748 16.887495 -4.875
VERTEX -4.875 16.887495 -8.443748
VERTEX 0 16.887495 -9.750002
VERTEX 4.875 16.887495 -8.443748
VERTEX 8.443748 16.887495 -4.875

# Vertex Normals!

VERTEX_NORMAL 0 -1 0
VERTEX_NORMAL 0.573584 -0.819147 0
VERTEX_NORMAL 0.431481 -0.867044 0.249116
VERTEX_NORMAL 0 1 0
VERTEX_NORMAL 0.431481 0.867044 0.249116
VERTEX_NORMAL 0.573584 0.819147 0
VERTEX_NORMAL 0.286792 -0.819147 0.496738
VERTEX_NORMAL 0.286792 0.819147 0.496738
VERTEX_NORMAL 0 -0.867044 0.498231
VERTEX_NORMAL 0 0.867044 0.498231
VERTEX_NORMAL -0.286792 -0.819147 0.496738
VERTEX_NORMAL -0.286792 0.819147 0.496738
VERTEX_NORMAL -0.431481 -0.867044 0.249116
VERTEX_NORMAL -0.431481 0.867044 0.249116
VERTEX_NORMAL -0.573584 -0.819147 0
VERTEX_NORMAL -0.573584 0.819147 0
VERTEX_NORMAL -0.431481 -0.867044 -0.249116
VERTEX_NORMAL -0.431481 0.867044 -0.249116
VERTEX_NORMAL -0.286792 -0.819147 -0.496738
VERTEX_NORMAL -0.286792 0.819147 -0.496738
VERTEX_NORMAL 0 -0.867044 -0.498231
VERTEX_NORMAL 0 0.867044 -0.498231
VERTEX_NORMAL 0.286792 -0.819147 -0.496738
VERTEX_NORMAL 0.286792 0.819147 -0.496738
VERTEX_NORMAL 0.431481 -0.867044 -0.249116
VERTEX_NORMAL 0.431481 0.867044 -0.249116
VERTEX_NORMAL 0.865033 -0.501714 0
VERTEX_NORMAL 0.749141 -0.501714 0.432517
VERTEX_NORMAL 0.432517 -0.501714 0.749141
VERTEX_NORMAL 0 -0.501714 0.865033
VERTEX_NORMAL -0.432517 -0.501714 0.749141
VERTEX_NORMAL -0.749141 -0.501714 0.432517
VERTEX_NORMAL -0.865033 -0.501714 0
VERTEX_NORMAL -0.749141 -0.501714 -0.432517
VERTEX_NORMAL -0.432517 -0.501714 -0.749141
VERTEX_NORMAL 0 -0.501714 -0.865033
VERTEX_NORMAL 0.432517 -0.501714 -0.749141
VERTEX_NORMAL 0.749141 -0.501714 -0.432517
VERTEX_NORMAL 1 0 0
VERTEX_NORMAL 0.866025 0 0.5
VERTEX_NORMAL 0.5 0 0.866025
VERTEX_NORMAL 0 0 1
VERTEX_NORMAL -0.5 0 0.866025
VERTEX_NORMAL -0.866025 0 0.5
VERTEX_NORMAL -1 0 0
VERTEX_NORMAL -0.866025 0 -0.5
VERTEX_NORMAL -0.5 0 -0.866025
VERTEX_NORMAL 0 0 -1
VERTEX_NORMAL 0.5 0 -0.866025
VERTEX_NORMAL 0.866025 0 -0.5
VERTEX_NORMAL 0.865033 0.501714 0
VERTEX_NORMAL 0.749141 0.501714 0.432517
VERTEX_NORMAL 0.432517 0.501714 0.749141
VERTEX_NORMAL 0 0.501714 0.865033
VERTEX_NORMAL -0.432517 0.501714 0.749141
VERTEX_NORMAL -0.749141 0.501714 0.432517
VERTEX_NORMAL -0.865033 0.501714 0
VERTEX_NORMAL -0.749141 0.501714 -0.432517
VERTEX_NORMAL -0.432517 0.501715 -0.749141
VERTEX_NORMAL 0 0.501714 -0.865033
VERTEX_NORMAL 0.432517 0.501715 -0.749141
VERTEX_NORMAL 0.749141 0.501714 -0.432517

# Face Definitions!

FACE 2,1,1 3,2,2 4,3,3
FACE 1,4,4 52,5,5 51,6,6
FACE 2,7,1 4,3,3 5,8,7
FACE 1,9,4 53,10,8 52,5,5
FACE 2,11,1 5,8,7 6,12,9
FACE 1,13,4 54,14,10 53,10,8
FACE 2,15,1 6,12,9 7,16,11
FACE 1,17,4 55,18,12 54,14,10
FACE 2,19,1 7,16,11 8,20,13
FACE 1,21,4 56,22,14 55,18,12
FACE 2,23,1 8,20,13 9,24,15
FACE 1,25,4 57,26,16 56,22,14
FACE 2,27,1 9,24,15 10,28,17
FACE 1,29,4 58,30,18 57,26,16
FACE 2,31,1 10,28,17 11,32,19
FACE 1,33,4 59,34,20 58,30,18
FACE 2,35,1 11,32,19 12,36,21
FACE 1,37,4 60,38,22 59,34,20
FACE 2,39,1 12,36,21 13,40,23
FACE 1,41,4 61,42,24 60,38,22
FACE 2,43,1 13,40,23 14,44,25
FACE 1,45,4 62,46,26 61,42,24
FACE 2,47,1 14,44,25 3,48,2
FACE 1,49,4 51,50,6 62,46,26
FACE 3,2,2 15,51,27 16,52,28
FACE 3,2,2 16,52,28 4,3,3
FACE 4,3,3 16,52,28 5,8,7
FACE 16,52,28 17,53,29 5,8,7
FACE 5,8,7 17,53,29 18,54,30
FACE 5,8,7 18,54,30 6,12,9
FACE 6,12,9 18,54,30 7,16,11
FACE 18,54,30 19,55,31 7,16,11
FACE 7,16,11 19,55,31 20,56,32
FACE 7,16,11 20,56,32 8,20,13
FACE 8,20,13 20,56,32 9,24,15
FACE 20,56,32 21,57,33 9,24,15
FACE 9,24,15 21,57,33 22,58,34
FACE 9,24,15 22,58,34 10,28,17
FACE 10,28,17 22,58,34 11,32,19
FACE 22,58,34 23,59,35 11,32,19
FACE 11,32,19 23,59,35 24,60,36
FACE 11,32,19 24,60,36 12,36,21
FACE 12,36,21 24,60,36 13,40,23
FACE 24,60,36 25,61,37 13,40,23
FACE 13,40,23 25,61,37 26,62,38
FACE 13,40,23 26,62,38 14,44,25
FACE 14,44,25 26,62,38 3,48,2
FACE 26,62,38 15,63,27 3,48,2
FACE 15,51,27 27,64,39 16,52,28
FACE 27,64,39 28,65,40 16,52,28
FACE 16,52,28 28,65,40 29,66,41
FACE 16,52,28 29,66,41 17,53,29
FACE 17,53,29 29,66,41 18,54,30
FACE 29,66,41 30,67,42 18,54,30
FACE 18,54,30 30,67,42 31,68,43
FACE 18,54,30 31,68,43 19,55,31
FACE 19,55,31 31,68,43 20,56,32
FACE 31,68,43 32,69,44 20,56,32
FACE 20,56,32 32,69,44 33,70,45
FACE 20,56,32 33,70,45 21,57,33
FACE 21,57,33 33,70,45 22,58,34
FACE 33,70,45 34,71,46 22,58,34
FACE 22,58,34 34,71,46 35,72,47
FACE 22,58,34 35,72,47 23,59,35
FACE 23,59,35 35,72,47 24,60,36
FACE 35,72,47 36,73,48 24,60,36
FACE 24,60,36 36,73,48 37,74,49
FACE 24,60,36 37,74,49 25,61,37
FACE 25,61,37 37,74,49 26,62,38
FACE 37,74,49 38,75,50 26,62,38
FACE 26,62,38 38,75,50 27,76,39
FACE 26,62,38 27,76,39 15,63,27
FACE 27,64,39 39,77,51 40,78,52
FACE 27,64,39 40,78,52 28,65,40
FACE 28,65,40 40,78,52 29,66,41
FACE 40,78,52 41,79,53 29,66,41
FACE 29,66,41 41,79,53 42,80,54
FACE 29,66,41 42,80,54 30,67,42
FACE 30,67,42 42,80,54 31,68,43
FACE 42,80,54 43,81,55 31,68,43
FACE 31,68,43 43,81,55 44,82,56
FACE 31,68,43 44,82,56 32,69,44
FACE 32,69,44 44,82,56 33,70,45
FACE 44,82,56 45,83,57 33,70,45
FACE 33,70,45 45,83,57 46,84,58
FACE 33,70,45 46,84,58 34,71,46
FACE 34,71,46 46,84,58 35,72,47
FACE 46,84,58 47,85,59 35,72,47
FACE 35,72,47 47,85,59 48,86,60
FACE 35,72,47 48,86,60 36,73,48
FACE 36,73,48 48,86,60 37,74,49
FACE 48,86,60 49,87,61 37,74,49
FACE 37,74,49 49,87,61 50,88,62
FACE 37,74,49 50,88,62 38,75,50
FACE 38,75,50 50,88,62 27,76,39
FACE 50,88,62 39,89,51 27,76,39
FACE 39,77,51 51,6,6 40,78,52
FACE 51,6,6 52,5,5 40,78,52
FACE 40,78,52 52,5,5 53,10,8
FACE 40,78,52 53,10,8 41,79,53
FACE 41,79,53 53,10,8 42,80,54
FACE 53,10,8 54,14,10 42,80,54
FACE 42,80,54 54,14,10 55,18,12
FACE 42,80,54 55,18,12 43,81,55
FACE 43,81,55 55,18,12 44,82,56
FACE 55,18,12 56,22,14 44,82,56
FACE 44,82,56 56,22,14 57,26,16
FACE 44,82,56 57,26,16 45,83,57
FACE 45,83,57 57,26,16 46,84,58
FACE 57,26,16 58,30,18 46,84,58
FACE 46,84,58 58,30,18 59,34,20
FACE 46,84,58 59,34,20 47,85,59
FACE 47,85,59 59,34,20 48,86,60
FACE 59,34,20 60,38,22 48,86,60
FACE 48,86,60 60,38,22 61,42,24
FACE 48,86,60 61,42,24 49,87,61
FACE 49,87,61 61,42,24 50,88,62
FACE 61,42,24 62,46,26 50,88,62
FACE 50,88,62 62,46,26 51,50,6
FACE 50,88,62 51,50,6 39,89,51

```

# Answer
> 2 votes
Ok, I solved it...

I simply had to change the code that fills the buffers to this:

```
    bool isDuplicate;
    indices.clear();
    for(int i = 0; i < polygonCount; i++)
    {
        for(int i2 = 0; i2 < 3; i2++)
        {
            indices.push_back(faceDefinitions[i].vertexIndexes[i2]);
        }
    }

    modelData->indices = new unsigned long[indices.size()];
    modelData->indexCount = indices.size();

    for(int i = 0; i < vertexCount; i++)
    {
        modelData->vertices[i].position = vertexPositions[i];
    }

    for(unsigned long i = 0; i < indices.size(); i++)
    {
        modelData->indices[i]  = indices[i];
    }

```

So it was an indexing error in the end...

# Answer
> 0 votes
Here are two little c++ functions from my project. I tried to make them readable without knowledge of my code. Just know the ObjImporter class is a container for the information read from the obj file.

They essentially use a map to store every unique vertex generated by the face list. In order to do this, a hash value has to be generated from the position, texture, and normal indices. My implementation just uses two random constants that work for my obj files. If your files are larger, there is a chance that you may get hash collisions which will place incorrect vertices in your index buffer so adjust them as needed. The hash key is mapped to the index of the vertex in the vertex buffer.

Once you know how to hash your vertices from the indices, you can use this to check if a vertex already exist in your vertex buffer. If it does then you have it's index into the buffer from the map and if it isn't you know that you can append the vertex to the buffers.

The second function is dependent upon your vertex drawing type. My implementation below assumes you are using triangle list. (Two triangles for each quad)

```
// Description -
// Given an index to a vertex, that vertex is then checked using a map to determine if
// it is in the vertex buffer already. If it is then it's index is just appended to the index
// buffer, if it isn't than the vertex is appended to the map and both the index and vertex buffers
// Parameters -
// _vBuffer - Vector containing the vertex buffer you are building.
// _iBuffer - Vector containing the index buffer you are building.
// _vMap    - Map that uses a hash value to determine if a vertex is already in the buffer. <Key,Value> = <HashValue, vertexBufferIndex>
// _faceIndex   - Index into an array of faces containing position, normal, and texture value indices. Face list provided by obj file.
// _vertexIndex - Index into the face object.
// _import - Container object for the face and vertex array from the obj file. Class was responsible for reading and storing the obj file.
void ImportVertex(std::vector<VERTEX> &_vBuffer, std::vector<unsigned int> &_iBuffer, std::map<unsigned int, unsigned int> &_vMap,
    const unsigned int _faceIndex, const unsigned int _vertexIndex, const ObjImporter &_import) {

    // Vertex that will be pushed onto the vertex buffer vector.
    static VERTEX _vTemp;

    // Get the indices from the face for the vertex.
    int _vPosIndex = _import.GetFaceIndexPtr(_faceIndex)->GetVertexPositionIndex(_vertexIndex);
    int _vNorIndex = _import.GetFaceIndexPtr(_faceIndex)->GetVertexNormalIndex(_vertexIndex);
    int _vTexIndex = _import.GetFaceIndexPtr(_faceIndex)->GetVertexTextureIndex(_vertexIndex);

    // Initially build the key from just the position.
    unsigned int _vKey = _vPosIndex;

    // Set the position using the index from the face.
    _vTemp.SetPosition(_import.GetVertexPositionPtr(_vPosIndex));

    // If you have a normal index and value.
    // My importer fills the indices with -1 if they don't exist.
    if (_vNorIndex >= 0) {
        _vTemp.SetNormal(_import.GetVertexNormalPtr(_vNorIndex));
        // Append the key value multiplied by a constant.
        // This constant is dependent upon the size of your obj file and it must be unique for
        // each different vertex.
        _vKey += _vNorIndex * 1000;
    } else _vTemp.SetNormal(0.0f, 0.0f, 0.0f);

    if (_vTexIndex >= 0) {
        _vTemp.SetTexture(_import.GetVertexTexturePtr(_vTexIndex));
        // Append the key value with the texture index scaled by
        // a higher constant.
        _vKey += _vTexIndex * 1000000;
    } else _vTemp.SetTexture(0.0f, 0.0f, 0.0f);

    // Check to see if the map already contains the key generated.
    if (_vMap.count(_vKey) == 0) {
        // Since the vertex is new it will be at the end of the vector.
        // Map it's key to it's position.
        _vMap[_vKey] = _vBuffer.size();
        // Push back the vertex onto the vertex buffer vector.
        _iBuffer.push_back(_vBuffer.size());
        // Push back the index of this vertex onto the index buffer.
        _vBuffer.push_back(_vTemp);
    // If the vertex is already in the map and hence in the vertex buffer,
    // then just add it's index to the index buffer.
    } else _iBuffer.push_back(_vMap[_vKey]);
}

// Description -
// Given an obj file, the faces are iterated through and used to build a triangle list
// vertex buffer.
void Import(const ObjImporter &_import) {
    // Vectors are used to build the index and vertex buffers
    std::vector<RENDEROBJECT_DEFAULT_VERTEX>  _vAggregateBuffer;
    std::vector<unsigned int> _iAggregateBuffer;
    std::map<unsigned int, unsigned int> _vMap;

    // Iterate through every face in the obj file.
    for (unsigned int i = 0; i < _import.GetFaceCount(); ++i) {
        // If it's a triangle.
        if (_import.GetFaceIndexPtr(i)->GetVertexCount() == 3)
            // Grab each vertex
            for (int k = 0; k < 3; ++k)
                ImportVertex(_vAggregateBuffer, _iAggregateBuffer, _vMap, i, k, _import);
        // Else assumes a quad was provided.
        else {
            // Grab each vertex. This is dependent upon vertex drawing type.
            // The order below assumes a triangle list.
            ImportVertex(_vAggregateBuffer, _iAggregateBuffer, _vMap, i, 0, _import);
            ImportVertex(_vAggregateBuffer, _iAggregateBuffer, _vMap, i, 1, _import);
            ImportVertex(_vAggregateBuffer, _iAggregateBuffer, _vMap, i, 2, _import);
            ImportVertex(_vAggregateBuffer, _iAggregateBuffer, _vMap, i, 2, _import);
            ImportVertex(_vAggregateBuffer, _iAggregateBuffer, _vMap, i, 3, _import);
            ImportVertex(_vAggregateBuffer, _iAggregateBuffer, _vMap, i, 0, _import);
        }
    }
}

```

---
Tags: c++, models, directx11
---


# Question
Title: No response to touch from XNA page after navigated from Silverlight page
I am creating XNA/Silverlight game in Windows Phone Mango. Testing with the emulator in both the Release and Debug mode.

From the main page, I call a settings page written in Silverlight. Then I back out without making any changes. I enter the XNA page, the touch does not work properly.

If I start the app, then enter the XNA page straight from the main page, the touch does work.

In `OnNavigatedTo`:

```
TouchPanel.EnabledGestures = GestureType.Tap

```

Calling the settings page from main page:

```
NavigationService.Navigate( new Uri("/Pages/SettingPage.xaml", UriKind.Relative));

```

Games.cs buttons tap detection (only the detection lines):

```
while (TouchPanel.IsGestureAvailable && ! actionFound)
{
    GestureSample gestureSample = TouchPanel.ReadGesture();
    if (gestureSample.GestureType == GestureType.Tap)
    {
        // do work
    }
}

```

I add breakpoints in the 'do work' sections, it only gets hit after 3-4 taps.

I change the settings page to embedded Silverlight on XNA page, the same problem happens.

Just to make sure the timer is working, I change one of the sprites to move up and down in `OnDraw`. The sprite moves OK in both cases.

I been stuck on this for two days, and I got three more pages to code I need to call for a proper game.

Thanks in advance for any help.

# Answer
Really hard to tell given the information you've shared, but I would check to make sure that you don't have a Silverlight control sitting on top of your game eating the input events. If you have any controls in the game's XAML try setting IsHitTestVisible to false. Likewise try doing the same for controls in Settings.xaml.

Some other thoughts:

* How are you "backing out" from Settings.xaml?
* What happens if you only set Gestures once? i.e. not every time you navigate to the page.
* Have you tried checking MouseState, does it work? (To enable set Tap gesture enabled then check Mouse.GetState().
* Is it possible the !actionFound condition in your while loop is causing problems?
> 1 votes

---
Tags: xna, windows-phone-7, silverlight
---


# Question
Title: How can I create a 'SdkTrayManager' without 'OIS::Mouse'?
An `OIS::Mouse` is required to create an `SdkTrayManager`:

```
// Constructor in SdkTray.h
SdkTrayManager(const Ogre::String& name, Ogre::RenderWindow* window,
    OIS::Mouse* mouse, SdkTrayListener* listener = 0) :

```

However, it's only used in the `refreshCursor` method:

```
mCursor->setPosition(mMouse->getMouseState().X.abs, mMouse->getMouseState().Y.abs);

```

Is there was a way to only pass `X.abs` and `Y.abs` to the manager, instead of a pointer?

# Answer
> 3 votes
If that's what `SdkTrayManager` uses, then that's what `SdkTrayManager` uses. There's no getting around it without actually modifying the code.

---
Tags: ogre
---


title: Is "pure" OpenGL productive enough?

text:
# Question
Title: Is "pure" OpenGL productive enough?
I know that this is a difficult question and I hope I can convey my meaning. Over time I've used many different engines from XNA over Unity to Panda3d and even tried native directX once. My final impression is that an engine basically serves to do this:

* implement a scene graph
* offer classes like actor to add them to the scene graph
* implement an asset pipeline that exports to actors or something similar
* allow for custom logic scripts that hook onto the engine and are called at the right times. In Unity you can override update() in panda3d you can add methods to the taskmanager that are then called repeatedly. In Jmonkey they are called controls. It's basically the same. Additionally you can listen to physics events and the like.
* then there's work done under the hood: physics, rendering and networking.

I appreciate all of these points very much and acknowledge the comfort a good engine can offer. The problem is: I'd like to create a game in a comparably young language (Google's Go) and there's no engine out there yet. Bindings for OpenGL exist and I figure I could easily hack a little engine of my own together.

The points one, two and four are not too difficult. I'd do the rendering with custom shaders anyways so that's work that has to be done in any case. For now I don't need complex physics and the standard raycast and collision check wouldn't be too hard for me. The only problem is an asset pipeline because I've got no experience in processing 3d data at all. I've only lived on the programmatical side up to now and the 3d models I've used were admittedly ugly. In the end it will probably add up to a weekend of coding and ongoing maintaining work.

The bottom-line is: I don't have to use go but then again there's no deadline for the project and I figured it might be fun to use this language. Is anyone out there still using "pure" OpenGL and can tell me about the work that lies ahead? Have you ever done this before?

**Do you think that low-level OpenGL is a too complex choice for a one-man team or does the work to hack together something of my own pay off in the end ?**

EDIT: You might want to read the comments below Nicol Bolas post since they explain the question a little better.

# Answer
Whether or not writing directly to OpenGL is "too complex" for a one-man team depends almost exclusively on who that one developer is.

Whether or not the work to hack something together will "pay off in the end" depends almost exclusively on what that one developer considers to be an acceptable payoff.

I've built my own game engine using raw OpenGL (including cross-platform support, sound, physics, memory management, etc). It took a lot of time. I never completed a major game with it. It certainly never "paid for itself" in monetary terms, but I learned a *lot* of things in the process. Did the choice pay off in the end?

Well, that depends on your point of view. And it's really not a question which anyone else can answer for you.
> 7 votes

# Answer
> The problem is: I'd like to create a game in a comparably young language (Google's Go) and there's no engine out there yet.

Then you need to make a decision: do you want to make a *game*, or do you want to program something in Go?

If you want to make a game, you should let questions like "what language do I use" influence you as little as possible. Yes, you will be avoiding languages that you don't know, but you should be focusing on languages that you *know*. You should do whatever it takes to follow the shortest path that allows you to get to the actual game making part of making a game.

If you just want to code something up in Go, then that's what you want to do.

> Do you think that low-level OpenGL is a too complex choice for a one-man team or does the work to hack together something of my own pay off in the end ?

It depends on what you're making.

For example, take a game like SpaceChem. You would get more or less nothing out of using a pre-packaged engine to make SpaceChem. It's basically a GUI-based game. Coding directly to OpenGL is simple and effective.

Asset conditioning for such a game is also simple, because there aren't any 3D models. It's just 2D flatcards running around. Physics is non-existent.

The same goes for many kinds of GUI-style games. Bejeweled, etc. Indeed, using an engine like Unity would make these kinds of games harder to make, not easier.

Now, if you're making something more graphically complex like an FPS as a one-man team, then yes, I would suggest using some form of library or engine to make things easier.

That being said, I think you do not understand that there are levels between "Unity" and "Use OpenGL". Unity is a full-fledged game engine, which means it has features like physics, scripting, entity support, etc. OpenGL is just a rendering system.

There are many levels between those two points. For example, you could build an engine with Ogre3D, Bullet Physics, and Lua, with some entity glue to put them all together. You still get an asset conditioning pipeline (courtesy of Ogre3D), and Bullet has most of your physics needs covered. Yes, you have to write the entity system and the various Lua hooks. But you have everything you need.
> 10 votes

# Answer
It depends on what you want to do. Building an engine takes time. If you're more interested in building an engine, exploring technology etc. than building a game, then go for it! But if your real goal is to build a game, and an engine is just a stepping stone to doing that, then maybe building your own engine isn't the best plan.

Plenty of people absolutely do use raw OpenGL and D3D. For example, some years ago I spent a lot of time building a set of OpenGL tech demos. These are in no way games, though, just an extremely simple programs and scenes built for the express purpose of showing off some technique. I don't consider it "uncomfortable" to use the raw API, but then I'm not trying to build a game.
> 4 votes

---
Tags: opengl, architecture
---


# Question
Title: Determine the stride of a DirectX Texture2D line?
Is there a way to determine, or preferably calculate/predict, the the stride of a line of a DirectX 11 Texture2D resource when using SharpDX?

(E.g. Can we say the stride of a line is always a power of 2?)

# Answer
> 4 votes
I don't know in which case you would like to do this, though I have two cases in mind:

1. If you are creating a Texture2D with an initial DataRectangle, the Pitch must be set to the number of bytes per row and is theoretically equal to TextureWidth * SharpDX.DXGI.FormatHelper.SizeOfInBytes(Format.XXX), unless you are laying out your data differently in memory.
2. If your are using DeviceContext.MapSubresource, you can't determine in advance what would be the stride and you need to use the Pitch returned by the DataBox.RowPitch. The stride could be hardware dependent, depending on the layout on the GPU memory.

---
Tags: directx, directx11, sharpdx
---


title: How to synchronize two components?

text:
# Question
Title: How to synchronize two components?
I have two components I'd like to connect them to each other.

1. PhysicalComponent
containing rigid body(position, rotation, velocity) and is holding body from physics engine.
2. GraphicsComponent
onscreen representation(position too, rotation too).

I'd like to sync this components, how to do it?

1. Read position, and rotation in GraphicsComonent from Physical comopnent.
2. Add one more component that sync them.

But problem is that I want to change on screen representation (other class such as PositionInerpolator do it, and it can work only with GraphicsComponent), and it must change physical body position. Is it a bad idea, and I must move physical body directly?

Thanks in advance.

# Answer
The way I handle it in my engine is to call a FixedUpdate() on all components when the fixed timestep physics frame ends, when the PhysicsComponent receives FixedUpdate() it will query for the rigid body position from the physics engine, if it finds a change in position since the last update it sends a message to itself saying its position has changed, and includes the new position in the message. This is a message type the RenderComponent listens for. When the RenderComponent receives the position it updates the position of the render mesh.

You're free to see the exact code for yourself if you would like, the engine is open-source, and is built on an Entity-\>Components hierarchy: http://quickstartengine.codeplex.com
> 2 votes

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