title: DirectX 9 light class

text:
# Question
Title: DirectX 9 light class
At the moment I am trying to create a tech demo in directX 9. I have a good understanding of basic lighting but, in my game/demo, I want to be able to create and light a scene like the following:

Could someone please help me and point me in the direction of a good base light class, or where I could learn how to implement one myself?

# Answer
That tech demo uses deferred rendering, it might be hard to get exactly that quality but it is perfectly possible to write a deferred renderer for DirectX9.

The idea behind deferred rendering is that you trade video memory for speed of calculating lighting. You create multiple render targets (using MRT) one for the lighting, one for the diffuse + specular intensity, one for the normals + specular power. Light calculations needed for adding a new light are performed on the data from the render targets (mainly from normals and depth data in there) so drawing an extra light means you don't have to draw the geometry an extra time. This way a scene with a dozen or even a hundreds of lights is possible, as opposite to a normal forward renderer where you have to draw all the geometry for each light, which quickly becomes costly.

Unfortunately computing shadows is still expensive but good designers have noticed that it's not necessary at all for all lights to cast a shadow to get a realistic scene.

An excellent example of this technique is the game S.T.A.L.K.E.R, and lucky for you they did a few articles on their implementation of the technique which are available for free at nVidia's developer pages.

Another similar technique is called light pre-pass of which some excellent slides by Wolfgang Engel are available here

Now as for some tutorials to point you at, I don't know of any specific C++/DirectX 9 one's, but to show it's possible this is a tutorial for deferred rendering in XNA, which uses only techniques available in DirectX 9 (XNA can't do any DirectX 10+ stuff since it has to run on the Xbox 360 as well)
> 2 votes

# Answer
Achieving the quality of lighting in the screenshot you provided and takes a team of programmers and a small army of artists. You're better off using an existing engine (like the Unreal Development Kit or CryEngine) which has the lighting you want.

However, if you want to do it yourself, I'd suggest taking a look at this presentation: Rendering Tech of Space Marine. It goes to great lengths to explain the techniques used in their DirectX 9 deferred renderer. It should either give you a starting point or let you realize that you've bitten off more than you can chew.

Keep in mind that it took them close to 6 years to develop Space Marine from scratch on Xbox 360 and PC.
> 0 votes

---
Tags: lighting, directx9
---


title: Geometry instancing in OpenGL ES 2.0

text:
# Question
Title: Geometry instancing in OpenGL ES 2.0
I am planning to do geometry instancing in OpenGL ES 2.0 Basically I plan to render the same geometry(a chair) maybe 1000 times in my scene.

What is the best way to do this in OpenGL ES 2.0?

I am considering passing model view mat4 as an attribute. Since attributes are per vertex data do I need to pass this same mat4, three times for each vertex of the same triangle(since modelview remains constant across vertices of the triangle).

That would amount to a lot of extra data sent to the GPU( 2 extra vertices\*16 floats\*(Number of triangles) amount of extra data).

Or should I be sending the mat4 only once per triangle?But how is that possible using attributes since attributes are defined as "per vertex" data?

What is the best and efficient way to do instancing in OpenGL ES 2.0?

# Answer
ES2 has neither glVertexAttribDivisor nor floating point textures so your options are quite limited.

Definitely put your chair model into a VBO if you're not doing so already. From there you're more or less restricted to individual draw calls - one per chair - so it's a question of getting the transformation matrix for each chair to the GPU as efficiently as possible.

You could do this with regular glUniform calls, or you could abuse some extra vertex attrib slots and make some glVertexAttrib (note: not glVertexAttribPointer) calls before drawing each chair, specifying the matrix using 4 such slots, and these values will "stick" for each subsequent vertex in the chair. That can be a fast enough path on some hardware but slower on other so you're going to have to experiment.

If your chairs don't rotate one other thing you can do is just send position to your shader and construct a new transformation matrix on the fly there. That sounds horrible but it's actually incredibly fast (it's just setting 3 floats) and might do the job.

On the whole though, and assuming that you're aiming for a typical mobile platform, I'm thinking that whatever you do, draw calls are going to kill you.
> 8 votes

# Answer
Your best bet is to use an instancing approach pretty similar to skinned models. Create a VBO that will hold many copies of your chair, all of them identical. Now, every vertex must have a byte attribute that will hold the index to the transform matrix that it will be applied to it. Send an array of matrices to your shader and use them as the world transform of each of your chairs. This way, you can draw in each call as many chairs as the maximum size of the array parameter, without having to rewrite any data in the VBO.
> 7 votes

# Answer
Wolfire Games has an excellent blog post about fast object instancing. What they do is render the model a bunch of times, but send a different matrix for each object to a uniform slot.

This is a pretty efficient way to instance a whole bunch of objects, because you only have to send the data once (the biggest bottleneck when rendering a batch of objects will always be bandwidth) and then transform the model in a shader.
> 3 votes

# Answer
http://www.youtube.com/watch?v=rfQ8rKGTVlg

This is a Google Talk on WebGL, which is OpenGL ES for JavaScript, meaning there's no geometry instancing either. It may give you an idea, though it's hard to tell because i don't know whether your bottleneck is on the GPU or the CPU.

Though, you should learn about uniform variables, there's absolutely no need to send a mat4 in an attribute, all vertices of your chair will be transformed by the same matrix, you have to send it only once per model, not per triangle. Uniform variables let you do that, they're a special kind of a variables that you can set in the shader program itself.
> 1 votes

---
Tags: opengl, opengl-es, opengl-es2
---


# Question
Title: How can I do fast Triangle/Square vs Triangle collision detection?
I have a game world where the objects are in a grid based environment with the following restrictions.

All of the triangles are 45-90-45 triangles that are unit length. They can only rotate 90°. The squares are of unit length and can not rotate (not that it matters)

I have the Square vs Square detection down and it is very very solid and very fast (max vs min on x and y values)

Wondering if there are any tricks I can employ since I have these restrictions on the triangles?

# Answer
**You could first treat every triangle as a square, then, once a collision with a triangle-as-square is detected, you could investigate further to see if collision actually occurred with the triangle.**

Since both triangle and square are convex shapes, an overlap is easily detectable when one contains one or more vertexes of the other.
For axis aligned square, *point containment test* is easy as checking for minimum ad maximum for both x an y.
For triangles a point is *in* when signed distances of it from lines edges are lying on (computed with constant winding) are all positive (or all negative depending on your distance function).

Since in your case edges are always 0°, 90° or 45°, the containment test is easy as checking **all** this conditions *(with AND operator)*

```
   A /|
 p. / | C
   /__|
     B

```
* p.x\<c.x
* p.y\>b.y
* p.x+p.y\> **K**

where **K** depends on the line equation of A and can be easily precomputed for the two cases (from lower right to upper left and the mirrored version) and adjusted with the position of the shape.
> 3 votes

# Answer
The triangle can be easily defined by three lines: horizontal, vertical, and diagonal:

* Line1: x = 0
* Line2: y = 0
* Line3: x = 1-y |/
* corner90: TOP\_LEFT

or

* Line1: x = 1
* Line2: y = 0
* Line3: x = y \\|
* corner90: TOP\_RIGHT

or

* Line1: x = 0
* Line2: y = 1
* Line3: x = y |\
* corner90: BOT\_LEFT

or

* Line1: x = 1
* Line2: y = 1
* Line3: x = 1-y /|
* corner90: BOT\_RIGHT

These weird symbols are pictures of triangles, I just didn't bother to draw horizontal lines.

Now, You need first to treat the triangle as a square. If it collides, then You need to check the square against triangle's slope.

Let's define a function to check if a point is on 'good' side of the slope (outside the triangle):

```
function isOutSlope ( x, y, corner90 ):Boolean {
if ( corner90 == TOP_LEFT ) return x > 1-y // x = 1-y; //    |/
if ( corner90 == TOP_RIGHT ) return x < y // x = y; //    \|
if ( corner90 == BOT_LEFT ) return x > y // x = y; //    |\
if ( corner90 == BOT_RIGHT ) return x < 1-y // x = 1-y; //    /|
}

```

Now we need to check just one point of square - the one that is closest to corner90, when the two shapes almost collide, but not yet. If triangle.corner90 is TOP\_LEFT, then it will be also top left corner of square , if corner90 is BOT\_RIGHT, then it is bot right corner of square etc. If You don't understand my point here, then sketch a few situations, where square and square would collide, but square and rectangle either don't, almost or do collide; that should clear it up a little bit.

Let's make another function to make it more readable:

```
function getCornerLocalPos ( corner ):Point {
if ( corner == TOP_LEFT ) return new Point (0,0)
if ( corner == TOP_RIGHT ) return new Point (0,1)
if ( corner == BOT_LEFT ) return new Point (1,0)
if ( corner == BOT_RIGHT ) return new Point (1,1)
//else throw ERROR ("THIS IS A CIRCLE!!!")
}

```

So, let's make the main function

```
function detectSquareToTriangleCollision ( rect, triang ):Boolean {
if ( !detectSquareToSquareCollision (rect,triang) ) return False //if two squares wouldn't collide, then by no chance they won't if one turns to be a triangle.

//These deltas are used to translate one coordinate context to another
delta_x = rect.x - triang.x
delta_y = rect.y - triang.y
p = getCornerLocalPos ( triang.corner90 )
p.x += delta_x
p.y += delta_y

return isOutSlope ( p.x, p.y, triang.corner90 )
}

```

I didn't test it, but I sketched a little bit to make sure most is valid. I wrote the code for readability, but optimizing is straight-forward. I am not a native english speaker and hence I'm sorry if I accidentally insulted Your mother or did any other faux pas. I assumed same as Mr Anton - the triangles rotate in steps of 90 degrees, not in 0-90 degree range. If that would be the case, the thing would be a little bit more tricky, but the isOutSlope function code should be helpful.
> 1 votes

# Answer
Keep doing max vs min tests as you are, but also test in two coordinate systems rotated +/- 45 degrees. I.e. test max vs min across x, y, (x - y) and (-x + y). This'll work since any edge in your environment will be aligned with one of these (assuming I correctly read between the lines of your question).

If their coordinates are integers you can even get away with only testing the rotated systems iff you are only testing against objects in the same "cell". But if you're not already keeping a map of what objects are in what cells and vice versa, then this pretty much amounts to the same thing as the above.
> 0 votes

---
Tags: collision-detection, mathematics
---


# Question
Title: Get video chipset manufacturer in Direct3D
I'd need to know if the video chipset Direct3D runs on is from **Nvidia, AMD or Intel**.

Is there a way to do that?

# Answer
Ha, found it with more googling.

D3D9: call `IDirect3D9::GetAdapterIdentifier` and check the `VendorId` of the provided `D3DADAPTER_IDENTIFIER9` structure.

D3D11: call `IDXGIAdapter::GetDesc` and check the `VendorId` of the provided `DXGI_ADAPTER_DESC` structure.

Video chipsets vendor IDs, retrieved from this list:

* Nvidia: **0x10DE**
* AMD: **0x1002**, 0x1022
* Intel: 0x163C, **0x8086**, 0x8087

In bold: the IDs mentioned in CardCaps.pdf (provided with the DirectX SDK), that add up with what Direct3D returns on actual hardware.
> 9 votes

---
Tags: directx, nvidia, amd, intel
---


# Question
Title: How do I interpolate air drag with a variable time step?
So I have a little game which works with small steps, however those steps vary in time, so for example I sometimes have 10 Steps/second and then I have 20 Steps/second. This changes automatically depending on how many steps the user's computer can take. To avoid inaccurate positioning of the game's player object I use `y=v0*dt+g*dt^2/2` to determine my objects y-position, where dt is the time since the last step, v0 is the velocity of my object in the beginning of my step and g is the gravity. To calculate the velocity in the end of a step I use `v=v0+g*dt` what also gives me correct results, independent of whether I use 2 steps with a dt of for example 20ms or one step with a dt of 40ms.

Now I would like to introduce air drag. For simplicity's sake I use `a=k*v^2` where a is the air drag's acceleration (I am aware that it would usually result in a force, but since I assume 1kg for my object's mass the force is the same as the resulting acceleration), k is a constant (in this case I'm using 0.001) and v is the speed.

Now in an infinitely small time interval a is k multiplied by the velocity in this small time interval powered by 2. The problem is that v in the next time interval would depend on the drag of the last which again depends on the v of the last interval and so on... In other words: If I use `a=k*v^2` I get different results for my position/velocity when I use 2 steps of 20ms than when I use one step of 40ms.

I used to have this problem for my position too, but adding `+g*dt^2/2` to the formula for my position fixed the problem since it takes into account that the position depends on the velocity which changes slightly in every infinitely small time interval.

Does something like that exist for air drag too? And no, I dont mean anything like Adding air drag to a golf ball trajectory equation or similar, for that kind of method only gives correct results when all my steps are the same. (I hope you can understand my intermediate english, it's not my main language so I would like to say sorry for all the silly mistakes I might have made in my question)

# Answer
> 0 votes
There is a similar expression for drag as well, and it is obtained in the same way: by solving the differential equation `v'=kv²`. It yields `v=v0 / (1 - k t v0)`. Note that coefficient `k` needs to be a negative number, because drag accelerates against the direction of the velocity. Assuming the coefficient does not change over time, the resulting velocity is independent of the timestep.

Though the calculated velocity might be accurate at every step, by numerical integration, the position is not, but since `v(t)` is a known function, we can integrate analytically too: `x = x0 + ln(1 - k t v0) / -k`.

# Answer
> 1 votes
It seems to me that the major problem you have is that your physics cannot be interpolated linearly, as you'd except. Because the air drag depends on the speed of the last interval, it has to be run at the same framerate constantly.

A good article on framerate is Fix Your Timestep!.

What I would do in your case is to run the physics simulation at a fixed framerate, for instance 30 frames per second, but run the rendering as fast as possible.

Here's the main loop I use for almost all my games:

```
g_TimeStart = GetTickCount() - (int)(g_FramePhysics + 1);

do
{
    g_TimeCurrent = GetTickCount();
    g_TimeStack += (float)g_TimeCurrent - (float)g_TimeStart;
    g_TimeStart = g_TimeCurrent;

    // when debugging, you'll end up with a gigantic stack of
    // frames to simulate, which is annoying
    // this puts a cap on the amount of frames to simulate
    if (g_TimeStack > g_FramePhysicsMax)
    {
        g_TimeStack = g_FramePhysicsMax;
    }

    while (g_TimeStack > g_FramePhysics)
    {
        glfwPollEvents();

        // to slow down the physics, we change this value
        g_Scene->Update(Scene::s_DeltaTime);

        RenderManager::Get().ClearInput();

        g_TimeStack -= g_FramePhysics;
    }

    // render scene

    g_Scene->Render();

    // render interface

    RenderInterface();

    // swap

    glfwSwapBuffers();
}
while (g_WindowOpen);

```

A mistake I made in the past is to have delta time be something like 1/30. The correct value is 1 for a simulation that runs at normal speed. Thus, to slow it down to 15 fps, you'd input a value of 0.5 into your physics simulation. The physics simulation will still run at a fixed 30 frames per second, but each frame will "weigh" less overall. However, you'll have to be careful with the delta time and figure out where you need to apply it in your physics simulation.

Are you updating a position with a velocity? Update the velocity with the delta time.

Are you updating a position with a velocity, but the acceleration of the velocity changes? Update the acceleration with the delta time, *but not the velocity*.

---
Tags: game-mechanics, physics, interpolation
---


# Question
Title: How do I get a new license for gDEBugger after the 1 free year?
I downloaded the gDEBugger from gremedy over a year ago, with their one year free license. The license has since expired and their site says that I'll be presented with the option for 1 year free license the first time I run it after install. This doesn't happen when re-installing, it just tells me the license has expired. How do I get a new license? I use this regularly for debugging shader problems and performance testing my game.

# Answer
Try deleting the C:\ProgramData\GraphicRemedy directory, run gDEBugger again and ask for a new temporary license.

If you are using linux, check the .gremedy directory and remove the existing license file.
> 2 votes

# Answer
**UPDATE**

As of December 2012, Gremedy has released a version of their software with the license mechanism disabled. It's available for download here.

> Version 5.8.1 Changed: Licensing mechanism disabled, it is no longer needed to acquire a free license to run gDEBugger.

---

The gDEBugger from gremedy appears to have been abandoned. Their forums have been down for a while and the last release on their site was December 16, 2010 with version 5.8.

AMD now hosts AMD gDEBugger. Their website has a release from April 20, 2012 with version 6.2 (as of this writing). The system requirements now list 'The latest AMD Catalyst driver'. The program will still operate without an AMD card, however kernel debugging will be disabled.
> 6 votes

---
Tags: graphics-programming, debugging
---


# Question
Title: Continuous Integration, what are the strategies to manage binary content?
Currently we are testing various configurations between Feature Branching and CI with Feature toggling.

I can see there are several viable options out there for the code, but I also know that CI totally relies on the possibility to merge the code.

So I wonder, how do you manage CI with binary data, like art assets?

I can also see another problem: all the code can be tested before to commit, I can even validate the data before to commit, but how can I test the art?!

Should I use another methodology for art content?

# Answer
> 1 votes
Using CI, just like any merge situation with binary data, the old data is simply replaced as a whole. You have the same end result, the data is up-to-date. The only downside is the transfer time. Since you have to transmit the entire file, instead of just the delta.

As for testing the art/other binary data. You have to think about: **how can the art/binary assets fail**?

* **Data corruption** \- If it's corruption you're worried about, that will be revealed at run time when the assets are being loaded, just like any run time code problems. In you data validation tests, you'll need to ensure you load the art assets too.
* **Numerical errors** \- Accidentally give some creature 1000 health instead of 100? It can be caught creating normal ranges, or statistical analysis to find outlayers. Otherwise you'll need a human checking.
* **Aesthetics** \- If you're worried about the art not looking right, sounds not sounding right or music that's too fast paced, well that's not something you can automatically test for. Just like logical errors in the code, aesthetic issues with your art assets need a human checking them.

You should use continuous integration for the art assets too. You won't find any more problems with art assets than you would with regular code.

---
Tags: methodology, asset-management
---


# Question
Title: How to Move a Player in a Tile-Based RPG
I've been following a JavaHub tutorial that basically uses a pixel engine similar to MiniCraft. I've attempted to make a Player Class as such, and I'm basically making a mock Pokemon game for learning's sake:

```
    package pokemon.entity;

    import java.awt.Rectangle;

    import pokemon.gfx.Screen;
    import pokemon.levelgen.Tile;
    import pokemon.entity.SpritesManage;;

    public class Player
    {
      int x, y;
      int vx, vy;
      public Rectangle AshRec;
      public Sprite AshSprite;
      Screen screen;
      Sprite[][] AshSheet;

      public Player()
      {
        AshSprite = SpritesManage.AshSheet[1][0];

        AshRec = new Rectangle(0, 0, 16, 16);

        x = 0;
        y = 0;

        vx = 1;
        vy = 1;

        screen.renderSprite(0, 0, AshSprite);
      }

      public void update()
      {
        move();
        checkCollision();
      }

      private void checkCollision()
      {

      }

      private void move()
      {
        AshRec.x += vx;
        AshRec.y += vy;
      }

      public void render(Screen screen, int x, int y)
      {
        screen.renderSprite(x, y, AshSprite);
      }

    }

```

I guess what I really want to do is have the Player centered in the screen and have the sprite drawn based on an Input Handler.

I have a render method in the main Game Class that I'm using to render the tiles for the map. I'd imagine I'd just need to add some parameters or methods in the Player Class? Do I create and render the sprite for the Player in the Main Class or Player Class?

Main render method:

```
    private void render()
    {
      BufferStrategy bs = getBufferStrategy();
      if(bs == null)
      {
        //Technically 3 dimensions;
        requestFocus();
        createBufferStrategy(3);
        return;
      }

      level.renderBkgrd(xScroll, yScroll, screen);
      level.renderSprite(0, 0, Ash.AshSprite);

      for(int i = 0; i < screen.pixels.length; i++)
      {
        pixels[i] = screen.pixels[i];
      }

      //Here are the graphics that you meticulously use to put in a separate paint method.
      Graphics g = bs.getDrawGraphics();
      g.drawImage(image, 0, 0, getWidth(), getHeight(), null);

      //If they are already drawn, don't show them again.
      g.dispose();
      bs.show();
    }

```

...And level.renderSprite() is what I thought would work...But without it the code gives me a NullPointerException.

**Update:**

Normally, a Game/Board/World class can aggregate all of the object updates and renderings. Knowing what I do now, in a World `update()` method, I typically throw the `player.update()` method in there and the drawing method in the World `draw()` method. The answer concerning through objects into an object manager is also a good suggestion, especially considering you could have multiple different enemies that will probably be deleted or updated synchronously in the near future as the game runs.

It appears I had a specific problem with an NPE (as general as it can be). It looks like I was over-complicating things way too much: I could just abstract the render/draw method out and have a player sprite (determined by the Player Class, if need be) rendered at the player's coordinates (again, determined by the Player Class). As you can see in the Player Class above I have a render method which calls the screen render method while I'm fiddling around with the Level instances rendering something in the main render() method and it's just a hot mess.

Moral of the story: A good game dev tutorial will offer you the reason for their methodology based on design patterns like separation of concerns that make the code much more maintainable.

# Answer
> 4 votes
I noticed in the comments you want to make an Entity Class.

This basically indicates you want all of your objects in the game for example your player, a building etc to share similarities. To do this you simply decide what are those similarities and put them in your entity class (for my example i will assume everything will have a position so X & Y and update and render method this would then become.

```
public class Entity {
  private int x;
  private int y;

 public int getX() {
   return x;
 }

 public void setX(int x) {
  this.x = x;
 }

 public int getY( {
   return Y;
 }

 public void setY(int y) {
  this.y = y;
 }

 public void update() {
 }

 public void render(Screen screen) {
 }
}

```

(Note my render method does not pass x, y as my entity will know its position.)

Now I my entity class I can create sub types of that class like player by doing

```
public class Player extends Entity
{
  @Override
  public void update() {
    //update logic for my player here
  }

  @Override
  public void render(Screen screen) {
     //Players Drawing logic here.
  }
}

```

No that i have a Base Class (Entity) I can put my objects in a list and then use that list to call the methods of each like so.

Add to list

```
List<Entity> objInMyGame = new ArrayList<Entity>();
obj.add(new Player());

```

iterate through them all to update them.

```
for(Entity e : objInGame) {
 e.update();
}

```

Hope this helps.

On a side note please take a look at Java coding conventions, it helps make your code more readable :)

# Answer
> 1 votes
Draw your player at:

playerX - cameraX playerY - cameraY

Then, set your camera to:

cameraX = (screenWidth / 2) - (playerX / 2) cameraY = (screenHeight / 2) - (playerY / 2)

---
Tags: java, rpg
---


# Question
Title: Image with FadeIn effect blinks when added to scene
I am trying to add an image to the scene, but it should just be added to the scene invisible, FadeIn and then be deleted when the effect finishes.

My problem is that the images *blink* once when they are added to the scene, then they do the intended effect. My best guess is that when they are added they show on the scene for a split second before starting the animation. I though of making them invisible for a split second before activating them, but I am not sure how to code it.

```
 const bool Sunbeams::add()
{
const CCSize kSceenSize = CCDirector::sharedDirector()->getWinSize();

const int nRayType = random( m_kRays.size());

const CCPoint kPosition( random( static_cast < int >( kSceenSize.width)),
                         0.0f);

const float fDuration = random( m_fDurationVariance) + m_fDurationMin;

CCSprite* pkLightBeam = CCSprite::spriteWithTexture( m_kRays[nRayType]);

if ( !pkLightBeam)
{
    msg::debug( "Sunbeams::add",
                "Failed to create sprite from ray '%d'!\n",
                m_kRays[nRayType]);

    return false;
}

pkLightBeam->setAnchorPoint( CCPointZero);

pkLightBeam->setPosition( kPosition);

m_kActiveBeams.push_back( pkLightBeam);

CCDirector::sharedDirector()->getRunningScene()->addChild( pkLightBeam);

CCActionInterval* pkAction = CCFadeIn::actionWithDuration( fDuration);

CCActionInterval* pkActionBack = pkAction->reverse();

pkLightBeam->runAction( CCSequence::actions( pkAction,
                                             pkActionBack,
                                             0));

return true;
}

```

# Answer
It was a problem with the alpha, the image was shown before the effect started

```
pkLightBeam->setOpacity( 0);

```

before adding it to the scene fixed it.
> 0 votes

---
Tags: cocos2d-x
---


# Question
Title: How do I raycast for a spherical harmonic shader using the iOS GPU?
I am beginning an Spherical Harmonics shader project for an iOS app I am writing. I have begun by reading this excellent in-depth paper on the subject.

The paper describes a scene pre-processing step that involves ray-casting (one bounce, shadow feeler). Can someone describe how ray-casting can be performed using GLSL on iOS?

# Answer
The raycasting is a *preprocess*. It has nothing to do with GLSL.

You raycast to find ambient occlusion, really. Where a ray does not strike any geometry, it is "open to ambient lighting" from that direction.

What Green is trying to do on page 26 is estimate the ambient occlusion function in spherical harmonics. To do so he *first* generates a "sphere of rays" in every which direction (page 7). He evaluates the SH function on each (l,m) band and saves that in a data structure coupled with the ray direction.

### Want: To estimate the ambient occlusion function at VERTEX in spherical harmonics

To estimate the ambient occlusion function at VERTEX in SH, you cast all the rays in the "sphere of rays collection". Call an example ray `RAY`. Where `RAY` DOESN'T strike anything, it should be used to estimate the ambient occlusion function at VERTEX. So, you add a *scaled copy* of the SH coefficients of RAY to the SH approx to of the ambient occlusion function at VERTEX. The scaled of the SH coefficients of RAY is the dot product of RAY with the VERTEX's normal.
> 1 votes

# Answer
Ray casting which therefore is ray tracing is very very expensive. If you want it in real-time, that would be impossible or only possible within very restricted scene.

I do not recommend calculating spherical harmonics for general scene in iOS. Alternatively, you can pre-calculate spherical harmonics values via PC and use them in iOS such as sh light map(or sh value for each vertex).

The method for ray casting is same as ray tracing. You can find much references and sources codes about it.
> -1 votes

---
Tags: ios, glsl, spherical-harmonics
---


# Question
Title: Using SurfaceFormat.Single and HLSL for GPGPU with XNA
**I'm trying to implement a so-called ping-pong technique in XNA**; you basically have two RenderTarget2D A and B and at each iteration you use one as texture and the other as target - and *vice versa* \- for a quad rendered through an HLSL pixel shader.

* step1: A--PS--\>B
* step2: B--PS--\>A
* step3: A--PS--\>B

...

In my setup, both RenderTargets are SurfaceFormat.Single.

In my .fx file, I have a tachnique to do the update, and another to render the "current buffer" to the screen.

Before starting the "ping-pong", buffer A is filled with test data with SetData\<float\>(float\[\]) function: this seems to work properly, because if I render a quad on the screen through the "Draw" pixel shader, i do see the test data being correctly rendered.

However, *if i do update buffer B*, something does not function proerly and **the next rendering to screen will be all black.**

For debug purposes, i replaced the "Update" HLSL pixel shader with one that should simply copy buffer A into B (or B into A depending on which among "ping" and "pong" phases we are...). From some examples i found on the net, i see that in order to correctly fetch a float value from a texture sampler from HLSL code, **i should only need to care for the red channel**.

So, basically the debug "Update" HLSL function is:

```
float4 ComputePS(float2 inPos  : TEXCOORD0) : COLOR0
{
  float v1 = tex2D(bufSampler, inPos.xy).r;
  return float4(v1,0,0,1);
}

```

which still doesn't work and results in a all-zeroes ouput. Here's the "Draw" function that seems to properly display initial data:

```
float4 DrawPS(float2 inPos  : TEXCOORD0) : COLOR0
{
  float v1 = tex2D(bufSampler, inPos.xy).r;
  return float4(v1,v1,v1,1);
}

```

Now: playing around with HLSL doesn't change anything, so maybe I'm missing something on the c# side of this, so here's the infamous Update() function:

```
_effect.Parameters["bufTexture"].SetValue(buf[_currentBuf]);
_graphicsDevice.SetRenderTarget(buf[1 - _currentBuf]);
_graphicsDevice.Clear(Color.Black); // probably not needed since RenderTargetUsage is DiscardContents
_effect.CurrentTechnique = _computeTechnique;
_computeTechnique.Passes[0].Apply();
_quadRender.Render();
_graphicsDevice.SetRenderTarget(null);
_currentBuf = 1 - _currentBuf;

```

Any clue?

# Answer
> 0 votes
Just found the answer myself, and it was a newbie issue.
Turns out the **vertex shader was shifting the wole rendering** that in a couple of updates, quickly exited the area visible when drawing results on the screen.

To fix this and have every pixel of the texture buffer aligned with its matching pixel on the RenderTarget buffer, **the drawn quad has to be from \[-1,-1\] to \[1,1\]** *(and not from \[0,0\] to \[1,1\] as one could be tricked to think)* and **following vertex transform is needed**:

```
output.Pos = input.Pos + float4(-0.5f/renderTargetSize.x, 0.5f/renderTargetSize.y, 0, 0);

```

so that *Pos* points exactly to the middle of a pixel/texel.

---
Tags: xna, c#, hlsl, gpgpu
---


# Question
Title: libgdx setOrigin and setPosition not working as expected?
I create a camera:

```
camera = new OrthographicCamera(5.0f, 5.0f * h/w);

```

Create a sprite:

```
ballTexture = new Texture(Gdx.files.internal("data/ball.png"));
ballTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
TextureRegion region = new TextureRegion(ballTexture, 0, 0, ballTexture.getWidth(), ballTexture.getHeight());
ball = new Sprite(region);

```

Set the origin, size, and position:

```
ball.setOrigin(ball.getWidth()/2,ball.getHeight()/2);
ball.setSize(0.5f, 0.5f * ball.getHeight()/ball.getWidth());
ball.setPosition(0.0f, 0.0f);

```

Then render it:

```
batch.setProjectionMatrix(camera.combined);
batch.begin();
ball.draw(batch);
batch.end();

```

But when I render it, the bottom left of my ball sprite is at (0, 0), not the center of it, as I would expect it to be because I set the origin to the center of the sprite. What am I missing?

# Answer
> 5 votes
setOrigin does not affect translation, only rotation and scaling.

Thanks to nEx. Software for their answer on SO.

---
Tags: android, libgdx
---


title: DrawImage doubt

text:
# Question
Title: DrawImage doubt
What is the best option for animation in a game (HTML5 Javascript)? Put all the images in one png and change the background.

Or create each image separately and draw with `DrawImage`?

# Answer
I would suggest using Texture Atlas, or as I call it, a Sprite Map. This is especially important for Javascript as it reduces the number of HTTP requests to the server. For example, 8 frames = 8 HTTP requests for non-mapped images.

Another advantage of using a Sprite Map is the fact that canvas already supports drawing 'sliced' images. When drawing an image, you can define a sourceX & sourceY as well as a targetX & targetY. In my engine this is exactly how I handled animations.

```
ctx.drawImage( data, sourceX, sourceY, sourceWidth, sourceHeight, targetX, targetY, targetWidth, targetHeight);

```
> 1 votes

# Answer
"To measure is to know" as the saying goes. Try both methods and see what works.

**Drawing each image separately**

Advantages:

* Lots of detail in your images.
* Fast artistic pipeline. Adding a new image doens't take much time, because it's just an image in a folder.
* Grouping can reduce image swapping. If your trees all use `tree1.png`, make a `TreeGroup` that attaches that image and renders all your trees.

Disadvantages:

* Easy to go over budget. Your images might be too large for your game and fixing it might take too much time.
* Image swapping. Constantly swapping out images can reduce framerate significantly.

**Texture atlas**

A texture atlas is a large texture that contains all smaller textures used in (a section of) the game.

Advantages:

* No swapping of images. All your sprites use the same image, just with different coordinates. This can be a speed benefit.

Disadvantages:

* Less detailed images. Everything has to fit in one image, so each image won't get as much space.
* Less artistic flexibility. It's hard for artists to fit all those images on a single large image.

Most likely you'll end up with a combination of the two techniques: a texture atlas for small, static objects and high-resolution images for your dynamic objects.
> 0 votes

---
Tags: javascript, html5, image
---


# Question
Title: What algorithms can I use for bullet movement toward the enemy?
I'm developing 2D strategy game. There are weapons that shoot at enemies. From what I've read in this, this, this and this post I think that I need linear algebra, but I don't really understand what algorithm I should use so the bullet will go to the target? Do I need a `pathfinder`, why?

Can you please suggest what algorithms and/or books I can use for bullet movement toward the enemy?

# Answer
I suggest you read Linear algebra for game developers part 1 / part 2 over on Wolfire's blog. They explain linear algebra quite easily - there aren't algorithms, just vector math. I know you linked that tutorial, but if you haven't read part 2 yet, **definitely read part 2** because it explains how this works.

### An overview of how it's done

The basic process is that you have a vector for the bullet's position, and a vector representing its movement in each frame, and you add this movement vector (also known as displacement vector) to its position on each update to move the bullet.

You determine the movement vector through vector math too: determine the vector from the bullet to the target (vector difference), which gives you the direction for the bullet to go in. To go at the right speed in that direction: normalize this vector (to give it a length/magnitude of 1), then multiply it by the speed the bullet should be going at. The resulting vector will be your movement vector.
> 8 votes

---
Tags: algorithm, movement, bullet-physics, tower-defense
---


title: Logic behind a bejeweled-like game

text:
# Question
Title: Logic behind a bejeweled-like game
In a prototype I am doing, there is a minigame similar to bejeweled. Using a grid that is a 2d array (`int[,]`) how can I go about know when the user formed a match? I only care about horizontally and vertically.

Off the top of my head I was thinking I would just look each direction. Something like:

```
int item = grid[x,y];
if(grid[x-1,y]==item)
{
    int step=x;
    int matches =2;
    while(grid[step-1,y]==item)
    {
        step++;
        matches++
    }
    if(matches>2)
        //remove all matching items
}
else if(grid[x+1,y]==item
    //....
else if(grid[x,y-1==item)
    //...
else if(grid[x,y+1]==item)
    //...

```

It seems like there should be a better way. Is there?

# Answer
> 7 votes
Loop through each item in the same axis (x or y), if they are the same as the previous item them increment matches. When the next item becomes different, check if matches is or greater than 3, call a function that removes matching items, and continue.

AS3 code:

```
var grid:Array = [[2,3,2,2,2,4],
                  [ .. ]]; //multidimensional array
var matches:uint;
var gemType:uint;
for(col = 0; col < grid.length; col++){
    matches = 0;
    gemType = 0; //Reserve 0 for the empty state. If we make it a normal gem type, then only 2 are needed to match for the start.
    for(i = 0; i < grid[0].length; i++){
        if(grid[col][i] == gemType){
            matches++;
        }
        if(grid[col][i] != gemType || i == grid[0].length - 1){ //subtract 1 because arrays start at 0
            if(matches >= 3){
                removeMatches(blah);
            }
            gemType = grid[col][i];
            matches = 1;
        }
    }
}

```

This is only for the x axis, for y, grid\[col\]\[i\] would become grid\[i\]\[row\], etc. I'm sure you can figure that out :)

# Answer
> 4 votes
Just thought I'd weigh in with our experience in building a Match-3-like game.

We have built a prototype for a Match-3 based word game, a little like mashing up scrabble and Bejeweled. We realized very early on that the engine that supplies new gems/tiles to fill empty spaces would have to be highly introspective (we run hybrid heuristics and MonteCarlo sampling) in order to create actual opportunities for a player to string letters to form words through the Match-3 mechanic. It's way more elaborate than the description but I'm keeping it brief because we'd have to write a paper.

To answer the OP -- we are doing pattern checks to score how many matches there are on any given gird, at the current time, through a method very similar to "gladoscc" code snippet. While it works robustly, the computational cost for running that recursively during the tree-search play-out becomes a substantial burden, so we are in the process of rewriting this portion of the logic and the data-representation with the bit-board methodology (commonly implemented in other-grid like games like chess, checkers, Othello, etc.) In tests we have shown that it can run over 20 times faster in ActionScript, and so for us the need to do it is a slam-dunk -- and frees up essential cycles for responsiveness, sound, animation, etc.

# Answer
> 2 votes
Recursion, yo. It's for when you don't know your boundaries.

```
   public int getHMatchSize(int row, int column)
    {
        int returnMe = getMatchValue(row, 0, column, 1);

        if (returnMe < 3)
        {
            return 0;
        }
        else return returnMe;
    }

    public int getVMatchSize(int row, int column)
    {
        int returnMe = getMatchValue(row, 1, column, 0);

        if (returnMe < 3)
        {
            return 0;
        }
        else return returnMe;
    }

    /// <summary>
    /// I return the match size.
    /// </summary>
    /// <param name="row"></param>
    /// <param name="rowDelta">1 means look vertically.  Dont set both deltas to 1.</param>
    /// <param name="column"></param>
    /// <param name="columnDelta">1 means look horizontally.  Dont set both deltas to 1.</param>
    /// <returns>The number of contiguous matching things</returns>
    public int getMatchValue(int row, int rowDelta, int column, int columnDelta)
    {
        int[] start = getEndItem(row, -1 * rowDelta, column, -1 * columnDelta);
        int[] end = getEndItem(row, rowDelta, column, columnDelta);

        int returnMe = 0;
        returnMe += end[0] - start[0];
        returnMe += end[1] - start[1];
        return returnMe;
    }

    /// <summary>
    /// I will return the end of a sequence of matching items.
    /// </summary>
    /// <param name="row">start here</param>
    /// <param name="column">start here</param>
    private int[] getEndItem(int row, int rowDelta, int column, int columnDelta)
    {
        Gem matchGem = new Gem(-1);
        int[] returnMe = new int[2];

        if (boardSpace[row + rowDelta][column + columnDelta] == boardSpace[row][column])
        {
            return getEndItem(row + rowDelta, rowDelta, column + columnDelta, columnDelta);
        }
        else
        {
            returnMe[0] = row;
            returnMe[1] = column;
            return returnMe;
        }
    }

```

# Answer
> 0 votes
You can use the flood fill algorithm. It's really useable to this type of problem.

---
Tags: algorithm, game-mechanics
---


title: Omni-directional shadow mapping

text:
# Question
Title: Omni-directional shadow mapping
What is a good/the best way to fill a cube map with depth values that are going to give me the least amount of trouble with floating point imprecision?

To get up and running I'm just writing the raw depth to the buffer, as you can imagine it's pretty terrible - I need to to improve it, but I'm not sure how.

A few tutorials on directional lights divide the depth by W and store the Z/W value in the cube map - How would I perform the depth comparison in my shadow mapping step?

The nvidia article here http://http.developer.nvidia.com/GPUGems/gpugems\_ch12.html appears to do something completely different and use the dot of the light vector, presumably to counter the depth precision worsening over distance? He also scales the geometry so that it fits into the range -.5 +.5 - The article looks a bit dated, though - is this technique still reasonable?

Shader code http://pastebin.com/kNBzX4xU

Screenshot https://i.stack.imgur.com/PB3ME.jpg

# Answer
> 2 votes
Your shader code looks a little confused to me. When you write out the depth value to the shadow map, you *must* divide Z/W in the pixel shader. The raw Z value you get after multiplying by the projection matrix can't be directly compared to anything else because the projection matrix is constructed assuming that Z is going to be divided by W, so if you leave out that step you're just screwing up your numbers.

Likewise, in the code for applying the shadow map, to generate the depth value for comparison, you should transform the point by the same matrix used to render the shadow map (the same world-to-clip matrix, anyway; clearly the local-to-world will be different if it's a different object). Then interpolate Z and W into the pixel shader and divide per-pixel, just the same way as for rendering the shadow map.

I think the errors in the screenshot you posted are due to the algorithm being incorrect, not to precision problems with the depth format. However, the simplest thing you can do to improve depth precision for projective shadows is to push out the near plane, so make sure you don't have a ridiculously small near plane value for your shadow map projection matrix.

---
Tags: hlsl, directx9, shadows, shadow-mapping
---


# Question
Title: Game thread, render thread, animation/inverse kinematics, and synchronization
In a multithreaded setup with a game logic thread and a render thread, with some kind of skin mesh animation with inverse kinematics plus etc how does animation work? Does the game logic thread just update a number saying time T in the animation and then the render thread infers Who owns the skin mesh animation, the game logic thread or the render thread? How is it stored in the scene graph if it is stored there at all? When the game logic updates does it do the computation of the skin mesh animation and the computation of the inverse kinematics and then store the result directly in the scene graph or is it stored indirectly and the render thread does the computation?

# Answer
> 0 votes
First of all, the question is too complex and unclear, but I'll try to answer it anyway.

"How does animation work?" - you can design however you want.

"Who owns the skin mesh animation, the game logic thread or the render thread" - what do you mean? Threads are just execution contexts. If you want to, with caution you can share data across threads, since all threads share the same address space ( -need to ensure no race conditions i.e. harder to design and debug; +saves RAM).

"stored indirectly and the render thread does the computation" - you can design however you want. The correct answer depends heavily on the CPU and RAM usage. If the computation is really cheap, but produces huge data set - you'll probably want to compute it on the main thread to save RAM. If however the computation is expensive but produce small dataset - you'll probably want to compute that on some other thread, store the result somewhere in RAM, and have the renderer thread get that result and update your scene graph with the new data.

P.S. I suggest you to read the following article: Designing the Framework of a Parallel Game Engine, esp. section #2. And this one: Multithreading the Rendering Pipeline for 3D Model Animation \- as you can see, they choose to duplicate the modified data across threads.

# Answer
> 2 votes
Don't design your threading like that. The idea of giving each system its own thread is not a good way to actually utilize the system. Game play and rendering really do work in lock step (if there's no gameplay update, there's nothing new to render). More importantly, there's only a few subsystems to a game engine, but there are a lot of cores in today's machine, and the core count is only increasing.

A better approach is to use a batch/job system. Run each system in lock step, but split up the work of the systems into threads. For rendering, that'll mostly be occlusion culling. For gameplay, it will often be path finding, and maybe ray casting and AI occlusion tests. For physics, it'll be various islands of separated objects.

One of the only systems worth giving its own dedicated thread is audio, and that's only because audio is super ridiculously sensitive to latency and stalls, far far more so than any other part of a game.

Once you design threads around batches instead of parallel systems, the ownership problem becomes much simpler. Instead of worrying whether gameplay or rendering owns a mesh, you instead know that only one or the other is touching the mesh at any given time. Your rendering jobs are then split into completely isolated batches of objects, so again there's very little contention to even think about.

---
Tags: animation, rendering, multithreading, synchronization
---


# Question
Title: Why is C/C++ preferred for game developers?
Some people say it offers more control to developers, but what is it precisely that can be controlled through C++ which can't be controlled using, for example, Java?

# Answer
Java runs in a virtual machine, while C++ is run directly on the hardware. What this means is that you have more control over where your memory goes and what is done with it in C++.

Java is a garbage collected language. You do not have direct control over your memory. You can allocate new chunks of memory, but you do not have (fine) control over when it gets deleted. The garbage collector checks every piece of memory you allocated every x frames and determines whether it's garbage or still being used.

For games this can be disastrous. Every few frames some garbage collector comes along to check *every single allocation you've made* to see if it's still being used? Talk about a slowdown!

Secondly, most of the libraries we use were either written in C or written in C++. I'm talking about Scaleform, Havok physics engine, PhysX, SpeedTree, etc. All professional packages, used extensively in the industry. If another language wants to be king, it better support them.

My personal view is that Java is really nice for desktop applications and apps, but not for games. Java has a lot of nice tools for developers and it can theoretically be run on any platform that has an implementation of the Java Virtual Machine, but I still prefer C++ because I *need* that control over my memory. Especially when you start working with exotic data structures (red-black tree, doubly linked list, etc.) it helps to keep a good overview of all your memory allocations.

I'm not saying: don't use Java. I'm saying: think about why you're using Java. Minecraft was built in Java, so it is certainly possible to build games in Java. But would it have been a better game, had it been built in C++? Well, it certainly wouldn't have been so cheap to get it running on the big three (Windows, MacOS, Linux), but even so, it encountered lots of platform-specific bugs in its development, bugs that Java couldn't smooth over.

There are tons of C++ frameworks now for beginning programmers. There's really no excuse not to learn it, especially if you want to further your career in the industry.
> 21 votes

# Answer
Short answer: C++ compiles to native code, so performance is up to the developer,not a runtime or VM.

Long answer:

C++ being "faster" has nothing to do with C++. At the moment, it is one of very few languages available that are supported by tools that produce standalone, native code for multiple platforms.

Back in the day, you could use C, C++, BASIC/2, Delphi, etc , and get efficient, freestanding executables. The choice of language was a matter of personal preference and market forces.

These days, the assumption that "C++ is faster" is essentially a self-fulfilling prophecy, though LLVM is in a good position to change that as it makes whatever goes into the parser moot, as it once was.

Borland had it right: Multiple languages that were parsed, first optimizations applied, then passed to a common backend compiler and linker. Which is effectively one of LLVMs major accomplishments.

Java is structured in such a way that it would be very difficult to implement without the JVM. Oddly enough, C#, commonly, and incorrectly, assumed to be roughly equivalent to Java, already compiles to native code on several platforms, including iOS.

Top of my Christmas list? A time machine to go back and add properties, real exception handling and actual WORKING polymorphism to C++, and get rid of the f"d up arrow syntax crap that the parser can figure out on its own. I wrote a preprocessor for that 10 years ago because it's freaking stupid.
> 2 votes

---
Tags: c++, java
---


# Question
Title: When to use Euler vs Axis angles vs Quaternions?
I understand the theory behind each but I was wondering if people could share their experiences in when one would use one over the other

For instance, if you were implementing a chase camera, a FPS-style mouse look or writing some kinematic routine, what would be the factors you consider to go with one type over the other and when might you need to convert from one form of representation to the other?

Are there certain things that only one system can do that the others can't? (eg smooth interpolation with quaternions)

# Answer
> 8 votes
I will quote John Carmack here:

> You will eventually regret any use of Euler angles.

Source

In my experience, I have found this to be true. Euler angles are terrible for:

* Relative orientation - parents to children, children to parents
* Camera's - it's good to use a matrix, better to use a quaternion
* Animation - matrices will have to be transformed to quaternions to be slerped anyway

However, if you want to store transformations as user-changeable text it's best to use Euler angles. Quaternions are difficult to wrap your brain around (4D space? What!) and a matrix looks like a mess of numbers to the average user.

But even here, you will probably regret their use eventually.

To answer your questions:

> chase camera

Quaternion camera with Vec3 position. However, if it's quick and dirty, I'd use a matrix camera with a lookat from a normal to the target.

> FPS-style mouse look

Quaternion camera with Vec3 position. Mostly because a quaternion camera doesn't have gimbal lock.

> some kinematic routine

Quaternions for rotation, Vec3 for position. Quaternions can be lerped (fast) and slerped (quality). The only downside is that they will have to be converted to matrices before being uploaded to a shader, but the benefits outweigh the cost in this case.

---
Tags: xna, 3d, mathematics
---


title: Trouble with Collada bones

text:
# Question
Title: Trouble with Collada bones
I have a Collada file with a rigged mesh. I've read the node tags in the library\_visual\_scenes tag and extracted the matrix for each node and stored everything in a hierarchical bone structure. My Matrix container is "row major", so I'd store the first float of a matrix tag in the 1st row, 1st column, the second in the 1st row, 2nd column, etc. From what I gather this is the Bind Pose Matrix. After that I went through the tag and extracted the float array in the source tag of the skin tag of the controller for the mesh. I stored each matrix from this float array in their corresponding Bone as the Inverse Bind Matrix. I also extracted the bind-shape-matrix and stored it.

Now I'd like to draw the skeleton with OpenGL to see if everything is working correctly before I go about skinning. I iterate once over my bones and multiply a bone's Bind Pose Matrix by it's parents and store that. After that I iterate again over the bones and multiply the result of the previous matrix multiplication by the Inverse Bind Matrix and then by the Bind Shape Matrix. The results look something like this:

\[0.2, 9.2, 5.8, 1.2 \]
\[4.6, -3.3, -0.2, -0.1 \]
\[-1.8, 0.2, -4.2, -3.9 \]
\[0, 0, 0, 1 \]

I've had to go to various sources to get the little understanding of Collada I have and books about 3d transform matricies can get pretty intense. I've hit a brick wall and if you could please read through this and see if there is something I'm doing wrong, and how I'd go about getting an X,Y,Z to draw a point for each of these joints once I've calculated the final transform, I'd really appreciate it.

# Answer
I see you are trying to parse a COLLADA file by hand. I was once as young and naive as you. Welcome to our shared hell. My COLLADA loader is 2837 lines long (one .cpp) and it doesn't even support *half* the spec.

Before we continue, I simply must point you to this excellent resource loader: ASSIMP. It has a silly name, but it will load any COLLADA file perfectly.

> My Matrix container is "row major"

Are you sure about that? OpenGL uses column-major matrices, in this format:

```
[ X1 Y1 Z1 WX ]
[ X2 Y2 Z2 WY ]
[ X3 Y3 Z3 WZ ]
[ TX TY TZ CZ ]

```

> From what I gather this is the Bind Pose Matrix.

The nodes will either be a node for a mesh or a joint, as you probably realize by now. You are correct, the animation source list (the combination of `translate`, `rotate` and `scale` tags inside the `node` tag) is the bind pose. *But it is not required!* If no animation source list is provided, you must use the inverse bind matrix and inverse it to get the bind matrix. For rendering models with skinned animation, however, you only need the inverse bind matrix.

The inverse bind matrix for a joint is defined in the skin.

For each node that is not a joint (every mesh), you must look up the skin using either the id or the name as specified in the node tag. A node with a skin has an `instance_controller` tag with a `url`.

Then you have to add the joints to the skeleton for this model. Keep in mind that a skin might not have inverse bind matrix definitions for every joint, to keep things easy.

Here's what that looks like in my code. It also explains why COLLADA is so hard to parse.

```
std::string* src_name = (*it)->skin_ptr->vertex_weights->input_joint_names->source_ptr->data->GetStringData();
float* src_matrix = (*it)->skin_ptr->vertex_weights->input_inv_bind_matrix->source_ptr->data->GetFloatData();

for (unsigned int j = 0; j < (*it)->skin_ptr->vertex_weights->input_inv_bind_matrix->source_ptr->data0>count; j++)
{
    // collada stores its matrices as row-major, my matrix class uses column-major

    tb::Mat4x4 inv_bind_matrix;

    inv_bind_matrix[tb::Mat4x4::X1] = src_matrix[ 0];
    inv_bind_matrix[tb::Mat4x4::Y1] = src_matrix[ 4];
    inv_bind_matrix[tb::Mat4x4::Z1] = src_matrix[ 8];
    inv_bind_matrix[tb::Mat4x4::WX] = src_matrix[12];

    inv_bind_matrix[tb::Mat4x4::X2] = src_matrix[ 1];
    inv_bind_matrix[tb::Mat4x4::Y2] = src_matrix[ 5];
    inv_bind_matrix[tb::Mat4x4::Z2] = src_matrix[ 9];
    inv_bind_matrix[tb::Mat4x4::WY] = src_matrix[13];

    inv_bind_matrix[tb::Mat4x4::X3] = src_matrix[ 2];
    inv_bind_matrix[tb::Mat4x4::Y3] = src_matrix[ 6];
    inv_bind_matrix[tb::Mat4x4::Z3] = src_matrix[10];
    inv_bind_matrix[tb::Mat4x4::WZ] = src_matrix[14];

    inv_bind_matrix[tb::Mat4x4::TX] = src_matrix[ 3];
    inv_bind_matrix[tb::Mat4x4::TY] = src_matrix[ 7];
    inv_bind_matrix[tb::Mat4x4::TZ] = src_matrix[10];
    inv_bind_matrix[tb::Mat4x4::CZ] = src_matrix[15];

    (*it)->skin_ptr->joint_names.push_back(*src_name);
    (*it)->skin_ptr->inverse_bind_matrices.push_back(inv_bind_matrix);

    src_name++;
    src_matrix += 16;
}

```

So, here's what you have to do if you want to draw the skeleton:

* Parse the root skeleton (all joints)
* Locate the mesh you want to draw.
* Locate the skin for the mesh.
* Parse the inverse bind matrices in the skin and put them in the skeleton for the joint.
* To get a joint's bind matrix, multiply its parents inverse bind matrix (recursive) with its inverse bind matrix and inverse it.
* To get a joint position, get the translation part of the matrix.
* Draw lines between every joint used by the model.

And then you're not even there yet. Because every node might also have a local transformation. And that complicates matters to an insane degree.

So unless you have no other choice, use ASSIMP! It will save you headaches and nightmares.
> 3 votes

---
Tags: opengl, 3d, matrix, linear-algebra, collada
---


# Question
Title: How do I go from a simple html5 tic tac toe game to an online 2 player game?
I've been working on an online 2 player Tic Tac Toe solution for blackberries. both old and new. And so far I have html5 code that has a 3 x 3 layout that switches between x and o for the game mechanics. I believe I'm still missing a check for win function but my question is about the server side of this game. I'm not sure how to go about learning what exactly I want. how do you take what I have now, and make this into a functioning online game?

I've been told WAMP is a good solution, as well as IIS. and its all really over my head, so i'm hoping to get a little more clarity as far as what I should focus on to bring this game to life.

# Answer
If you're building in HTML5 I suggest you look into Node.js and Socket.IO, as they fit well for your type of gameplay and are easy to implement due to Node.js' event loop. On top of that, you only need to use javascript for the client and server.
> 1 votes

---
Tags: javascript, html5, server, client-server
---


title: as3 3D camera lookat

text:
# Question
Title: as3 3D camera lookat
I'm making a 3D camera scene in Flash, draw using drawTriangles() and rotated and translated using a Matrix3D. I've got the camera to look after a specific point, but only on the Y-axis, using the x and z coordinates, here is my code so far:

```
var dx:Number = camera.x - lookAt.x;
var dy:Number = camera.y - lookAt.y;
var dz:Number = camera.z - lookAt.z;

camera.rotationY = Math.atan2(dz, dx) * (180 / Math.PI) + 270;

```

so no matter the x or z position, the point is always on the mid of the screen, IF and only if y matches with the camera. So what I need is to calculate the rotationX (which are measured in degrees not radians), and I was wondering how I would do this?

# Answer
Well, if you're going to do it manually like you're doing right now, you're going to have a bad time.

What you need is actually two matrices: a projection matrix and a camera matrix. First you transform your triangles from world space (in the scene) to camera space (around the camera) and then from camera space to screen space (on the screen).

The first transformation is done using a camera matrix, while the second is done using a projection matrix.

Now, I'm going to assume you don't care about correct perspective, so I'll give you a matrix for an *orthographic projection*. It looks like there is no matrix class in standard AS3, so I'll give you a generic answer.

First, you will need to store 16 floating point numbers. They are aligned in the following configuration:

```
[ X1 Y1 Z1 WX ]
[ X2 Y2 Z2 WY ]
[ X3 Y3 Z3 WZ ]
[ TX TY TZ CZ ]

```

So that's four rows of four floating point numbers.

Let's build an identity matrix, which is a special matrix that doesn't change the input vector.

```
 [ 1.0 0.0 0.0 0.0 ]
 [ 0.0 1.0 0.0 0.0 ]
 [ 0.0 0.0 1.0 0.0 ]
 [ 0.0 0.0 0.0 1.0 ]

```

Next, we will need to know the viewport, the dimensions of the screen.

```
 view_x = 0;
 view_y = 0;
 view_w = GetScreenWidth();
 view_h = GetScreenHeight();

```

And also a value for z-near and z-far. But we can set that to -1 and 1, because we're not interested in perspective projection.

```
 z_near = -1;
 z_far = 1;

```

Now we can fill our matrix:

```
Identity();

values[X1] =  2.f / (view_w - view_x);
values[Y2] =  2.f / (view_y - view_h);
values[Z3] = -2.f / (z_far - z_near);

values[TX] = -(view_w + view_x) / (view_w - view_x);
values[TY] = -(view_y + view_h) / (view_y - view_h);
values[TZ] = -(z_far + z_near) / (z_far - z_near);

```

But was just the first step! Now we have a projection matrix, but not a camera matrix.

Again, start with an identity matrix:

```
 Identity();

```

We'll need three vectors: the camera position, the camera target and a world up vector. World up is usually `(0.0, 1.0, 0.0)`, so we'll keep it that way for now.

```
 Vec3 camera_pos = GetCameraPosition();
 Vec3 camera_target = GetCameraTarget();
 Vec3 world_up = Vec3(0.0, 1.0, 0.0);

```

Now we can build three normalized vectors: `f`, `s` and `u`.

```
Vec3 f = (camera_target - camera_position).GetNormalized();
Vec3 u = world_up.GetNormalized();

Vec3 s = f.GetCrossProduct(u).Normalize();
u = s.GetCrossProduct(f);

```

And now we can fill our camera matrix:

```
values[X1] = s.x;
values[X2] = s.y;
values[X3] = s.z;
values[WX] = 0.0;

values[Y1] = u.x;
values[Y2] = u.y;
values[Y3] = u.z;
values[WY] = 0.0;

values[Z1] = -f.x;
values[Z2] = -f.y;
values[Z3] = -f.z;
values[WZ] = 0.0;

values[TX] = -u.GetDotProduct(camera_position);
values[TY] = -s.GetDotProduct(camera_position);
values[TZ] = f.GetDotProduct(camera_position);
values[CZ] = 1.0;

```

Once you have these matrices, it becomes a piece of cake to transform coordinates to screen space:

```
Vec3 homogenized_position = camera_projection * camera_transform * src_position;

```

Here, we're transform the incoming `src_position` with the matrices and the matrices with each other. Multiplying matrices:

```
Mat4x4 Mat4x4::operator * (Mat4x4 a_Other)
{
    float a0, a1, a2, a3;

    Mat4x4 result;

    a0 = a_Other.values[X1];
    a1 = a_Other.values[Y1];
    a2 = a_Other.values[Z1];
    a3 = a_Other.values[WX];

    result.values[X1] = (a0 * values[X1]) + (a1 * values[X2]) + (a2 * values[X3]) + (a3 * values[TX]);
    result.values[Y1] = (a0 * values[Y1]) + (a1 * values[Y2]) + (a2 * values[Y3]) + (a3 * values[TY]);
    result.values[Z1] = (a0 * values[Z1]) + (a1 * values[Z2]) + (a2 * values[Z3]) + (a3 * values[TZ]);
    result.values[WX] = (a0 * values[WX]) + (a1 * values[WY]) + (a2 * values[WZ]) + (a3 * values[CZ]);

    a0 = a_Other.values[X2];
    a1 = a_Other.values[Y2];
    a2 = a_Other.values[Z2];
    a3 = a_Other.values[WY];

    result.values[X2] = (a0 * values[X1]) + (a1 * values[X2]) + (a2 * values[X3]) + (a3 * values[TX]);
    result.values[Y2] = (a0 * values[Y1]) + (a1 * values[Y2]) + (a2 * values[Y3]) + (a3 * values[TY]);
    result.values[Z2] = (a0 * values[Z1]) + (a1 * values[Z2]) + (a2 * values[Z3]) + (a3 * values[TZ]);
    result.values[WY] = (a0 * values[WX]) + (a1 * values[WY]) + (a2 * values[WZ]) + (a3 * values[CZ]);

    a0 = a_Other.values[X3];
    a1 = a_Other.values[Y3];
    a2 = a_Other.values[Z3];
    a3 = a_Other.values[WZ];

    result.values[X3] = (a0 * values[X1]) + (a1 * values[X2]) + (a2 * values[X3]) + (a3 * values[TX]);
    result.values[Y3] = (a0 * values[Y1]) + (a1 * values[Y2]) + (a2 * values[Y3]) + (a3 * values[TY]);
    result.values[Z3] = (a0 * values[Z1]) + (a1 * values[Z2]) + (a2 * values[Z3]) + (a3 * values[TZ]);
    result.values[WZ] = (a0 * values[WX]) + (a1 * values[WY]) + (a2 * values[WZ]) + (a3 * values[CZ]);

    a0 = a_Other.values[TX];
    a1 = a_Other.values[TY];
    a2 = a_Other.values[TZ];
    a3 = a_Other.values[CZ];

    result.values[TX] = (a0 * values[X1]) + (a1 * values[X2]) + (a2 * values[X3]) + (a3 * values[TX]);
    result.values[TY] = (a0 * values[Y1]) + (a1 * values[Y2]) + (a2 * values[Y3]) + (a3 * values[TY]);
    result.values[TZ] = (a0 * values[Z1]) + (a1 * values[Z2]) + (a2 * values[Z3]) + (a3 * values[TZ]);
    result.values[CZ] = (a0 * values[WX]) + (a1 * values[WY]) + (a2 * values[WZ]) + (a3 * values[CZ]);

    return result;
}

```

And multiplying a Vec3 with a matrix:

```
Vec3 Mat4x4::operator * (Vec3 a_Vector)
{
    Vec3 result;

    float x = (a_Vector.x * values[X1]) + (a_Vector.y * values[X2]) + (a_Vector.z * values[X3]) + values[TX];
    float y = (a_Vector.x * values[Y1]) + (a_Vector.y * values[Y2]) + (a_Vector.z * values[Y3]) + values[TY];
    float z = (a_Vector.x * values[Z1]) + (a_Vector.y * values[Z2]) + (a_Vector.z * values[Z3]) + values[TZ];
    float w = (a_Vector.x * values[WX]) + (a_Vector.y * values[WY]) + (a_Vector.z * values[WZ]) + values[CZ];

    result.x = x / w;
    result.y = y / w;
    result.z = z / w;

    return result;
}

```

However, one last step is still required. These coordinates will be in homogenized space, ranging (-1, 1) for x and y. That's not what we want, so we'll convert it to pixel coordinates:

```
Vec2 screenspace_position = Vec2(
    (homogenized_position.x * 0.5 + 0.5) * GetScreenWidth(),
    (1.f - (homogenized_position.y * 0.5 + 0.5)) * GetScreenHeight()
);

```

If you are having trouble understanding any of this, first try to implement it. Look up things you don't know. Perhaps you don't know how to do the cross product of two Vec3's or what a normalized vector is. Figure out how to implement it, then try to understand what all this code does.
> 0 votes

---
Tags: 3d, mathematics, actionscript-3, camera
---


# Question
Title: Tutorials for Managed DirectX development?
Are there any good tutorials, for someone new to DirectX development? I'd like to use the SharpDX library in a project, but am completely new to this sort of graphics programming. I'm looking for a good resource for very beginner-level DirectX samples, either on the web or in print? I assume the code there will be C++, but I'm hoping they'll be straightforward enough for me to map to C#.

# Answer
You might want to have a look at Microsoft XNA. It's not the whole DirectX deal but it comes close in terms of features. To understand the interface, you need (basically) no prior knowledge of DirectX/C++. It comes with its own abstractions and might thus be more approachable for you if you don't need as much low-level access as DirectX (and its managed wrappers) would normally allow. Furthermore, the XNA Game Studio should come with some samples and tutorials that make it easier to get into graphics programming.

I'm sorry I can't say for sure, though, as I've only gone the C++/DirectX route myself.
> 0 votes

# Answer
Riemers.net has some pretty easy to follow tutorials on programming wwith DirectX directly from c++ or with XNA. Helped me a lot!

http://www.riemers.net/eng/Tutorials/dxcpp.php
> 0 votes

# Answer
Excuse the self promotion, but I'm in the process of writing some tutorials for Windows 8 Metro using SharpDX and C#, starting from the basics. You can find them in my blog.

Jose Fajardo has a collection of SharpDX demos, but since they use XAML interop, they are pretty hard to understand unless you have some knowledge of Windows 8 development.

And the full package of SharpDX comes with some nice examples, too.
> 0 votes

---
Tags: c#, directx, slimdx, sharpdx
---


# Question
Title: XNA Platformer Sample: Supporting multiple resolutions?
I have been looking at the XNA Platformer Sample and noticed that, when you change the resolution, the game world still renders at 800x480 and not the new width and height of the display.

Can anyone suggest a simple way to make the Platformer sample support multiple resolutions?

# Answer
First of all, to test this answer on Windows, use a fresh copy of the game and add the following line to the constructor of `PlatformerGame`.

```
Window.AllowUserResizing = true;

```

This will let you resize the window and see the changes in action.

---

The easiest way is to simply **scale the game so that it fits on screen**. You need to pass a scaling matrix to `SpriteBatch.Begin`.

Here I have provided code to calculate a matrix that will "fit" the content into the available space and centre it:

```
var gameWorldSize = new Vector2(800, 480);
var vp = GraphicsDevice.Viewport;

float scaleX = vp.Width / gameWorldSize.X;
float scaleY = vp.Height / gameWorldSize.Y;
float scale = Math.Min(scaleX, scaleY);

float translateX = (vp.Width - (gameWorldSize.X * scale)) / 2f;
float translateY = (vp.Height - (gameWorldSize.Y * scale)) / 2f;

Matrix camera = Matrix.CreateScale(scale, scale, 1)
        * Matrix.CreateTranslation(translateX, translateY, 0);

spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, camera);

```

(Note the way that I scale by 1 and translate by 0 on the Z axis. Not modifying the Z axis of sprites is important when using `SpriteBatch`.)

Note that, when you scale the game like this, any graphics that are "pixel perfect" will no longer be perfectly aligned to any pixels. One way to solve this is to have multiple versions of your assets at different, fixed scales - draw them at fixed world sizes (not by their pixel size) and then only allow `scale` in the above code to be a set of fixed values matching those asset sizes.

---

The other way is to **implement a scrolling camera** (focused on the player). This is good because it allows the world to be any size, independent of the screen size.

```
var vp = GraphicsDevice.Viewport;

float translateX = vp.Width / 2 - level.Player.Position.X;
float translateY = vp.Height / 2 - level.Player.Position.Y;

Matrix camera = Matrix.CreateTranslation(translateX, translateY, 0);
spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, camera);

```

A good camera will "lag" a little bit behind the player in order to feel more natural. You can find lots of tutorials on making a good platformer camera online.

Continuing on my notes about keeping assets fixed to the pixel grid: This method allows you to do this with a single set of assets. Just make sure your camera position is rounded to the nearest pixel if this is what you want to do.

---

Note that the HUD is - in the original sample - sharing the same sprite batch as the level display. This will cause HUD elements to appear in the wrong place. You should separate them out so that the HUD is not affected by the camera, like so:

```
spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, camera);
level.Draw(gameTime, spriteBatch);
spriteBatch.End();

spriteBatch.Begin();
DrawHud();
spriteBatch.End();

```

---

You can, of course, combine these approaches and come up with your own variations (like the fixed-scales-multiple-graphics-sets variation I suggested earlier). What you do will depend on the game you are making.

Obviously both methods require you to make the game world larger so that it looks nice when you can see beyond its edge. I'll leave this as an exercise.

There are a few other good questions on handling 2D game scaling on this site. Here is one such question.
> 7 votes

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


# Question
Title: How to build Arena-ish level using grid tiles?
I had an idea of procedurally generating arena-type levels in which the player would either fight hordes of enemies, or another skilled opponent. The level would be built at the very start of the layout, and will have a layout similar to those in Quake Live; Pickups, enemy spawners, etc. What would be the best way to achieve this?

# Answer
Algorithms are specific solutions for specific problems, for level generation you don't need algorithms, just logic.

First of all you need a specific idea how the maps should look like, then you need a few abstract data types which describes the features of the map, in this case those could be: player start point, platforms, pathways.

Now you have set those you need to distribute them: where should platforms be placed and where the player start point? Also how many platforms? When you have done that you can connect the Platforms by Pathways.

Having that basic structure set up you then can place game play details: you could connect a few platforms by jumpers and put item spawns on others.

Short example pseudo code:

```
func generateMap(int width, int height)
{
  struct Point{ int x, y; };
  struct Connection{ Point start, end; };
  list<Point> platforms;
  list<Connection> pathways;
  Point player;

  // Set Player point somewhere on the left side in the middle:
  player = { width/4+Random(-100, 100), height/2 };
  platforms.append(player);

  // Now distribute a few more platforms:
  int numPlatforms = (width*height)/300+Random(-2, 2);
  for(i=0; i < numPlatforms; i++)
  {
    /* Insert code here to generate random coordinates which are not too near to the already existing platforms*/
    platforms.append({x, y});
  };

  // Make connections (for simplicity sake here just randomly, this doesn't really work well obviously.)
  foreach(Point platform in platforms) pathways.append( {platform, platforms[Random(platforms.length)]} );

  // Quake style arenas are symmetrical so just mirror what you already have here.
  [...]

  // Now do stuff like generating a Tile map from that data, depends a lot on the underlying engine.
  [...]
}

```
> 1 votes

# Answer
You're unlikely to find a standard algorithm for doing that. Also, I'm not sure you'd get the structural aspects you want from using pure noise. I'd look into how procedural cities or building are generated, then apply those to making your own algorithm. There's a Survey of Procedural City Generation (pdf). Then over at the Procedural Content Generation Wiki, there's a good list of links related to dungeon generation. Hopefully this is enough to get you started.
> 0 votes

---
Tags: 2d, sprites, procedural-generation, levels
---


title: Why is my ground so dark?

text:
# Question
Title: Why is my ground so dark?
I wanted to add a ground so I can know the position of a helicopter in the world. But the ground appeared in a weird way:

The ground had the following texture:

This is the code:

```
public class ImportModel
{
    public Vector3 Position { get; set; }
    public Vector3 Rotation { get; set; }
    public Vector3 Scale { get; set; }
    Model Model;
    Matrix[] modeltransforms;
    GraphicsDevice GraphicDevice;
    ContentManager Content;
    BoundingSphere sphere;
    bool boundingimplemented = false;
    public ImportModel(string model, GraphicsDevice gd, ContentManager cm, Vector3 position, Vector3 rot, Vector3 sca)
    {
        GraphicDevice = gd;
        Content = cm;
        Position = position;
        Rotation = rot;
        Scale = sca;
        Model = Content.Load<Model>(model);
        modeltransforms = new Matrix[Model.Bones.Count];
        Model.CopyAbsoluteBoneTransformsTo(modeltransforms);
    }
    public void Draw(Camera camera)
    {
        Matrix baseworld = Matrix.CreateScale(Scale) * Matrix.CreateFromYawPitchRoll(Rotation.Y, Rotation.X, Rotation.Z) * Matrix.CreateTranslation(Position);
        foreach (ModelMesh mesh in Model.Meshes)
        {
            Matrix localworld = modeltransforms[mesh.ParentBone.Index] * baseworld;
            foreach (ModelMeshPart meshpart in mesh.MeshParts)
            {
                BasicEffect effect = (BasicEffect)meshpart.Effect;
                effect.World = localworld;
                effect.View = camera.View;
                effect.Projection = camera.Projection;
                effect.EnableDefaultLighting();
            }
            mesh.Draw();
        }
    }
    public BoundingSphere BoundingSphere
    {
        get
        {
            if (!boundingimplemented)
            {
                foreach (ModelMesh mesh in Model.Meshes)
                {
                    BoundingSphere transformed = mesh.BoundingSphere.Transform(
                    modeltransforms[mesh.ParentBone.Index]);
                    sphere = BoundingSphere.CreateMerged(sphere, transformed);
                }
                Matrix worldTransform = Matrix.CreateScale(Scale) * Matrix.CreateTranslation(Position);
                BoundingSphere transforme = sphere;
                transforme = transforme.Transform(worldTransform);
                return transforme;
            }
            else
            {
                Matrix worldTransform = Matrix.CreateScale(Scale) * Matrix.CreateTranslation(Position);
                BoundingSphere transformed = sphere;
                transformed = transformed.Transform(worldTransform);
                return transformed;
            }
        }
    }
}

```

Then I call the class from the Game1 class:

```
ImportModel ground = new ImportModel("ground", GraphicsDevice, Content, Vector3.Zero, Vector3.Zero, new Vector3(20f));

```

This is how the scene looks from top:

# Answer
You must set `effect.Texture` to a `Texture2D` object that contains your checkers texture and you have previously loaded with the `ContentManager`.
> 1 votes

---
Tags: xna, c#, 3d
---


title: Changing balls direction in Pong

text:
# Question
Title: Changing balls direction in Pong
I'm making a Pong game to get started with game-developement but I've run into a problem that i can't figure out.

When trying to change the balls direction it doesn't change. This is the relevant code:

```
function moveBall(){
    this.speed = 2.5;
    this.direction = 2;
    if(this.direction == 1){
        ball.X +=this.speed;
    }
    else if(this.direction == 2){
        ball.X -=this.speed;
    }
}

function collision(){
    if(ball.X == 500){
        moveBall.direction = 2;
    }
    if(ball.X == 300){
        moveBall.direction = 1;
    }
}

```

Why doesn't it work? I've tried many different ways, and none of them seem to work. The `moveBall.direction` changes though, since it alerts the new direction once it reaches the defined `ball.X` position.

If someone could help me I would deeply appreciate it. I've included a JSFiddle link.

http://jsfiddle.net/hustlerinc/y4wp3/

# Answer
**1)** I would remove your direction variable because it can be included as part of the speed variable: negative speed values move left and positive speed values move right. This allows you to remove the if statements in the `moveBall` function and reduce it to a line or two

**2)** `direction` (if you keep it) and `speed` should be set outside of the move function, this will fix your problem. Every time you go to move your ball, it's resetting the `speed` and the `direction` back to their original values.

**3)** Using `==` to compare the position against an exact point can be dangerous, it is better to always use `>=` or `<=` depending on the case. But I won't be too hard on you because I'm pretty sure that's just for testing.

I don't really want to give you the codez, even though I did fix it, because learning how to fix these things is all part of the learning process :)
> 4 votes

# Answer
A very simple way to handle this would be to omit the direction variable and just deal with xspeed and yspeed. This is how I handle reversing directions.

```
Ball = {
    pos: {x: 2, y: 2},
    size: {x: 8, y: 8},
    speed: {x: 2, y: 2},
    update: function() {
        if (this.pos.x < 0 || (this.pos.x + this.size.x) > canvas.width) this.speed.x *= -1;
        if (this.pos.y < 0 || (this.pos.y + this.size.y) > canvas.height) this.speed.y *= -1;
        this.pos.x += this.speed.x * deltaTime;
        this.pos.y += this.speed.y * deltaTime;
    }
}

```

If you require the direction variable, you can keep track of the previous x and y position and do a trace from that to the new position.

**Edit**: Keep in mind the code assumes the Ball is 8px by 8px and is drawn from top-left rather than the center. It would be easy to add an offset and have this handled for you.
> 2 votes

# Answer
why did you put `this.direction = 2;` in second line of `moveBall` function? just remove it!
> 1 votes

---
Tags: javascript
---


# Question
Title: Controlling a GameObject from another GameObject's script component
I'm creating a game where when starting the game, a Cube is duplicated `GridSize * GridSize` times when the game starts. Now, after the cubes are duplicated I want to attach a variable to them, say "Flag" which is a bool, from another script component (let's say I have a Prefab that generates the cloned cubes).

In short, I have something like this:

CreateTiles.cs : Attached to Prefab

```
void Start() {
    createMyTiles(); // a function that clones the tiles
    flagRandomTiles(); // a function that (what I'm trying to do) "Flags" 10 random cubes
}

```

CubeBehavior.cs : Attached to each Cube

```
public bool hasFlag;
// other stuff

```

Now, I want `flagRandomTiles()` to set a Cube's hasFlag property via code, assuming I have access to them via a `GameObject[]` array.

Here's what I've tried:

1. `Cubes[x].hasFlag = true;` \- No access.
2. Making a function such as `Cubes[x].setHasFlag(true)` \- still no access.
3. Initializing Cubes as a CubeBehavior object array, then doing the above - GameObjects can't be converted to CubeBehaviors - I get this error when I try to assign the Cubes into the array.

How do I do this?

# Answer
> 4 votes
It looks like Cube\[\] is an array of GameObjects? If so, you need to reference any attached behaviors by using

```
 CubeBehavior cubebehavior = Cube[i].GetComponent<CubeBehavior>();
 cubebehavior.hasFlag = [yourvalue];

```

The syntax above uses the generic signature for GetComponent(); If this syntax is difficult to understand, you can also use `GetComponent("T") as T` which does not return you a strongly typed component.

Please read the **docs** if you want to know additional info.

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


# Question
Title: What is the best way to display a cut scene?
How do we show cutscene in the game? Currently I am using images and animation upon them to show cutscenes or story. I heard from my friend that showing a video might be one of the option too.
Is it a good option or is there any other option except those two? I'd also like to know pros and cons of each option if you can provide.

# Answer
> 4 votes
It depends what kind of cutscene you want. Some games have a comic book style cutscene where images would be the best option. Unless you're trying to actually make a 30 fps video out of images. Then a video would be the way to go. A third option is to actually do it in game by using the character models and animating those. This gives a smooth transition (unless you want the cutscene to be higher quality). My bro said the advantage is that this is dynamic. For example if the player is holding something he will keep holding it. Unlike a video which doesn't change.

---
Tags: ios, marmalade, cutscene
---


title: Math major as a viable degree

text:
# Question
Title: Math major as a viable degree
While I realize there are many topics about CS vs software engineering vs game school programs, I haven't found anything relating to whether pure math degrees (with CS minor and electives) would also be a viable program. By this I mean: Would having a math major, CS minor put one at competitive disadvantage as compared to a pure CS program?

This relates specifically to game engine programming, more on the graphics side.

Background (for those who care): Currently a math major, CS minor at school and looking to land a career doing graphics engine programming. Admittedly, I love math and if at all possible would like to stay my current program as long as it doesn't put me at a competitive disadvantage trying to land a job post-graduation. That being said, I'm strong in the traditional C/C++ languages, strong concurrent programming skills, and currently produce self-made games for iOS. As an employer, how badly is the math major hurting me? Just want to get some advice from people already in the field!

# Answer
The thing with CS jobs. It doesn't really matter what your degree is in, you can still get a job, as long as you can show that you're able to code. I know plenty of very smart developers who don't have their degrees in computer science. That being said, there is still the "getting your foot in the door" part of the job, when people don't know what you can do yet, a degree is important there. **Your mathematics/CS combination seems ideal for graphics engines.** I don't think you'll have a problem getting people to take a look at your skills. Additionally, since you're strong in coding already and can show games you've produced, I think you've just sealed the deal for many employers.
> 3 votes

---
Tags: mathematics, graphics-programming, game-industry, hiring
---


# Question
Title: Implementing a FSM with ActionScript 2 without using classes?
I have seen several references of A.I. and FSM, but sadly I still can't understand the point of an FSM in AS2.0. Is it a must to create a class for each state?

I have a game-project which also it has an A.I., the A.I. has 3 states: *distanceCheck*, *ChaseTarget*, and *Hit the target*.

It's an FPS game and played via mouse.

I have created the A.I. successfully, but I want to convert it to FSM method...

My first state is `CheckDistanceState()` and in that function I look for the nearest target and trigger the function `ChaseState()`, there I insert the `Hit()` function to destroy the enemy,

The 3 functions that I created are being called in `AI_cursor.onEnterframe`.

Is there any chance to implement an FSM without the need to create a class? From what I've read before, you have to create a class. I prefer to write the code on frames in flash and I still don't understand how to have external classes.

# Answer
First of all: You don't need classes to implement a FSM. Sure, it's a nice and extendable design, but something like this works just as well (using a switch statement):

```
onUpdate(){
    switch(state){
        case STATE_1:
            do state 1 stuff
            if(conditionThatLeadsToState2){
                state = STATE_2;
            }
            break;
        case STATE_2:
            do state 2 stuff
            if(conditionThatLeadsToState3){
                state = STATE_3;
            }
            break;
        ... etc ...
    }
}

```

Using a `switch` statement works for very simple FSMs, but gets really cumbersome with more complex architectures. Since Functions are also objects in flash, you could have functions as states (instead of classes). Here's an example written in ActionScript 2:

```
var count = 0;

function state1(){
    count++;
    if(count == 10){
        state = state2;
    }
    trace("state 1, increasing: " + count);
}

function state2(){
    count--;
    if(count == 0){
        state = state1;
    }
    trace("state 2, decreasing: " + count);
}

var state = state1;

function onEnterFrame(){
    state();
}

```

As you can see, we're always executing `state` in the update (`onEnterFrame`) method. But we can dynamically change `state` during runtime. So in the `state1` function I'm assigning `state2` to `state`, when a certain condition is met. This pattern is pretty close to an implementation with classes and should be fairly flexible.

But if your implementation already works, why not keep it the way it is? I'm pretty sure you have already implemented your own FSM pattern and it seems to work.

Also using classes is really easy. Just write your class, save it to an `.as` file in the same folder as the FLA and then instantiate it with `myInstance = new MyClass();` in your code. A quick google-search turned up this tutorial.
> 3 votes

---
Tags: software-engineering, flash, ai, fsm
---


# Question
Title: Blender 2.6: Changing the Resolution (Rings/Segments) of a UVSphere's
I know that it's possible to change the resolution (I mean the rings and the segments) of a UVSphere by pressing `[F6]` and changing some arguments.

But what if I add a UVSphere to my canvas at first, then I do something else in the meantime and *not till then* I want to change the resultion of the UVSphere which I added *before*. Is that possible? Thanks.

# Answer
> 3 votes
The simplest thing would be to remove it and add a new UV sphere. Once the sphere has been placed, the options for changing it's attributes is gone. The only option I know of is to add a subdivide surface modifier to your sphere. That will subdivide all the quads, but it essentially only allows you to double your rings and segments, not increase them separately or by a factor less than 2. So to easily replace an existing UV sphere, you can do the following:

1. Select the UV sphere you want
2. Press Shift+S and select `Cursor to Selected`
3. Press X and confirm delete
4. Press Shift+A and select `Mesh->UVSphere`
5. Choose your arguments

---
Tags: 3d, blender
---


title: Translate along local axis

text:
# Question
Title: Translate along local axis
I have an object with a position matrix and a rotation matrix (derived from a quaternion, but I digress). I'm able to translate this object along world-relative vectors, but I'm trying to figure out how to translate it along local-relative vectors. So if the object is tilted 45 degrees around its Z-axis the vector (1, 0, 0) would make it move to the upper right.

For world-space translations I simply turn the movement vector into a matrix and multiply it by the position matrix: `position_mat = translation_mat * position_mat`. For local-space translations I'd think I'd have to use the rotation matrix into that formula, but I see the object spin around instead when I apply a translation over time no matter where I multiply the rotation matrix.

# Answer
Just take the desired movement vector, multiply it by the object's rotation matrix, then use the result as before, i.e. convert it to a translation matrix and multiply it into the `position_mat`.
> 4 votes

---
Tags: 3d, matrix, transformation
---


# Question
Title: C++ and SDL Trouble Creating a STL Vector of a Game Object
I am trying to create a Space Invaders clone using C++ and SDL. The problem I am having is in trying to create Waves of Enemies. I am trying to model this by making my Waves a vector of 8 Enemy objects.

My Enemy constructor takes two arguments, an x and y offset. My Wave constructor also takes two arguments, an x and y offset. What I am trying to do is have my Wave constructor initialize a vector of Enemies, and have each enemy given a different x offset so that they are spaced out appropriately.

```
Enemy::Enemy(int x, int y)
{
    box.x = x;
    box.y = y;
    box.w = ENEMY_WIDTH;
    box.h = ENEMY_HEIGHT;

    xVel = ENEMY_WIDTH / 2;
}

Wave::Wave(int x, int y)
{
    box.x = x;
    box.y = y;
    box.w = WAVE_WIDTH;
    box.y = WAVE_HEIGHT;

    xVel = (-1)*ENEMY_WIDTH;
    yVel = 0;

    std::vector<Enemy> enemyWave;
    for (int i = 0; i < enemyWave.size(); i++)
    {
        Enemy temp(box.x + ((ENEMY_WIDTH + 16) * i), box.y);
        enemyWave.push_back(temp);
    }
}

```

I guess what I am asking is if there is a cleaner, more elegant way to do this sort of initialization with vectors, or if this is right at all. Any help is greatly appreciated.

# Answer
There are a couple of problems here.

Firstly, enemyWave is a local variable and gets destroyed at the end of the constructor when it goes out of scope, which makes it useless as a long term data structure.

Secondly, everything you store in a vector needs to follow the rule of three. It's not clear if your Enemy classes do.

Apart from that, this is pretty much how you initialise a vector, an element at a time.
> 1 votes

---
Tags: c++, vector, sdl
---


title: A* Start path finding in HTML5 Canvas

text:
# Question
Title: A* Start path finding in HTML5 Canvas
I'm trying implement A\* Start path finding in my games(which are written with JavaScript, HTML5 Canvas). Library for A\* Start found this - http://46dogs.blogspot.com/2009/10/star-pathroute-finding-javascript-code.html and now I'm using this library for path finding. And with this library, I'm trying write a simple test, but stuck with one problem. I'm now done when in HTML5 canvas screen click with mouse show path until my mouse.x and mouse.y. Here is a screenshot:

(Pink square: Player, Orange squares: path until my mouse.x/mouse.y)

Code how I'm drawing the orange squares until my mouse.x/mouse.y is: http://pastebin.com/bfq74ybc (Sorry I do not understand how upload code in my post)

My problem is I do not understand how to move my player until path goal. I've tried: 'http://pastebin.com/nVW3mhUM

But with this code my player is not beung drawn.(When I run the code, player.x and player.y are equals to 0 and when I click with the mouse I get the path player blink and disappear)

Maybe anyone know how to solve this problem?

And I'm very very very sorry for my bad English language. :)

# Answer
I can see two problems with your code:

```
for(var i = 0; i < path.length; i++) {
    player.x += path[i].x;
    player.y += path[i].y;
}

```

you're using `+=`, which means you're adding to the current position, if the player is at `0,0` (and let's say the path is `{(1,1),(1,2),(2,3)}`), the player position will be `(1,1),(2,3),(4,6)` , which is probably not what you want (and probably why it's disappearing.) You should use `player.x = path[i].x;`.

Second, a `for` loop is executed entirely in one tick, so before showing on the screen or allowing for more player input, your square will already be at its final position. Since you're using javascript I assume you have a setInterval/setTimeout/requestAnimationFrame, inside of whatever code you have you should do something like this:

```
var currentFrame = 0;
var lastFrame = 0;
var i = 0;
setInterval(function(){
    currentFrame++;
    if(currentFrame-lastFrame >= 10){
        lastFrame = currentFrame;
        player.x = path[i].x; player.y = path[i].y;
        i++
        if(i > path.lenght) i = 0;
    }
},33);

```

this is not simply copy and paste tho, so if you want a more suited answer, post more of your code.
> 2 votes

---
Tags: javascript, html5, path-finding
---