# Question
Title: XNA 4.0 - Mixing 3D and 2D - SpriteBatch putting weird alpha texture over whole scene
I am working on a game in XNA 4.0 that has been entirely in 3D so far but now I want to incorporate a HUD.

I have tried doing a simple test using spriteBatch as such:

```
spriteBatch.Begin();
spriteBatch.Draw(Player.Texture, new Rectangle(0, GameConstants.GraphicsDevice.Viewport.Height - 50, 50, 50), Color.White);
spriteBatch.End();

```

This works fine and the test texture shows as a rectangle in the correct position but the 3d World behind seems to have a sort of "haze" over the top which looks like the drawn "Player.Texture" has been put all over the viewport but at an alpha of like 0.1f.

I googled around and have a reset() function to change some of the GraphicsDevice properties back after drawing the SpriteBatch but nothing has changed and I haven't seen anyone else with this problem.

I thought it would be that SpriteBatch changes the blendmode to additive but in my reset() function I set the blendmode to opaque so I have no idea where this strange effect is coming from, it looks like I've ran some post-processing on the whole scene.

If I change the Player.Texture that is drawn in the SpriteBatch then the "haze" changes to look like the new texture so it is definitely to do with that.

Are there any other GraphicsDevice propterties I should check to change back?

**Edit**

Okay, I have just realised the "haze" over the top is from the SkySphere texture, I am using the MSDN skysphere shader from this tutorial.

So when I comment out the SkySphere code, the spritebatch and 3d drawing looks completely fine, but this leaves me with the problem that I can't have a SkySphere anymore.

Is there some reason why the skysphere is sort of drawn over the scene translucently rather than behind the 3D after I use a SpriteBatch? As I said before, it kind of looks like additive blending.

Below are 2 screenshots, the top is with spritebatch and no skysphere, below is with spritebatch and skysphere where I am having problems. I have cropped the images down to save upload (my internet is pretty slow at the moment) and I've changed the area of the scene in the 2nd image to show more clearly what it looks like. As I move around the scene with the camera the "haze" overlay stays in the same place exactly as how the SkySphere works, as in not taking into account the world matrix.

# Answer
> 1 votes
It looks like you're drawing your skysphere after your HUD. You should draw the skysphere after drawing the world (the depth buffer will save you a lot of overdraw), and draw the hud last.

---
Tags: xna, 2d, xna-4.0, spritebatch
---


# Question
Title: screen coordinate not working with pixel values
I have a very simple effect file shown below. I am using this to draw 2D lines, however it is not behaving how I expected and I can't seem to get my head round why.

If I draw a line that goes from 0,0 to 100, 100 for example, I would expect it to draw a line from one corner of the screen to a little way in. I would expect it to treat these numbers as screen coordinates. Instead, the line is huge! A line of about 2 long fills the whole screen. Why is this? How can I modify my shader to 'think' in screen coordinates?

```
// a struct for the vertex shader return value
struct VSOut
{
float4 Col : COLOR;    // vertex color
float4 Pos : SV_POSITION;    // vertex screen coordinates
};

// the vertex shader
VSOut VS(float4 Col : COLOR, float4 Pos : POSITION)
{
VSOut Output;
Output.Pos = Pos;    // set the vertex position to the input's position
Output.Col = Col;    // set the vertex color to the input's color

return Output;    // send the modified vertex data to the Rasterizer Stage
}

// the pixel shader
float4 PS(float4 Col : COLOR) : SV_TARGET
{
return Col;    // set the pixel color to the color passed in by the Rasterizer Stage
}

// the primary technique
technique10 Technique_0
{
// the primary pass
pass Pass_0
{
    SetVertexShader(CompileShader(vs_4_0, VS()));
    SetGeometryShader(NULL);
    SetPixelShader(CompileShader(ps_4_0, PS()));
}
}

```

# Answer
> 3 votes
Screen coordinates go from -1 to +1 along each axis. You can remap from pixel coordinates by doing

```
x = (x / screenWidthInPixels) * 2.0 - 1.0
y = (y / screenHeightInPixels) * 2.0 - 1.0

```

This could be done in the vertex shader, in which case you'd have to pass in the screen width and height as parameters, or you could do it on the app side when you fill the vertex buffer.

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


title: D3DXVec3Project returns odd values

text:
# Question
Title: D3DXVec3Project returns odd values
I would have thought that if the object is on-screen that this function should return screen coordinates. When used in conjunction with the directX draw text function, it works fine. Textual overlays track the 3D objects perfectly, however consider the following code:

```
D3DXVec3Project(&xyCoords, &HeadPosition(), &viewport, &matProjection, &matView, &matFinal);//for thought bubble

D3DXVECTOR2 origin = D3DXVECTOR2(
    (0.0f / SCREEN_WIDTH) * 2.0f - 1.0f,
    (0.0f / SCREEN_HEIGHT) * 2.0f - 1.0f);

D3DXVECTOR2 headPos = D3DXVECTOR2(
    (xyCoords.x / SCREEN_WIDTH) * 2.0f - 1.0f,
    (xyCoords.y / SCREEN_HEIGHT) * 2.0f - 1.0f);

lineRenderer.Draw2DLine(origin, headPos, D3DXCOLOR(1, 0, 0, 1), D3DXCOLOR(1, 1, 0, 1));

```

origin has a value of -1, -1 which is fine (texture coords for the screen go from -1 to 1 in each axis) but headPos has the value of -1.#IND000 in both the x and y. I think this may be because D3DXVec3Project is returning MASSIVE numbers, although I could be wrong.

Who knows what's going on under the hood of DrawText\_A in the following code, but it clearly compensates for whatevers not working with the above code.

```
D3DXVec3Project(&xyCoords, &HeadPosition(), &viewport, &matProjection, &matView, &matFinal);

    rct.left   = xyCoords.x;
    rct.right  = xyCoords.x;
    rct.top    = xyCoords.y;
    rct.bottom = xyCoords.y;

    m_font->DrawTextA(NULL, stateStream.str().c_str(), -1, &rct, DT_LEFT|DT_NOCLIP ,   D3DXCOLOR(1,0,0,1));

```

This all works perfectly. Where am I going wrong with the first bit of code?

EDIT - the code below gives me the following values (also listed below)

```
D3DXVECTOR2 origin = D3DXVECTOR2(
    (0.0f / 1280.0f) * 2.0f - 1.0f,
    (0.0f / 720.0f) * 2.0f - 1.0f);

D3DXVECTOR2 headPos = D3DXVECTOR2(
    (xyCoords.x / 1280.0f) * 2.0f - 1.0f,
    (xyCoords.y / 720.0f) * 2.0f - 1.0f);

```

for origin I get (-1, 1.2) and for headPos I get (0, 1.401e-043#DEN). FYI HeadPosition() will return a vector3 that has a 0 z component and x and y values from about 2 to roughly 33.

Now how on earth can me with a calculator be better than the computer? what am I missing?

0.0f / 720.0f) * 2.0f - 1.0f should clearly = -1, not 1.2! what is going on?

0 / anything = 0, 0 * 2 = 0, 0 - 1 = **-1**!!!

# Answer
`-1.#IND` means division by 0, make sure that `SCREEN_WIDTH` and `SCREEN_HEIGHT` have a non-zero value.
> 4 votes

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


# Question
Title: Is there an algorithm to detect the "mainland" on a 2D map?
On this map, the "mainland" is all the land that can be connected to the center of the map in the four cardinal directions (north, south, east, west -- not diagonally).

I would like to detect the mainland and fill the holes in it. I thought of three things:

1. Search in every non-water (dark cells) cell if can be connected to the center of the map using a path finding algorithm. Too expensive! But this could work for the islands.
2. The mainland is filled with a bucket of green paint. Each hole is surrounded by paint... now what? If i check every water point inside the mainland for adjacency i'll delete some peninsulas and other geographical features displayed on the shoreline.
3. Some kind of edge detection to figure out the mainland. Keep whatever is inside, fill it if it's water, remove what's outside. Complex?

Perhaps some game experienced developer can help me out with this, possibly giving me the name of some known algorithm or technique?

# Answer
> 31 votes
**Removing Islands**

I've done this sort of thing before in one of my games. To get rid of outer islands, the process was basically:

1. First there must be a guarantee the center of the map will always belong to the main land, and each pixel starts out either as "Land" or "Water" (i.e. different colors).
2. Then do a **four direction flood fill** starting from the center the map and spreading throughout any "Land" tiles. Mark every pixel visited by this flood fill as a different type such as "MainLand".
3. Finally go over the entire map and convert any remaining "Land" pixel to "Water to get rid of other islands.

**Removing Lakes**

As for getting rid of the holes (or lakes) inside the island, you do a similar process but starting from the corners of the map and spreading through "Water" tiles instead. This will allow you to distinguish the "Sea" from the other water tiles, and then you can get rid of them just like you got rid of the islands before.

**Example**

Let me dig up my implementation of the flood fill that I have here somewhere (disclaimer, I didn't care about efficiency, so I'm sure there are *many* more efficient ways to implement it):

```
private void GenerateSea()
{
    // Initialize visited tiles list
    visited.Clear();

    // Start generating sea from the four corners
    GenerateSeaRecursive(new Point(0, 0));
    GenerateSeaRecursive(new Point(size.Width - 1, 0));
    GenerateSeaRecursive(new Point(0, size.Height - 1));
    GenerateSeaRecursive(new Point(size.Width - 1, size.Height - 1));
}

private void GenerateSeaRecursive(Point point)
{
    // End recursion if point is outside bounds
    if (!WithinBounds(point)) return;

    // End recursion if the current spot is a land
    if (tiles[point.X, point.Y].Land) return;

    // End recursion if this spot has already been visited
    if (visited.Contains(point)) return;

    // Add point to visited points list
    visited.Add(point);

    // Calculate neighboring tiles coordinates
    Point right = new Point(point.X + 1, point.Y);
    Point left = new Point(point.X - 1, point.Y);
    Point up = new Point(point.X, point.Y - 1);
    Point down = new Point(point.X, point.Y + 1);

    // Mark neighbouring tiles as Sea if they're not Land
    if (WithinBounds(right) && tiles[right.X, right.Y].Empty)
        tiles[right.X, right.Y].Sea = true;
    if (WithinBounds(left) && tiles[left.X, left.Y].Empty)
        tiles[left.X, left.Y].Sea = true;
    if (WithinBounds(up) && tiles[up.X, up.Y].Empty)
        tiles[up.X, up.Y].Sea = true;
    if (WithinBounds(down) && tiles[down.X, down.Y].Empty)
        tiles[down.X, down.Y].Sea = true;

    // Call the function recursively for the neighboring tiles
    GenerateSeaRecursive(right);
    GenerateSeaRecursive(left);
    GenerateSeaRecursive(up);
    GenerateSeaRecursive(down);
}

```

I used this as a first step to get rid of lakes in my game. After calling that, all I'd have to do was something like:

```
private void RemoveLakes()
{
    // Now that sea is generated, any empty tile should be removed
    for (int j = 0; j != size.Height; j++)
        for (int i = 0; i != size.Width; i++)
            if (tiles[i, j].Empty) tiles[i, j].Land = true;
}

```

**Edit**

Adding some extra information based on the comments. In case your search space is too big, you might experience a stack overflow when using the recursive version of the algorithm. Here's a link on stackoverflow (pun intended :-)) to a non recursive version of the algorithm, using a `Stack<T>` instead (also in C# to match my answer, but should be easy to adapt to other languages, and there are other implementations on that link too).

# Answer
> 7 votes
Modify the four direction flood fill algorithm http://en.wikipedia.org/wiki/Flood\_fill

# Answer
> 5 votes
This is a standard operation in image processing. You use a two-phase operation.

Start by creating a copy of the map. From this map, turn into sea pixels all land pixels that border the sea. If you do this once, it will eliminate 2x2 islands, and shrink bigger islands. If you do it twice, it will eliminate 4x4 islands, etcetera.

In phase two, you do almost the reverse: turn into land pixels all sea pixels that border the land, *but only if they were land pixels in the original map* (That's why you made a copy in phase 1). This regrows islands to their original form, unless they were entirely eliminated in phase 1.

# Answer
> 1 votes
I had a similar issue but not in game development. I had to find pixels in an image that were adjacent to each other and had the same value (connected regions). I tried using a recursive floodfill but kept causing stack overflows (I am a novice programmer :P). Then I tried this method http://en.wikipedia.org/wiki/Connected-component\_labeling it was actually much more efficient, for my problem anyway.

---
Tags: algorithm, maps
---


title: Rays starting in an octree node

text:
# Question
Title: Rays starting in an octree node
I just fixed a bug where rays *starting and ending* in an octree node were not detected as octree node hits (because the ray doesn't hit the sides).

I'm changing the code to check *if a ray starts in the octree node, then it is an automatic node hit*.

Any reason to *not* do this?

# Answer
If your ray starts in an octree node, then it could, of course, hit something in that node. If you ignored the node in which the ray starts, you risk missing the closest hit.

So, no, there is no reason *not* to do it because you *should* do it.
> 4 votes

# Answer
That's exactly the way to do it, provided that's a leaf node. If not, you need to drill down to subsequent levels to raymarch there.
> 2 votes

---
Tags: octree
---


# Question
Title: Do Playfish and Zynga use COTS game engines?
I'm very interested to learn how to make 2D and 3D games, but I'm very new to this field so I am wondering if companies like Playfish, Zynga and other producer of games on Facebook are using publicly available game engines to make their games or if they're building their own game engine or what?

What game engines or technologies that are used in such games?

Are there any resources available that I can use to get started?

# Answer
Briefly, yes. Zynga's Café World and PlayFish's Restaurant City uses Away3D.

I think developers might use more of 3d engines because 3d is not everyone's cup of tea - they can just focus on implementing game logic and mechanics instead of meddling with math. However they would shy away from game engines like Flixel, for reasons that Nick Wiggill has mentioned. (eg. risk of middleware)

*Source: http://away3d.com/comments/away3d-latest-from-the-internet*
> 1 votes

# Answer
In agreement with @thedaian, I think you'll find these companies who work in social (and) web games tend to have various different "templates" (engines, if you will, although that term to my mind implies a lot more) that they can re-engineer to various purposes. For example, a multi-directional top-down action engine, a platformer engine, an RTS-type engine... and so on. These templates are usually games they've either bought the code rights to, or more often have developed earlier on in their own existence.

Obviously this works well both internally, and if you are being contracted by clients to produce games, advergaming being the perfect example.

The thing is, since each game is so small and relatively easy to refactor into something else, there's often not a drive to actually properly factor out the engine aspects *as an engine*. That's more the domain of middleware sold by dedicated middleware vendors, where you want to provide a perfect, clean slate for customers to work with. In the continuum of games/front-end/interactive I've worked in, I've seen pretty consistent code reuse this way. Obviously, though, these companies are also building other, completely new codebases, even as they are reusing the old to increase revenues.

More generally, there is little reason for them not to use mature external frameworks/engines like Flixel or Impact.js to implement new games. Decisions to use middleware can be fraught with risk, however, and so this is not always the chosen route.

In a sense, I guess the engine-vs.-template matter is just me arguing semantics with myself but again, the general answer would be, "Yes, they do".
> 3 votes

---
Tags: game-industry
---


title: Away3D vs Papervision3D

text:
# Question
Title: Away3D vs Papervision3D
I have served Google and I found that there are many 3D game engine also I have another question here

Do Playfish and Zynga use Flash game engines?

and I know that away3D is used for social media games on Facebook

but I'm confused now which one is the best and will be good and easy to start with as I'm very new in game development

so if anyone can advice me I will be thankful

also if anyone can support me with tutorial or book that may help me this is will be great

Thanks in Advance

# Answer
The majority of social media flash games do not use a 3D engine at all. They are mostly 2D games (including fake 3D like isometric etc.).

That being said, Papervision3D is basically dead. There hasn't been much upgrades for this engine. Away3D is still actively developed, so are other engines like Yogurt3D or Alternativa.

But since Unity3D now also allows you to publish a SWF, this is probably the easiest way to create a 3D game that runs in the flash player.
> 1 votes

---
Tags: 3d, browser-based-games
---


# Question
Title: vector.size() instead of literal type breaking my draw code
I'm writing a simple class to draw all the debugging lines I have in my scene at once.

The code in the draw loop is this so far: (If I put for example, 2 instead of `temporary2DVerts.size()` where I have marked with `//THIS LINE`, the code works fine.) when I run the code below the line breaks `//HERE`. Access violation reading location 0x00000000. seems like the create buffer line is not working, but why? what's the solution?

```
D3D10_BUFFER_DESC bd;
bd.Usage = D3D10_USAGE_DYNAMIC;
bd.ByteWidth = sizeof(VERTEX) * temporary2DVerts.size();// THIS LINE
bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
bd.MiscFlags = 0;

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

void* pVoid;

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

    device->IASetInputLayout(screenVertexLayout);

    device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_LINELIST);

    UINT stride = sizeof(VERTEX);
    UINT offset = 0;
    device->IASetVertexBuffers(0, 1, &pBuffer, &stride, &offset);

    screenPass->Apply(0);

    device->Draw(temporary2DVerts.size(), 0);

    temporary2DVerts.clear();

```

# Answer
> 1 votes
It is very likely that `device->CreateBuffer` is failing, resulting in `pBuffer` being `NULL`. You need to check the return value.

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


title: Existing master server software?

text:
# Question
Title: Existing master server software?
Considering there are many games out there that use some sort of a server that contains a list of current games/servers, is there an existing library I can use instead of writing my own master server?

I only wish to store game/server data (server name/ip, num players, game-specific data...).

Thanks!

# Answer
> 3 votes
You should be able to use GameSpy. According to their marketing you also gain access to (above and beyond lobbies):

* User generated content.
* Screenshots.
* Competitive leaderboards.
* Data mining.
* Matchmaking.
* Live replay streaming.

As far as I know SteamWorks also provides lobby services - but your game needs SteamWorks approval before you gain access. You could also roll your own using Azure (e.g. using AppHarbor - for free); given how simple your requirements are.

---
Tags: server
---


# Question
Title: Optimizing HTML5 canvas transformed drawing in Javascript
I am trying to optimize my HTML5 game engine and have noticed that currently a majority of the time taken in the game loop can be taken when drawing transformed tiles. I think this is because each transformed tile saves the state of the canvas, applies a transform, draws the tile, then restores the state of the canvas. Fortunately I have (at least) 2 classes of tiles, and if I am only drawing un-transformed tiles, the game runs quite smoothly. Take a look:

Slow with transformed tiles in the background: http://sgdk2.enigmadream.com/ben/JavaSampleo.html Faster with no transformed tiles in the background: http://sgdk2.enigmadream.com/ben/JavaSample.html

Sure you could say that drawing the extra tiles alone is responsible, but I have used Chrome profiling to confirm that XFrame (transformed frame) is consuming more than 50% of the time. So here's the drawing code for XFrame:

```
XFrame.prototype.draw = function(ctx, x, y) {
   ctx.save();
   ctx.transform(this.m11, this.m12, this.m21, this.m22, this.dx+x, this.dy+y);
   ctx.drawImage(this.imageSource, (this.cellIndex % this.graphicSheet.columns) * this.graphicSheet.cellWidth,
      Math.floor(this.cellIndex / this.graphicSheet.columns) * this.graphicSheet.cellHeight,
      this.graphicSheet.cellWidth, this.graphicSheet.cellHeight, 0, 0, this.graphicSheet.cellWidth, this.graphicSheet.cellHeight);
   ctx.restore();
};

```

Now one thing I can imagine improving this is if I could determine that many of the tiles I was drawing were using the same transformation, and make the single transform span the drawing of many tiles. It would be a challenge given my current design, but I might be up to it if it would make a difference. *However* that is of little use because the position of the tile has to become part of the transformation if I want the location of the tile to be excluded from the transform operation, I think. For example, if I want to draw a tile rotated 90 degrees at a coordinate of 64,32, I can't simply apply the rotation matrix and then draw at those coordinates because 64,32 will get transformed to something like 32, -64 (right). So I have to apply the offset as part of the transform for all transformed drawing operations. And since each tile is drawn at a different location, that means a different transform for each tile.

Any suggestions for optimizing tile drawing operations where transformations may be applied at the tile level in real time?

# Answer
> 1 votes
You're answering your own question. If the API wraps up the transform ops, then obviously it is up to you to minimise those ops in the way you've described; you can't go beyond the API layer for optimisation. And that's really *all* you can do other than making sure of the usual details like minimising conditionals and other costly logic in your innermost draw loop. When I wrote a top-down tile scroller using canvas last year, I batched my ops this way, after initially setting the transform matrix and then applying the matrix to each individual tile, and of course it improved performance an order of magnitude. Doing every tile individually was only done while I was learning the API and setting up the code structure, then I refactored.

The only other thing I can suggest is to consider the CSS3/DOM route instead, and measure its performance against canvas on a browser-by-browser basis.

**EDIT** In response to your comment. Two things:

* In my code, there is a very good reason why I had no problem drawing tiles: for the tile drawing, at least, I was using `fillRect(x, y, width, height)` such that I could simply use the fillRect params to specify the offset for each solid-colour tile, completely separately from doing actual "by-camera" transformations, which are applied to the canvas *after* you've drawn the tiles this way. In my case in fact, I also applied scaling multiplications to those 4 params directly, to ensure my camera could implement zoom. TBH, it was a little complicated due to the very limitations your question addresses.
* However on that same note, you should be able to use `drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)` to draw to the desired offsets, such that no per-tile `translate()` calls are necessary. Then you can use bitmaps for your tiles, instead of flat colour as I did.

So again, only use translate, rotate and/or scale for the actual camera view as a whole, once you've already rendered all your individual tiles in at their various offsets using `drawImage()` or `fillRect()` to do the initial population, cheaply. Beyond that, there is really nothing more you can do to keep rendering costs down, other than simply skipping the explicit transforms altogether (can't recall if this is viable or not). HTH.

---
Tags: 2d, javascript, html5, optimization, html-canvas
---


# Question
Title: A comparison of graphics libraries and their respective programming languages
A comparison of graphics libraries and their respective programming languages. A.K.A. "Which do I pick? With a twist."

I'm a long time professional programmer who never gave up on programming as a hobby. 3D programming has always appealed to me, but after some trial and error I always came back to (and got stuck on) the same question:

Which to choose?

* C# with XNA.
* C++ with DirectX.
* Java with OpenGL.

All three appeal to me:

* XNA, because it's managed, of high quality and very complete.
* DirectX, because it's de facto standard for large games.
* OpenGL, because it's open. It has a proven track record of high quality games built using it. + Eclipse hotswap functionality is sexy.

Keep in mind here that I will:

* Use the above library and language for hobby use.
* Will want to develop both 3D games and 3D tooling.
* Might seek a job in a 3D programming industry.

For the sake of the argument, assume I am equally well versed in C#, C++ and Java. And have no preference for any of the three mentioned libraries. In reality I have a slight preference for one of those three, but the quality of the code I produce in the languages is the same.

Replies with sources as links are preferred! OGRE and Irrlicht (and similar) are also contenders, but not preferred because it introduces additional depencies on other developers.

# Answer
> 2 votes
If I were you, I'd take the time and learn OpenGL, particularly since you're a dedicated hobbyist at this stage. Like C and C++, it's a general-purpose tool that sets you up for opportunities in different industries, if it ever interests you to do 3D programming for eg. medical visualisation or defence contracting. They say that DirectX is a short leap from OpenGL. Also, I would say you can get into GPGPU technologies like OpenCL or Nvidia CUDA more easily if you take this route. And IMO, that's where the future is: General purpose, massively parallel processing without restricted access to the bulk of system memory.

So that's DirectX covered under that umbrella, as well. I would favour it only slightly less than OpenGL, but that's very much a personal preference. It's still miles ahead of the remaining alternatives.

For the above reasons and more, I wouldn't choose XNA. I find the framework restrictive and to me at least, the architecture desicions they took don't make much sense. Yes, I know it's great to be able to deploy for Windows and XBox360 at the same time. Yes I know C# 4.0 is (let's be fair) a great language in many ways. XNA *may* save you time. But I'd still avoid it unless I was specifically targetting the Xbox360 for a game that didn't require the degree of control that a lower level language offers.

To be fair, if you are not already a C or C++ programmer (you don't specify), I would certainly go the Java and OpenGL route. Notch, of Minecraft fame, has made a huge name for himself with those two technologies as an indie and I don't think that is something to sneeze at. I used Java briefly last year and in comparison to C#, it may have less modern features, but the consistency and simplicity of the core libraries are just brilliant. Java collections are an absolute pleasure, more than any other language I've worked with. And they support just about any type of collection you can think of, natively. And they're FAST.

You did leave out one popular option, which is Unity. This is ideal if you want a really, really fast start. The basic edition is free, and you can use DropBox for source control (since unless you pay for version control support otherwise, it can be problematic). It uses Mono C#, although not the newest version.

---
Tags: xna, opengl, graphics, directx
---


# Question
Title: Am I allowed to make my Minecraft clone open source?
I'm developing in my spare time a game like Minecraft. In fact, it isn't "*like* Minecraft", because I'm trying to make it a close as possible copy of it (meant as exercise for myself at the age of 16 and simply because of it is fun to me). Of course, I'm not copying the code using the Minecraft Coder Pack (MCP). I started the game from scratch in Java using OpenGL.

So, my question is: am I allowed to put my source code online on a public source code versioning host like GitHub, Google Code, et cetera (which makes my code open source, because I don't want to pay to use a private host)? Of course, I don't want to sell the game, because the game is from Notch.

A detail which might be important is that I'm using a custom texture pack (so, not the one that is shipped with the real Minecraft).

If it is allowed, are there any rules? I took a look to this page, but it seems that he doesn't say anything about this: http://www.minecraft.net/terms

---

**Edit:** There is the game called Terasology (started under the name Blockmania) from Begla. That is a nice project, but it is not meant to be as close as possible to Minecraft. That project is open source.

# Answer
> 19 votes
Okay, so here is my understanding of this - coming from developing games and a constant attempt to obtain more knowledge on licensing, copyright, open-source projects, etc.

You are allowed to make a *Minecraft* clone and open-source it with no repercussions as long as you don't use the title *Minecraft*, don't use any of *Minecraft*'s source code, and don't use any of *Minecraft*'s assets.

Doing any of those will violate the game's copyright. Programming a game to reflect a game you really enjoy isn't at all a bad thing, and sharing that code is a good thing. However, stepping on any of the toes of those at Mojang by using code or assets they created is not okay.

# Answer
> 11 votes
> ***Disclaimer:** I'm not a lawyer. I'm answering this on best knowledge, might be wrong, though.*

Yes, it's your work, you're allowed to do that. You can do with the stuff *you* write in your spare time whatever you want.

What you're not allowed is:

* Use original source-code (decompiled) from Minecraft and put that under another license
* Use original artwork from Minecraft
* Use the name "Minecraft" as your own
* Distribute the minecraft.jar

If you clone something, you need to watch out for possible copyright violations. Don't use anything which falls under Copyright. Copyright applies but is not limited to:

* Sourcecode
* Artwork (Graphics, Sound, etc.)
* The name

So if you clone software (a game or an application), *never* use anything from that software *directly*, *do it yourself*.

---
Tags: opengl, java, legal, minecraft-modding, licensing
---


# Question
Title: A* pathfinding algorithm to identify entrances into current "room"?
Was looking for some online articles that might have a good idea or two in how to approach this but not finding much. Most of it deals with the various ways to generate and follow a path to a known destination type.

Basically the idea is that you have an existing node graph and want to utilize that data in order to locate entrances into the current area an AI unit would want to defend. So think of an AI unit assigned a task of defending a point with a radius and wanting to choose the best direction to face while waiting for enemies to show up that would be pathing to the defend point.

The critical point that I was looking for input on would be how one might identify the entrance points. Or the nodes that are the doorways into the area being defended.

The best idea thought of would be to do a breadth first outward search from the defend point and identify nodes that can see the defend point, have links, but none of the linked nodes can also see the defend point.

# Answer
> 2 votes
There are two concepts at work here: graph topology and level geometry (aka topography). They're two sides of the same coin.

Furthermore, there are two ways your levels could be produced: manually or procedurally.

And this leads to 3 rough approaches that I've come across in my work.

---

**Arbitrary node placement within a static level** is super, if your constraints allow it. This is where you can place your nodes at any point in floating point space. This would be where you have level designers constructing your (static) levels. Here, the simplest and most sensible solution is to have them specify via editor or data file, nodes that represent portals inside your pathing graph. Obviously in this case it is also up to level designers to ensure that the geometry of the level is suited to that pathing which is put in place (usually you would do the level geom first, then lay pathing nodes over that to ensure the nodes are in all the right places and no others).

---

**Coarse-grained grids** are used when a more dynamic approach to pathfinding is required, such as where the level is either procedurally generated, and/or where it can change at runtime. Here, you need intelligence built in to detect what might be considered a "portal" in your grid of potential pathfinding nodes. Each cell in the grid you divided your level into, is at least as big as each entity you have moving around. In this case, it's very easy: wherever a cell has just two non-adjacent neighbours, it's single width, and you can assume that, if the previously walked cell had more than that, you've reached a narrowing point that you can call a portal. The downside? Particularly if your level is dynamic and you don't tend to match walls exactly to grid cell edges, you'll find there are times when geometrically it is clear that an entity could pass from one cell to another, but in terms of the pathfinding graph, due to its resolution and origin position, the pathing-evaluator simply can't detect the connectedness of two adjacent cells. This may not be a problem for you, however.

---

**Fine grained grids** are used in the same circumstances as coarse-grained grids, but with the added constraint that you don't want your pathfinding nodes to be so clearly delimited into low-res tiles. So each cell is smaller than the entities in question.

This sounds a lot easier than it actually is, geometrically speaking. Consider a cave complex constructed, throughout, of the same homogenous material. Say you use some form of noise to generate spaces inside a level-sized block of solid rock, and then used some sort of coherence/metaball approach to join the closest points of these spaces. Now bearing in mind that your pathfinding grid resolution is finer than the size of a single entity, some of these join channels are going to be too narrow for an entity to pass (even though air could pass through), while others might not. This will vary at different points along the channel, and you can see how the shape of entities can also affect where they might be able to traverse and where they might not. This is quite a problem in 3D; in 2D, it's a lot easier to handle but still not trivial. One way to make things easier in both cases is to assume either a square (cubic) or circular (spherical) bounding volume for each entity.

One way to identify portals is to exhaustively cast rays around a circular or spherical shell whose diameter is equal to the minimum width needed for an entity to pass through (i.e. their body width). In order to limit the number of locations to do such a test from (to something less than infinity), it's a good idea to quantise your level space into a grid. Even so, this is very time-consuming in both cases, especially in 3D, and if possible should be done once only, and cached. Of course, that is easier said than done if your level geometry is indeed dynamic. Another way to visualise this casting of ray to a shell, is to see it as the placement of an "atom" into a tiny open space, and growing that atom until is hits the surround rock, like a balloon expanding.

The point I'm getting at is that while a portal is pretty much instantly recognised by any higher animal (our facility probably being due to natural selection, since quickly identifying hiding places had to have been crucial), there is actually a lot of raw logic that goes into determining where a body of a given set of dimensions can pass, and where it can't.

---
Tags: ai, path-finding
---


title: Issue with loading XML

text:
# Question
Title: Issue with loading XML
So recently i've been changing my XML files that i'm using in-game, to add in a bit more data to the files but i've also changed the way in which i load & save files, by now using the XDocument API. \*Previous Thread/Topic: Xna, writing XML \</Asset\> end element

So now that i'm all done, i've come to trying out the new files in my new project and i have a strange error: *There was an error while deserializing intermediate XML. Input string was not in a correct format.*

Oddly though, this at **line 13**: http://pastebin.com/jMtNwV8N

In all honesty i don't know what to say. And to what exactly the problem is, i'm having a slight hunch that it could be something to-do with the way the files are saved: http://pastebin.com/Q2pJye5B

Problem is that my initial thinking right now is that it might have to be something to-do with the *'\t'* or *'\n'* literals, but then there's these literals in the actual data lines i.e **lines 11 & 12** so it wouldn't all of a sudden chuck me an error at **line 13**

Guess i'm just a bit mystified by this and to what the problem might be?

Any help greatly appreciated :)!

Edit: Well just to test it out then, i removed all the *'\t'* & *'\n'* from the saving code. And re-tried it then, unfortunately i'm still getting the same error :/ Same place, with the error occurring at the ending element of Rect.

# Answer
The word `deserializing` on your error message tipped me off - that wasn't supposed to appear in a normal scenario. That means it's a problem with the XNA content pipeline.

This happens because you were trying to build the XML through XNA's content pipeline. The solution is as simple as changing its *Build Action* property on the file from *Compile* to *Content*, and toggling the *Copy to Output Directory* property to true.

My old advice still applies though:

I don't think you should be adding whitespace to your data as a way to indent and make your XML look better, since they're not part of the data you're trying to store. This will force you to trim it when you read the data back, which is unnecessary in my opinion.

I think you should get rid of the tabs altogether, and possibly choose another character to act as the line separator (e.g. instead of using "\n" use a normal " " space).

---

**Edit**

> i think i might know what it is that is causing the issue. For some reason it seems, compiling the XML into the game, it doesn't like the ',' thats is separating the values. Changing that it works :O. Unsure why its so fussy?

I am guessing that maybe your content writer is still doing a split by " " and then writing it in that way to the stream, but since you're now separating your values by "," it's not written correctly. So when deserializing, the ReadObject method is expecting a list of rectangles, but finds something else and fails.

Add your content reader and writer to your post if you need help figuring that out, but it really should be just a matter of keeping both with sync with each other and with the file format.

---

**Edit 2**

By the way, this doesn't look right:

```
anim.Rect = new List<Rectangle>();
anim.Rect = (List<Rectangle>)input.ReadObject<List<Rectangle>>();

```

You probably only need the second line. You're creating a new list and then overwriting it immediately. Not that it doesn't work, but is wasteful.
> 1 votes

# Answer
I don't know the XDocument API as I do not practice C#, but from my own experience with others languages you are probably right when you are suspecting the '\t' and '\n'.

I tried to load and parse your xml file with tinyxml in C++, but I did not get any error. However, there is two solutions that come to my mind. You could try the following options:

1. Use the CDATA element as the text inside a CDATA section will be ignored by the parser.
2. Use a trim function to remove the white spaces and line breaks.
> 0 votes

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


# Question
Title: Cross platform development tool/platform for the modern indie game developer?
I'm a Flash developer, but I think it's time to think of other avenues. Ideally I want to be able to write once but be able to deploy to as many different platforms as possible, so iOS AND Android....Web AND Mobile. Are Html5 game development platforms good enough to create games that run on the web and mobile? or should I go with say Corona for iOS and Android, and use Html5 just for web?

I'm a professional developer so paying out for a decent game dev platform is not an issue, I just want to make sure I'm using the best tools for the job over the next few years.

Only interested in developing 2D games. Might well need physics. Corona definately seems a good option for mobile, but if it's possible to create everything in Html5 even if it's more work I'm wondering if it's worth the time learning that.

# Answer
> 7 votes
Unity seems to be a popular choice lately. It will allow you to run on iOS, Android, Web, PC, Mac.

Although, you're question needs to have more specifics like what kind of games you want to make, what features you must have, etc. Otherwise it's a just a "What's best?" question, which isn't good for this site.

# Answer
> 1 votes
I use LWJGL. Its a wrapper for OpenGL that is cross platform out of the box. With literally zero special considerations needed per platform, I'm able to produce a single jar, with a single click, that works on Windows, OSX, Linux, Solaris and a couple of others. Because LWJGL uses Java, you can abstract your game logic into a separate module and just adjust the renderer for use with Android. I have no experience with iOS, but I hear that apps must be programmed in Objective C, if thats true, then LWJGL+Java is ruled out instantly.

**All you need to know is Java, and OpenGL.**

I haven't used Unity, but from the outside looking in; it seems like a more drag and drop and scripting game development approach. LWJGL involves programming your game manually from scratch using any modern Java IDE (such as Netbeans).

# Answer
> 0 votes
Since you're specifically looking for 2D, you might want to have a look at Googles playn. It's an open-source framework that allows you to publish to HTML5, Java (Desktops) and Android. They had a working flash compiler, but that seems to have lagged behind or is no longer maintained.

The project is quite new, so it's probably not so mature yet. Also it's uncertain if there's ever going to be an iOS publish option.

# Answer
> 0 votes
Tom here from Scirra, we make the Construct 2 game maker

Construct 2 is used by thousands of game makers from all over the world, a mix of indie and professional. It also has a **built in physics engine** (Box2D) which you specified as a requirement in your question.

Construct 2 is capable of making just about any type of 2D game. You don't need programming knowledge to get going with it, but if you like to program as well you can extend Construct 2's capabilities by writing your own Javascript plugins and behaviours (and share them with the community!).

It's another option to take a look at anyway! Construct 2 also has an extensive free edition available.

---
Tags: android, ios, html5
---


# Question
Title: Best platform for puzzle game development on the iPad
I have a series of hidden object and puzzle games mapped out that I want to develop for the iPad and although I have written programs before, it's been a while. I've been trying to find the best platform to use and can't seem to find any helpful suggestions although HTML 5 seems to be the most mentioned. I will be using original graphics, perhaps some video cutscenes and music (think Dire Grove). Any suggestions?

# Answer
HTML5 is definitely the best for cross-platform support. As any browser that renders canvas should be able to play your game. Although you'll have to be wary, as there are still some browser specifics.

There is no doubt if you want to develop a game on iPad or iPhone, it is probably best to learn cocos2D and obj-C.

My suggestion? Pick a random thing you want to do, develop it FULLY, then decide if you liked it, then consider some ideas:

* was this an easy platform for me?
* Do I see a potential in the future for this platform?
* Did I have fun developing on this platform (most important)

Do not rush, take your time, and learn. I also do not recommend stopping half-way to develop on a different platform.

Have fun!
> 1 votes

# Answer
If you're making a game specifically for the iPad, I'd shy away from HTML5. You'll get much better performance using a native app.

As an example, here's Bejeweled in HTML5. Try running this in your ipad browser: http://bejeweled.popcap.com/html5/

As far as engines to use, I'd look at either Cocos2d or Unity. Both will get a lot of the heavy lifting out of the way and let you hopefully concentrate on making the game itself.
> 0 votes

# Answer
iOS has WebGL capabilities, but currently they have disabled it. I do however think it's likely they will enable it in the future, so HTML5 could be a good platform for you. Also, because your looking at making puzzle games these are traditionally less resource intensive than other genres of games so the current performance should be good enough for your needs.

We make the Construct 2 game maker engine which lets you create HTML5 games. No programming is required but if you want to you can program your own plugins and behaviours in Javascript to extend Construct 2's capabilities. If you're looking to make HTML5 games rapidly you may want to look at Construct 2 as an option. There's an extensive free edition as well which is getting quite popular now.

HTML5 has a good future ahead of it and it's just starting to gain some good traction so now might be a good time to step in!
> 0 votes

# Answer
I would recommend a mobile development platform like Corona or Moai. They make the process a lot simpler, by handling all the low-level eccentricities of iOS and letting you do all the programming in Lua.
> 0 votes

---
Tags: html5, puzzle, platform
---


# Question
Title: How to achieve this style of view in XNA?
I would like to use a Perspective projection to create the following effect in XNA:

Cubes are simply made up of 8 vertices and drawn using `DrawUserIndexedPrimitives()`.

Any extra suggestions, are also welcome.

# Answer
If what you want is indeed like your drawing suggests, then you're looking to implement an **oblique projection**. Check this video for an example of this type of projection in a game. The big difference is that the game in the video uses a set of pre-made tiles, while you're trying to do the projection mathematically.

For starters, here's a picture which should make evident the difference between perspective, isometric and oblique projections. Use it to decide which of these you really want.

Now, you can implement both Perspective and Isometric projections using methods already available in the XNA API:

* For a **Perspective Projection**, simply use one of the `Matrix.CreatePerspective` family of methods.
* For an **Isometric Projection**, use one of the `Matrix.CreateOrthographic` family of methods, and rotate your camera (or your objects) a bit in the X and Y axes so that they match the isometric look.

As for an **Oblique Projection**, I think it will be a bit more complicated. I've actually never seen an implementation of this before, so I'll just be going with my intuition. Someone let me know if there's a better, known solution to the problem. You're going to need a vertex shader. Here's the steps:

1. Set up an orthographic projection matrix (for which XNA already has helper methods). That's because both oblique and orthographic projections are types of parallel projections, so it's better to start from there.
2. Set up your camera so that it is looking down the Z axis, i.e. perpendicular to the XY plane. You can pan the camera around, but never change the angle it's facing.
3. Use a vertex shader, and after applying the projection matrix, modify the X and Y values using the following formula taken from the wikipedia article above. The angle should probably be around 45 degrees (you might have to invert the sign of Z depending in which space you do the calculation):

Optionally you could do this last calculation with a vector instead. For instance, if the angle is indeed 45 degrees, you could do this last step as something like:

```
position.xy += z * normalize(float2(1,1));

```

This should make vertices that are further away from the camera, be rendered more to the right, and up from their original positions.
> 4 votes

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


# Question
Title: Should I use Game Engines to learn to make 3D games?
HI i am a software engineering student in his second-last year.

I am proficient with C,C++,C# and java programming languages, and being a student of engineering I have studied calculus, vectors etc in both 2D and 3D & various other mathematical, probability and statistical topics.

I have made several 2D games, my most recent being a Super Mario-like game with side-scrolling and multiple levels.

Due to my these small game projects,i have become really interested in making games.

So now i want to move ahead to learn to make games in 3D.

Now I know that there are several game engines available which can take care of rendering details and other "low-level" stuff for me...

***My Question is:***

1) Is it a good idea to learn to program everything yourself, from making 3D shapes, terrains (using polygons meshes) etc, to programming mechanism for collision detection, lighting etc, considering my motive is to learn how to make games in 3D (but am not too eager to get into the game industry quickly, want to build a solid foundation first)

Or could I do without these details & work on the abstraction-level which the game engines (like UDK) provide ??

3) If I should try to develop from scratch, then can anybody suggest which API to use: Direct3D or OpenGL?? (which i would be more comfortable with, in light of my above mentioned skills) & can anybody also give me references to some good books, reading materials, tutorials, etc to get me started?? (I wouldn't mind theory as long as it helps me make a sound foundation)

Many Thanx in advance (for even reading my question, i know it's lengthy... but i need a DETAILED answer... :D :D )

# Answer
> 9 votes
In my experience you need to learn to program everything from scratch individually and use a game engine for any actual games you work on.

Even if you work in the industry you'll never write everything form scratch, you'll focus on certain aspects of the game. So if you want to maximize the use of your time, I would say have small projects like going on at openprocessing.org or something similar and use a game engine like Unity3D or corona for your personal projects.

Your *for fun* projects may look like:

* 2d perlin noise generator
* terrain generator
* 2d bone animation sim
* 3d cube scene with multiple cubes and from scratch camera projections on openprocessing.org
* simple 2d game using corona or unity3d
* random chapter from one of the GPU gems or game development gems books (the have lost of things you can try to implement)
* write some shaders in HLSL
* more advanced game with maybe some 3d using unity3d
* etc etc etc

Of course these projects would be tailored to things you're actually interested in.

# Answer
> 13 votes
It depends if you want to produce finished games or just learn.

If you actually want to make a game, making your own game engine from scratch just isn't feasible in any real timeframe unless you have an very narrow, simplified game and even then your still looking at quite a while.

Making a 3D game engine from scratch is a huge undertaking. They have heaps of stuff and most of it is complex.

Here is a bunch of stuff that a 'game' might contain:

* Your basic windowing toolkit (how to get a blank window in something like QT, SFML, GLFW, GLUT, SDL, WGL, etc... Or maybe a canvas in WebGL).
* Basic 3D api (draw a triangle).
* Integrating 2D stuff (you want menus and huds?). Simple basic stuff like overlaying SFML/SDL. Flash based UI? Integrate webkit for a HTML5 overlay? Integrate QT widgets?
* Handling input with your windowing system, what control types are there. Do you want to bind keys at runtime?
* More complex 3D api. Vertex Buffer Object, Vertex Array Objects. Rendering to a texture.
* Basic 3D knowledge such as Matrix and vector multiplications. How the transform matrices work. ModelView/Projection matrices.
* Learning an algebra math library so you don't have to do that all yourself from scratch (GLM for example).
* Loading your game from disk (Settings, World/Level data. Need to make your own file formats and loaders).
* Spacial geometry, How do you store all those object in 3D space. Just in one vector which is ok for smaller number of stuff or Octrees? BSPs?.
* Scenegraphs and rendering pipelines. How do you cut out the stuff you don't want rendered? Bounding boxes? Occlusion queries?
* Mesh Loading. How is the data stored? A simple OBJ, Parsing COLLADA XML and somehow producing something relevant to your gameengine/3dapi, your own optimized custom binary format? (which you will need a tool to produce unless your typing in vertices by hand). A 3rd party mesh loading library like assimp?).
* Texture loading (probably just use a simple lib, but which one? (I like DevIL with OpenGL) What format jpg? tga? dds?).
* Content creation. Will you just dump a bunch of placeholder meshes in or are you going to learn a 3D program like Blender, Maya or 3DS max. Are you going to animate them?
* Shaders. How to compile, bind values to them and use them. Then a whole new language either GLSL, HLSL or Cg for writing the shades themselves. There a pain to debug.
* Shading algorithms. Perpixel. Calculations for Blinn, Phong. Want toon shaders?
* Shadows. Want shadows, render the depth component of the scene from the view point of the light. How do you do that, binding frame buffer objects?
* Visual Effects. Glow can be quite nice and isn't much more than bluring. Depth of Field? Bloom? HDR? Antialiasing?
* Font rendering (Learn another 3rd party lib? Does your widget system have something?).
* Scripting? Lua? AngleScript? Python? Binding them to your language. Writing wrappers for everything.
* Best class structure for game data. Inheritance or component design pattern?, your probably going to have to mix and match quite a bit for a game. How about named runtime properties so you can do things like "player1.health=1" in a script (some languages this is quite easy but they have overhead as a result).
* Saving/Loading. How do you know what needs to be saved/loaded? Just do the whole level and waste everything or set stuff as 'dirty' and just save the dirty stuff.
* Networking, basic UDP networking, RPC calls (so a player can send that they moved). How do do you know what has changed and needs to be resent? Just have a few fixed values you sync or let anything change and keep a list somehow?
* Physics? Your own basic inbuilt physics engine? Or something like Bullet.
* Sound? OpenAL? OpenSL? DirectSound?
* Multithreading? Just the renderer?, a few choice threadable stuff (sound, physics) or the whole engine? How do you deal with multiple threads trying to read and write to the same stuff? Using locking mutexes with cost overhead or design a streamlines FIFO message passing que system.
* Optimizing. Are you going to use a flexible but more resource intensive language or something like C++ where you can play with pointers and pass by reference. How do you minimize dynamic memory allocation.
* Now how the hell do you pack that all together. So your script engine can access named runtime properties and cause the network to send packets with updated values while ensuring mutual exclusion and displaying it to the screen.

Giant imposing list aside, just about all of that is all insanely fun to learn, you programming will likely improve heaps as a result and much of it is useful in other areas or programming. Obviously a lot of that can be cut down depending on what you are trying to accomplish.

You will probably want to split up all that stuff into small projects. Much of it might not be 3D at all (like the networking and data structures). And lots of it isn't specific to 3D games either (networking, scripting , etc...).

One big problem with learning 3D is you need to make it interactive a lot more in order to understand it and have anything useful. Having a scripting engine for example can be great since you can just spawn in stuff at runtime, it break you out of just having a 3D rotating mesh on the screen and actually having something that looks like a game. Once you have the script engine maybe you can just store your levels as scripts rather than trying to invent your own data structures. Dumping in a physics engine will give you collision detection which is much harder in 3D than in 2D as well as all the cool physics interactions you will get. Choose a more inefficient scripting langauge that will let you introspect object properties.

Perhaps you could start off learning the api by porting your 2D game to it as a bunch of 2d squares. Then maybe you can look at trying to 3Difiy parts of it. Use a 3d mesh for the main character, then other ones, then 3Dify the tiles and background. Even that is kind of heavy since you need to learn things like animation and probably shading.

Another idea is a massive cutback on stuff. Some is obvious extras like multithreading. But maybe you shouldn't bother with any kind of lighting, shadows or texturing. Choose an art style that works with everything being flat like a cartoon (although actual cell/toon shaders also require learning different lighting algorithms). It would also save on making a whole bunch of textures and your models could probably have lower polygons counts. Or wireframe (although that might actually be more work since OpenGL core profile doesn't support actual wire-frame rendering any more, you either have to draw a bunch of lines which means either several redraws of your meshes or having different line based geometry layouts rather than the traditional triangle ones for your meshes or use a special wireframe shader.

On the flip side using a premade game engine allows you to skip much of the stuff in that list and you can concentrate on making an actual game and it's content. Just place an object as X,Y,Z and let the engine figure it all out. Of course you will be restricted by what you can do to what the engine supports or what you can make it support.

# Answer
> 2 votes
You're going to get a lot of opinions from the way you've structured your question. So here's my opinion.

> 1) Is it a good idea to learn to program everything yourself, ...

I think it's a good idea. You will be forced to learn the intricate details of how a typical piece of middleware would work. By the time you're done, you'll be capable of effectively using something like Unity or UDK.

However, I wouldn't set out to do this for a commercial project, as there is a lot of work involved and you will spend a lot of time fighting fires. I chose to do this with a game I've been working on (largely because at the time I had no other choice), and I will almost certainly not use this engine I've written for future projects, since there are very mature alternatives now. That said, I wouldn't take back the fact that I wrote everything from scratch, because I've learned so much of what goes on "under the hood" by doing so -- hence my opinion.

> 3) If I should try to develop from scratch, then can anybody suggest which API to use: Direct3D or OpenGL??

I'll suggest OpenGL. It's cross platform and is picking up a lot of steam with OpenGL ES. I've never used Direct3D, though, so you'd be wise to entertain other opinions, and consider your particular career goals.

---
Tags: software-engineering
---


# Question
Title: Draws fine in full OpenGL; not drawing anything in Chrome NaCL
I'm appealing to people's psychic debugging skills:

I have an OpenGL app that uses shaders and attributes in uploaded VBOs exclusively.

It runs fine on the desktop (Linux with integrated Intel card).

It compiles for and runs on Chrome NaCL, which is OpenGLES 2.0. It does not draw anything, however (Vista, an ATI card).

The `glClearColorf()` and `glClear()` are working, and by picking a random clear colour I can get a nice flicker going so I know I've got the whole draw and flush cycle going fine in Chrome NaCL.

However, as I said, my program doesn't draw any of its content.

I have liberal `glGetError()` checks everywhere, and at first when porting they found lots of stuff such as needing to specify a float precision in shaders and not using full ints for element arrays and such. But now there are no errors reported anywhere.

I have printf debugging so I know my code-path is right and that everything I can think of is asserted.

The NaCL "tumbler" demo does run. Apart from their codebase being massively smaller, I can't spot what they are initializing that I aren't.

Anyone got any ideas what classic thing I've run into?

# Answer
I was not calling `glViewport()` in my resize handler; with SDL code, I wasn't needing to call it ever at all, as it defaults to the visible window (although in SDL you do need to reset it if you support resizing windows). In NaCL, you do need to initialize the properly.

Another gotcha was that in SDL, the default clear colour is seemingly black. In NaCL, its transparent (if you copy the standard examples, that set 8-bit alpha on the `pp::Graphics3D` when they initialise), and so the webpage will show through the NaCL component. A neat useful fact, but if you're not looking out for it it can appear as though its not clearing.
> 2 votes

# Answer
A general-purpose answer:

Find some example code. (I'm assuming NaCl OpenGL sample code exists.) Make sure it works.

Now replace your main() function with the example code. Again, make sure it works - if it doesn't, you've got a linking error.

Now gradually transform the example code back into your real main(). Add your non-OpenGL initialization code, test. Replace the example render code with your game's render loop, then test. Add your input loop, test. Replace the OpenGL init code with your init code, test. Eventually it'll break - that's when you can start diving deeper into that breakage to find out why.

Give me a positive example and a negative example, and I can eventually tell you what's wrong with the negative example, guaranteed.
> 1 votes

---
Tags: opengl-es2, chrome
---


title: How to get translation from view matrix

text:
# Question
Title: How to get translation from view matrix
How can I retrieve the camera's world-space position from its view matrix? The only answers I've seen to this question suggest the translation is in the last row/col but this wouldn't work since the matrix contains \[x (dot) right, y (dot) up, z (dot) look\]

# Answer
> 10 votes
**Short Answer**

First invert the view matrix. Then fetch the translation from the last row/column.

**Long Answer**

One way to deduce the contents of a view matrix is to start by considering the camera as any other object in the world, and calculating a world matrix for it:

```
RightX  RightY  RightZ  0
UpX     UpY     UpZ     0
LookX   LookY   LookZ   0
PosX    PosY    PosZ    1

```

A world matrix transforms coordinates from local space to world space. But in this case, the camera's local space and the view space are one and the same, so we can also say this matrix transforms coordinates from view space to world space.

Since we need a conversion in the *opposite* direction, we have to invert the matrix. The result is what we call the **view matrix** which transforms coordinates from world space to view space:

```
   RightX        UpX        LookX      0
   RightY        UpY        LookY      0
   RightZ        UpZ        LookZ      0
-(Pos*Right)  -(Pos*Up)  -(Pos*Look)  1      // * = dot product

```

And that's the sort of matrix you have. So in order to get the camera position back from it, you will first need to invert it, and *then* you can grab the translation from the last row (or column depending on the system).

# Answer
> 7 votes
First off I would HIGHLY recommend just storing the position as a vector separately, it'll make things much easier computationally. Anyways...

`[x (dot) right, y (dot) up, z (dot) look]` is not the actual view matrix. The matrix itself is of the form:

```
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1

```

where the top left 3x3 matrix represents rotations, scale, etc. All the camera's orientation is done there. The remaining row and column are used for translation and some other complicated perspective stuff I'm not going to get into right now.

When you get the matrix (assuming it's a 4x4 matrix), translation will always be stored in either the last row or the last column, depending on whether your matrix class is row-major or column-major ordering.

What you're probably getting confused about is the fact that you need the dot products. What's going on is simplification of the matrix math, there are more detailed answers in this Stack Overflow question: https://stackoverflow.com/questions/349050/calculating-a-lookat-matrix

The solution can be found here, you need to take the inverse of the matrix and get the translation of that:

```
Vector3 ViewTrans = Matrix.Invert(ViewMatrix).Translation;
Position = ViewTrans;

```

# Answer
> 7 votes
Other answers here explain how to get the camera position from camera matrix inverse.

If the 3x3 part of the camera matrix has only rotation (no scaling or shearing) as they usually do, the calculation can be optimized by multiplying the camera matrix translation with the transpose of the camera rotation. Camera position is then the transformed translation vector multiplied by -1. In GLSL this is:

```
vec3 cameraPosition = -transpose(mat3(worldToCameraMatrix)) * worldToCameraMatrix[3].xyz;

```

or

```
vec3 cameraPosition = -worldToCameraMatrix[3].xyz * mat3(worldToCameraMatrix);

```

This is what I have been using in my vertex shaders if I don't want to calculate and pass the camera position as a uniform.

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


# Question
Title: How to import the .fbx scene with multiple objects in XNA so that the objects retain their scene position?
I have a scene that contains mutiple objects. How can I import it in XNA and maintain each object position? Right now I export the scene in .fbx and load it in a model like this:

```
 cube.model = contentManager.Load<Model>("cub");

```

But the objects don't retain their position and are all gathered in one point.

I need a method to import all the objects as individual objects but to retain the objects position in the scene. (i.e. I need to import the scene so that I may manipulate the objects and retain their position in the scene so that I shouldn't reposition all the objects by myself)

The objects are not connected, thus there are no bones. They are individual objects, just placed in some positions.

This is my drawing function, the cube is the gameobject.

```
void DrawGameObject(GameObject gameobject)
{
    foreach (ModelMesh mesh in gameobject.model.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.PreferPerPixelLighting = true;
            Matrix b = Matrix.Identity;
            effect.World = b * gameobject.orientation;
            effect.Projection = camera.projectionMatrix;
            effect.View = camera.viewMatrix;
        }

        mesh.Draw();
    }
}

```

# Answer
> 1 votes
Done. I was drawing the model wrong. It actually had bones:

```
void DrawGameObject(GameObject gameobject)
{
    Matrix[] transforms = new Matrix[gameobject.model.Bones.Count];
    gameobject.model.CopyAbsoluteBoneTransformsTo(transforms);

    foreach (ModelMesh mesh ingameobject.model.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.Projection = camera.projectionMatrix;
            effect.View = camera.viewMatrix;
            effect.World = transforms[mesh.ParentBone.Index] * gameobject.orientation;
        }

        mesh.Draw();
    }
}

```

---
Tags: xna, c#, assets, asset-management
---


title: Cross-Sections of 3D Rendered Objects

text:
# Question
Title: Cross-Sections of 3D Rendered Objects
I am currently trying to look into techniques that allow the calculation of arbitrary cross-sections of a 3D object or rendered volume. However, I have been unable to find much on the topic. I know of some software packages, such as the SolidWorks CAD package, that employ such techniques; as seen here:

Does anyone know of any available methods, techniques, algorithms, or tutorials that aim to achieve this result? Also, in terms of the theory of this technique and the concept of calculating it on the fly; how performant is such a technique likely to be?

# Answer
> 3 votes
If you just need to render the cross-section, you can specify a clipping plane. For example in OpenGL you can call glClipPlane and OpenGL will take care of everything else. Alternatively you can probably do the same thing in a shader.

If you need the actual geometry of the cross section, you can clip every polygon against the clipping plane. When a polygon is clipped partially, the vertex count is often increased, but the math behind it isn't anything tricky. You should be able to find tutorials for that with Googling using the keywords *frustum*, *culling* and *clipping*, such as this site.

---
Tags: 3d, graphics, graphics-programming
---


# Question
Title: How would you design components for an entity like this?
This is not a question about how to implement a component based system. I have my own system implemented and working fairly well, just can't figure out a good way to split some entities to fit the componnet based paradigm.

The entity is fairly simple, it can walk,jump and fire. It can get into some states like "frozen" that avoids movement of the player. It has other restrictions like can't do double jump.

In my current system, I have an input manager that has a target entity that receives events mapped to actions with semantics. I mean, my entity doesn't know about 'D' key or 'Left mouse click', it knows about Up,Down, Button1, etc...

Now the problem, when the user presses for example SPACE, the target entity is notified with a Left action and all the components are notified, but how would for example the Movement Component know that the entity is in "Frozen State" and it shouldn't be applying movement to it?.

Would you throw all this properties into an entity properties component and let all the other components check for them? Would you split entity in such a granulated level that a component for every property would be created? In this case we could have a component that has the "can be frozen" property and when it receives the collision with an ice projectil (it would be receiving a collision message) it can set the main entity state (that I would place it into the brain component) to frozen.

Could you suggest how you handle this tasks? The question could be rewritten as, How would you execute actions from an input system taking into account the restrictions of the entity.

Thanks in advance.

# Answer
There is an approach which is used to abstract input and translate inputs from multiple sources like gamepad, joystick, keyboard, touchscreen into game commands. It comes as an intermediate "intent system" used to capture most input messages.

The intent system can send intent commands/messages to all entities impacted if they have an intent component.

In the implementation I currently use, when an input event is trapped (keyboard, mouse, pen, touch...) the input system is notified, and if not handled by this system then the intent system is in charge... There only the relevant intent components are notified.

These components will then pass the resulting commands to other components like position, animation, particle and projectile generation, etc...

In your case the system will probably be simpler. All input can be collected and directly passed as intent (startAcceleratinToLeft, startJump, stopJump, startJump)... And your intent component will have access to all necessary data to manage the intents.

For example it will ignore the 2nd startJump because while your character is not colliding with a surface which can be used for jump the behavior component will simply ignore it or stash it for the post collision onTime() where it will be discarded if no collision with ground has happened.

I think this is the way to go, and if you want to scrap the intermediate messages (startJump, stopJump, etc) then handle the input directly in the intent component.

Additionally if there is no need for more intent handling (from AI, network or other sources) then you can directly handle intent in a dedicated module where the player entity is registered. But it's better to have this stem for later and to keep the game organized.
> 2 votes

---
Tags: game-design, component-based, entity-system
---


title: Understanding Fixed time step

text:
# Question
Title: Understanding Fixed time step
From what I understand about time based Euler Integration is that you will set a number of pixels you want your object to move in the space of second and then the value will be regulated based on the frame-rate of the machine your running the game on.

What I'm having issue with is this

```
 You will set your acceleration

 acceleration = 30;

```

Then that acceleration will be added to the velocity and multiplied by the time which would be say 0.0166667 if the frame-rate is 60fps which will cut down the velocity to the appropriate number for that frame which would be 0.50001

```
velocity += acceleration * dt;

```

but then when you add the velocity to the position it yet again multiplies the result by 0.0166667 which leaves you with 0.0833366667

```
position += velocity * dt;

```

What I'm trying to get is that instead of the 30 pixels per second I initially intended for the character to move I will need to put in an acceleration value of 1800.

I was wondering why this is done instead of simply multiplying the acceleration by the dt and leaving it at that ?

# Answer
> 3 votes
Acceleration is in units per second per second; it is the change in velocity over time. So you have to multiply it by time to get the change in velocity (units per second).

Similarly, velocity is in units per second; it is the change in position over time. So you have to multiply it by time to get the change in position (units).

You are not multiplying something by `dt` twice; you are multiplying the acceleration by `dt` to get the velocity change and adding it to velocity, then multiplying the velocity by `dt` to get the position change and adding it to position.

# Answer
> 0 votes
First you should understand that fixed time step is really much simpler than variable time step. If you like you can throw away `dt` completely, then your numbers will simply be per time step rather than per second.

Actually the only reason for including a `dt` in your code is that it makes it easy to change the update frequency while keeping everything else mostly constant.

---
Tags: physics
---


# Question
Title: Flash multi-player system: one player moves the other stops when using the mouse
I started making a small multi-player avatar chat to start my self with flash and multi-player. Everything worked fine when I was using arrows to move but when I started using the mouse something goes wrong.

Bit more info: When two or more users are connected at the same time and both on the users try to move one user will move and the other will stop in its tracks as the other users data is recived from the server.

EG: User one clicks to move and starts moving. Player two click while player one is in transit. Then player one stops before they reach there desired X,Y and user two carrys on until user one go's to move again.

When using the keys to move all players can move at the same time as there is no need for a loop which im guessing has something to do with the problem.

This is the code: http://pastebin.com/dCanCtP3

# Answer
> 1 votes
Every time you receive data, you overwrite your USER, MXX, and MYY global variables. You only store the data for one user at a time, so that is why only one user can move at any one time.

Consider making a class to represent a user and where it needs to move to, and then using an array to store all the users that are currently moving.

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


# Question
Title: 2D Collision: Check before or check after?
I'm using velocity to move my character, I just add/subtract 0.4f and then update the players position in the update loop.

I was wondering, when would be the best place to check for collision? Do I go ahead move the player, and then if I colliding push him out of the wall until there's no collision? Or do I check collision as soon as the key is pressed, and if there is - somehow find the distance and move the player?

My problem is that my game is tile based, but the world is constantly rotating around the player - I have a function that returns a list of objects of each block that the player is colliding with, and I'm having trouble separating wall collisions with floor collisions

# Answer
Both. As a body moves, there is a volume that it covers over a period of time. Imagine taking a sphere that moves along a line over a small period of time. The shape that it will cover (or "sweep") over this time is a capsule.

When you run your simulation over a time step, calculate these volumes and use those in your intersection testing. This will also solve the "Bullet through Paper" problem: if you have a very fast moving object move through a very thin object with a large enough time step, you won't detect the collision.

In your situation, there are lots of static objects; you can make an optimization to avoid calculating the swept volumes for these.

Interestingly, I just answered another question that is relevant, and will probably help you with other problems you're likely to encounter:

How to resolve penetration of two colliding bodies
> 6 votes

---
Tags: xna, 2d, collision-detection, platform
---


# Question
Title: What backwards compatibility to specify for an app for iOS and Android?
I'm having an app built, I'm not a programmer and I dont know exactly what to specify.

I want it to work on iPhones and iPads and iPod touches and also on Android devices - tablets as well as smartphones, and the Kindle Fire.

What backwards compatibility do I need to specify, at a sensible level?

# Answer
Android will be affected the most by backwards compatibility, because that API grew a lot between 1.x and 2.x. As someone who has done my fair share of playing with Android SDK, I'd personally say that the backwards limit for normal apps would be 1.6 (the vast majority of Android users have equal or newer devices than that), and games being 2.2 (that's about when they introduced multi-touch - something nearly mandatory for anything but the simplest of games).
> 2 votes

# Answer
For iOS it depends on whether the software needs to run on iPhone 4 or later hardware, or if its resource requirements are low enough to run on iPhone 3G.

A lot of iPhone 3G users did not update past iOS 3.1.2, so that's a good bar if you can / want-to capture them. If you don't care about iPhone 3G or if the app needs the hardware of iPhone 4, then target iOS 4.0.

There may be some particular features of your application which would require a specific later version, so YMMV.
> 1 votes

---
Tags: compatibility
---


# Question
Title: Clean way to detect collision of object with box2d
I have been looking into box2d (in java with libgdx) lately and have been trying to create my own custom bounce effect (I increase the `Restitution` after the first bounce)

To do this as a test I simply checked the location of the object and waited for the first bounce.

But now I wanted to actually implement this and came across a problem: How to detect the collision of 2 specific object in box2d?

I found this tutorial: box2d collision detection \- but I am very reluctant to use that code. There must be a simpler and cleaner way to detect a collision between 2 objects (without having to set user data and checking all collisions with giant `if()` conditions...)

Can anyone help me out? (assuming I am not just hopeful and there actually is a better way)

Help is greatly appreciated

Thanks, Jason

# Answer
> 3 votes
I think ultimately you will have to use user data but you can greatly reduce the number of collisions to check with collision filtering.

# Answer
> 1 votes
Add a trigger either to your moving ball or to the ground. A trigger is an volume causing some custom game action. Like reaching the end of the level or if a switch can be activated etc.

Your trigger class should know which objects caused the trigger to fire and can do the actual bouncing. Not sure how to do this with box2D though.

# Answer
> 1 votes
Have you tried this editor and its FixtureAtlas? If not, try it out. It automates several steps to make this work.

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


# Question
Title: How can I define a complex collision area on top of a tile map?
As many people recommended, I am using Tiled map editor to create a map for my game and it's great particularly because libgdx framework also provides with API for maps from Tiled.

I understand I can define collidable tiles or not in the map editor so I can deal with any collision in my code. But I am currently in a situation that I need to divide a tile into a collidable and non-collidable areas. Manually, I think I can define points and lines of bounds of the two areas and programmatically deal with it. But that's a lot of time-consuming work.

So I googled a lot and found this physics-body editor. This seems like a great tool to automate the process I mentioned above. The system, however, works with each of unpacked image and I am not sure it would work even if I unpack the image for its operation.

I wonder if there is any better way to do this whole process of defining collision area. Any suggestion will be much appreciated.

# Answer
> 21 votes
As usual I'll just throw a few ideas to the table. There are certainly several ways you can approach this problem. I'll describe the three I managed to remember, and it's up to you to decide which (if any) of these approaches is good for your project.

**Idea 1: Repeatable patterns in your tiles**

Does your system need to be flexible enough to support any conceivable collision area, or can you possibly break it down into a finite set of tile shapes that you can build with, and treat them as special cases? Here's a pair of resources to read up on this idea:

**Idea 2: Ignore the tilemap**

Yes, ignore the tilemap completly, and store a different, polygonal representation of your collision area. Then overlay this geometry on top of your tile based map, and handle collisions with it. If you don't need any physics, check the following resource:

Otherwise, I think you could probably use the tool you linked to.

**Idea 3: Pixel perfect collision detection**

Use pixel perfect collisions and use a separate mask or just the alpha channel in your tiles to encode your variable collision areas. For inspiration, check the following guide:

---
Tags: 2d, collision-detection, tiles, libgdx
---


# Question
Title: How to create a splash (loading) screen in cocos2d for Android?
How to create a splash (loading) screen in cocos2d for Android?

I need a loading screen that shows my app name and after that the next scene will show automatically.

Thanks

# Answer
Well, for cocos i have no idea. But I've done this with pure OpenGL-ES, I cant tell exactly how, since it depends in your implementation of Scene, your states, your sprite drawing, etc. But here's a pseudo code of how mine looks like:

```
SplashScreen::load()
{
    SetScreenClearColor(White);
    LoadTexture(R.drawable.GameLogo);

    StaticSprite sprite = new Sprite(R.drawable.GameLogo);
    sprite.setPosition(Screen.width / 2 - sprite.width / 2, Screen.height / 2 - sprite.height / 2);
    drawables.addToDraw(sprite);

    ScreenFader fader = new ScreenFader(White, 2);
    fader.setRectangle(0, 0, Screen.width, Screen.height);
    drawables.addToDraw(fader);
}

```

This will load your texture, put the logo in the center of the screen, register it to draw, create a ScreenFader(explain later) with a white color that would take 2 seconds to finsih, make the ScreenFader take the whole screen and register the ScreenFader to draw also.

The ScreenFader look like:

```
class ScreenFader
{
    float curTime;
    float endTime;
    boolean finished;
    Color color;
    ScreenFader(Color color, float endTime)
    {
        //some code to initialize vertices of a quad here
        //some code to attach color to vertices
        curTime = 0;
        this.endTime = endTime;
        this.color = color;
    }

    SetRectangle(int x, int y, int width, int height)
    {
        //set vertices to match the rectangle that was pass here
    }

    Update(float deltaTime)
    {
        if(!finished)
        {
            curTime += deltaTime;
            if(curTime >= endTime)
            {
                finished = true;
                curTime = endTime;
            }
            color.alpha = curTime / endTime;

        }
    }

    Draw()
    {
         DrawQuad(vertices, color);
    }
}

```

Thats it. And in your scene update, do this:

```
SplashScreen::Update(float deltatime)
{
    fader.Update(deltatime);
    if(fader.finished)
        ChangeScene(MainMenu); //Or something like
}

```

Hope it helps you to think in a way to do this.
> 1 votes

---
Tags: android, cocos2d, loading
---


# Question
Title: What are the time-efficiency characteristics of these voxel data structures?
Real-time, high-resolution voxel raycasters tend to use one of the following optimising data structures in order to achieve interactive frame rates. What are the pros and cons to these, and what other approaches are you aware of?

* Octrees
* KD-Trees
* Uniform 2D grid with run-length encodings for 3rd dimension (as used in Voxlap)

I am primarily concerned with their impacts on time efficiency rather than space efficiency, but feel free to respond on both aspects. This includes not only raycast time, but also reconstruction time following CSG ops.

I am interested specifically in real-time performance on the **CPU**, so please don't suggest that I skip the above in favour of GPU-centric volume rendering approaches which may not require these optimisations; those aren't of interest to me at this time.

# Answer
The octree vs. kd-tree debate seems ancient; as I recall I've seen both sides argued well. I can't speak about KD-trees with much experience, so I can only provide half the answer. That said, I know many optimizations that can be made to the Octree data structure, these could help you in your research, and are probably relevant:

Parametric Traversal (An Efficient Parametric Algorithm for Octree Traversal by J Revelles): I hear that similar optimizations exist for kd-trees, not sure how well they work. But for octrees the method described in this paper is fast even on the CPU, and I happen to know it's trivial to rewrite as optimized SIMD code. So be on the lookout for a similar thing. On that note,

SSE/NEON/Altivec: When looking into implementing both raycast and simple top-down traversal methods, see how well they vectorize. I wouldn't rely on the compiler for this, since it's such a specific and critical problem domain with so many nuances; in fact, I tend to lean towards writing at least my top-down routine in inline assembly for good measure. Beware of dodgy code-gen around intrinsics; spitting out "movups" everywhere is not unheard of.

Cache Coherence: KD-tree nodes are points with two subnodes each. Octree nodes have 8 or more; the result is that, while KD-Trees as implemented naively are easier, octrees are trivial to rewrite for better cache coherence. A cursory glance at google reveals some variety of methods described or advocated for cache-aware KD-tree optimization, only a few being pointer-less. With octrees, the way to go seems to be to store an integer offset in each node and use it to index a "node pool", which stores each group of 8 children in their own block. This, I've found, is fastest by at least an order of magnitude, and I don't see an equivalent boost coming from blocks of 2 subnodes. But you're welcome to try :D.

Since you're doing volume rendering, you may also want to check out Jon Olick's SIGGRAPH 2008 presentation on SVOs, from the "Beyond Programmable Shading" talk. Just find the link on his youtube demonstration. Aside from describing a structure similar to what I've outlined, it has a nifty optimization in it called "depth advance". The idea is to start the raycast close to the z-buffer of the previous frame, taking advantage of temporal coherence. Again, I don't know if this is possible with KD-trees, particularly since they don't subdivide along the z-axis and parametric traversal is likely harder, but you're welcome to try :D.

I don't mean to advocate one method or another, just pointing out that the basic algorithm is only as good as its implementation, and there are a lot of subtleties at play here.
> 2 votes

# Answer
> * Octrees
> * KD-Trees

Both provide ~around log time complexity to hit the wall yet, well implemented octree traversal apparently gives a little edge; however, KD traversal is simpler to implement.

> in favour of GPU-centric volume rendering approaches

I would love to test such GPU VR; in fact, for higher quality interactive rendering & bigger data-sets the best volumetric ray tracer running on dual x5670 outperforms any GPU setup I've tested so far.
> 1 votes

---
Tags: optimization, voxels, raycasting, csg
---


title: What is the metrics of vectors in XNA?

text:
# Question
Title: What is the metrics of vectors in XNA?
When exporting a model from 3ds Max as FBX to import it into XNA, what metrics should I choose to make 1 unit in 3ds Max equal to 1 unit in XNA?

For example: I have a sphere model with 1m radius exported to XNA. When drawing I use:

```
Matrix[] transforms = new Matrix[model.Bones.Count];
model.CopyAbsoluteBoneTransformsTo(transforms);
foreach (ModelMesh mesh in model.Meshes)
{
    foreach (BasicEffect be in mesh.Effects)
    {
        be.EnableDefaultLighting();
        be.World = mesh.ParentBone.Transform * Matrix.CreateScale(radius)
                    * TransformMatrix;
        be.View = camera.view;
        be.Projection = camera.projection;
    }
    mesh.Draw();
}

```

Radius is defined in my class as float.

This will draw a ball smaller than 1.

# Answer
> 4 votes
There isn't really a one-size-fits-all solution for this. You can make 1 unit in XNA equal to 1 metre, or 1 kilometre if you'd like. What I'd recommend is you find a transform and stick with it. Start with exporting a 1m sphere into XNA, adjust the scale and/or camera until it looks right, then base everything off that scale.

# Answer
> 2 votes
Not withstanding what Dman is conveying, since you are not following through fully with your matrix\[\] transforms, there may (or may not) be scaling information inside them that you are not taking into account when setting your be.World.

Use transforms\[mesh.parentBone.index\] instead of mesh.parentBone.Transform

---
Tags: c#, xna, 3dsmax, fbx
---


# Question
Title: The best option to multi-platform 2d mobile development
we are in the process of porting a game from iphone(made with cocos2s) to android(using the andEngine), and it has been a pain to do. So for our next project (a 2d game) we are thinking about using some multiplatform engine/framework. For now we are thinking about testing both unity, marmaled(former airplay sdk) and cocos2d-x. Do you have any opinion about this? Does someon have experience developing 2d games using Unity?

# Answer
I'm currently working on Unity to make a 2d game, not for mobile devices though. What I'm doing to keep it 2d is just to set the Z axis rotation of the camera to 0, and only move it on the X and Y axes. If you can afford the iOS license of Unity, then go for it, Unity really saves time on development, and you can make 3d games easily without messing with openGLES.
> 0 votes

# Answer
People have used cocos2d-x on top of Marmalade to add features such as particles that it is missing.
> 0 votes

---
Tags: android, iphone, cross-platform, mobile
---


# Question
Title: AS3 Internal preloader (one swf) for flash game with Embeded() images?
So I am using the Flash IDE.

And I am trying to make a preloader on Frame 1 so that it displays and loads progress before anything else is exported/loaded. So all my assets from the Library are on Frame 2 and all Actionscript Code is **Exported in Frame 2**.

But my Main Document class calls on other external classes that have Embeded images. Which are then exported in the First frame, which causes my game file to be huge in the First frame. And that essentially shows a white screen for a loong time before the preloader eventually shows up, but 60% loaded.

Is there a way to put the embeded images load later? (as in they would start loading in frame 2)

\[Slightly offtopic: I had an idea that I might import the images manually (its a tilesheet and a background image) to the Library. And then copypixel from the tilesheet. But I have never done this so I wouldnt know how to copypixel from something in the library\]

# Answer
If you have **Export classes in frame: 2** in your publish settings and use **Export in Frame 2** on your shared assets, then you really don't need the `[Embed]` meta-directive, as it's a Flex SDK thing. Also having everything in your library is going to be clearer.

So now the question is: How do you simulate the behavior of `[Embed]` using the flash library? Using the Flex SDK you would embed an image like this:

```
[Embed(source="asset.jpg")]
private var MyAsset:Class;

```

Creating a new instance of `MyAsset` would return a BitmapAsset instance, which is a subclass of `Bitmap`.

Using the Flash IDE, you would simply import the image to your library and then export it for ActionScript, as shown in the following screenshot:

I chose the same identifier ("MyAsset") as in the Flex example above.

Now we're basically set. The only difference is in instantiating the asset in code, as the types are different. As you can see in the screenshot, the Flash IDE automatically filled the Base class in for us, which is of type `BitmapData`. `BitmapData` is not a `DisplayObject`, so you cannot add it directly to your scene. So this won't work:

```
addChild(new MyAsset);

```

You would have to wrap it in a `Bitmap` to make it work:

```
addChild(new Bitmap(new MyAsset));

```

But since you're embedding a sprite-sheet which you blit to some other BitmapData object, you probably don't even want that. Therefore something like this will do:

```
var spriteSheet:BitmapData = new MyAsset;

```
> 0 votes

# Answer
I suggest you to use Flash Develop. It's open source and has a template that matches your needs: AS3 project with preloader

I switched from Flash IDE to Flash Develop about two years ago and I'm very satisfied. I converted almost all of my older projects to Flash Develop and it's very easy and quick to do that. I still have some issues with the debugger but it's nothing deadly.
> 1 votes

---
Tags: actionscript-3, platformer, preload
---


# Question
Title: Formula to calculate the changes in the fortunes of a stock based on how many shares are bought or sold
I am creating a stock market simulator for an event in my college. Supposing I have 20 companies in it all starting with a common base price, I need a formula to calculate the changes in the fortunes of a stock based on how many shares are bought or sold.

# Answer
> 5 votes
**TL;DR:**

```
/** A simplistic model for calculating share price.
 *
 *  @param company_value The total value of the company.
 *  @param number_of_shares The total number of shares in circulation.
 */
calc_share_price (company_value, number_of_shares) {
  return company_value / number_of_shares;
}

```

**Answer proper:**

If you had that, my friend, you would rule the world.

Unfortunately, stock values don't change as a function of buying and selling; they change as a function of their perceived value, which then causes people to sell and buy.

To elaborate; any model in which buying and selling directly affects the price is fundamentally broken and will cause a positive feedback loop.

If the cost of each share increases with people buying it, and the cost decreases with people selling it; then the only sensible thing to do would be to:

1. Buy as many shares as you can.
2. Wait until all other shares have been sold.
3. Sell all your shares.
4. Repeat.

Even as a simplistic model, this is woefully inadequate.

**To wit:**

To simulate a stock market; buyers and sellers must be able to determine the price themselves: A stock exchange just tracks the approximate value of a single share and makes trading easier.

There is a more in-depth explanation of how it works over at Economics; but the gist of it is: The value of a share of stock is roughly dependent on the value of the company and the number of shares, so those are the things you need to track.

Your problem is that buying and selling of shares in and of itself doesn't really change the value of the company; so you need some kind of external impulse to cause value changes.

---
Tags: mathematics
---