title: What calls trigger a new batch?

text:
# Question
Title: What calls trigger a new batch?
I am finding my project is starting to show performance degradation and I need to optimize it. The answer to my previous question and this presentation from NVidia have helped greatly in understanding the performance characteristics of code using the GPU but there are a couple of things that aren't clear that I need to know to optimize my drawing.

Specifically, what calls make the distinction between batches.

I know that any state changes cause a new batch, so that includes:

* Render State Changes
* Buffer Changes
* Shader Changes
* Render Target Changes

Correct? **What else counts as a 'state change'**?

**Does each Draw**Primitive() call constitute a new batch?\** Even if I were to issue the same call twice, with no state changes, or call it once on on part of the buffer, then again on another?

**If I were to update a buffer, but not change the bindings, would that be a new batch?**

That presentation and a DX9 page suggest using all of the texture slots available, which **I take to mean loading multiple objects in 'parallel' by mapping their buffers/shaders/textures to slots 1-16. But I am not sure how this works - surely to do this you would need to change the buffer binding and that would count as a state change?** (or is it a case of you do but it saves 16 calls so its OK?)

# Answer
> 1 votes
You can say that any change to a data that will be processed by a subsequent call to Draw\**Primitive() will trigger a state change.

If you call a Draw two times without changing anything, it's likely that your second call won't any anything from the first (well, except if you're drawing with alpha).

Change a constant buffer will trigger a new batch for sure.

With DX9 (and all 3D API in general) the state change that costs the most is the Texture slots one, by using all the 16 slots available you intent to minimize the texture switches. A good thing to do is (when possible) rendering the primitives using the same textures in consecutive calls.

It's not easy to figure things out in DX9 the API design doesn't help much to understand how to do things efficiently. DX10/11 APIs are really an improvement in this matter as everything is regrouped/organized into blocks where the creation and applying steps are clearly differentiated.

GPU optimization all in all is about:

1. Reducing the number of call/changes you make.
2. Make sure you disrupt the rendering flow as less as possible (and any change to a buffer that will be immediately used is a notable disruption).

Bonus answer: if you want to do Object Picking, with not going with a CPU based ray-tri intersection routine? It's pretty fast if you early reject objects with a first ray-bounding box intersection.

# Answer
> 4 votes
Back to back draw calls are extremely efficient. It should perform nearly identically to 'hardware instancing' features available in the APIs, aside from the added overhead of calling the API repeatedly. This is how we render relevant on-screen terrain fragments as well as all the random weapons in Borderlands.

You can usually consider updating resources (texture,constants,vertex,index) a separate issue to changing state. These involve additional penalties (lock stalls especially in SLI setups) depending on the driver. A lot of these are hidden by well written drivers by internally managing their own staging resources that get DMA'd asyncronously and freed behind the scenes.

Changing which resource objects (including rendertargets) the GPU is using is relatively cheap. The cost is primarily in the fact the GPU caches have to be cleared when they are changed, but it is normally negligable. The major state blocks (depth/stencil, blend/colorwritemask, rasterizer/scissor) historically are a bit trickier since a good number of those states depend heavily on other states, and is one of many reasons why older APIs like D3D9 are lazy about doing state work until draw calls occur. For example you might have the depth test set to less-equal but no depth buffer bound, but the driver has to turn it off when this happens.

If you are working with an older api like D3D9 one of the biggest free boosts you can get is to batch up all the shader constants into a giant struct and only upload the relevant dirty region before you call draw, as calling into the SetVertexShaderConstantF over and over is pretty expensive.

---
Tags: performance, optimization, sharpdx
---


title: Alpha blending without depth writing

text:
# Question
Title: Alpha blending without depth writing
A recurring problem I get is this one: given two different billboard sets with alpha textures intended to create particle special effects (such as point lights and smoke puffs), rendering them correctly is tedious.

The issue arising in this scenario is that there's no way to use depth writing and make certain billboards obey depth information as they appear in front of others that are clearly closer to the camera. I've described the problem on the Ogre forums several times without any suggestions being given (since the application I'm writing uses their engine).

What could be done then? sort all individual billboards from different billboard sets to avoid writing the depth and still have nice alpha blended results? If yes, please do point out some resources to start with in the frames of the aforementioned Ogre engine. Any other suggestions are welcome!

# Answer
Let me give you the bad news straight away: there is no fix for this, not in Ogre, not in any engine.

This website explains the problem nicely.

However, a solution in your case could be to first render all your opaque objects, turn off depth writing, render the particles and turn depth writing back on. This will allow for transparent particles to blend with the background, but unfortunately they cannot blend with each other, unless you render each particle individually.
> 4 votes

# Answer
It can't be done with Ogre. From Sinbad himself, on this thread:

> It's basically impossible to sort between particle systems efficiently. The reason is that to sort arbitrarily would require every particle to be rendered independently, which would totally kill performance.
>
> You need to use workarounds like using 'hard' alpha and leaving depth-writing on if you want perfect sorting.
>
> If you have a case where one type of particle system should always be on top of another, you can separate them using render queues. But you can't interleave systems.
> 2 votes

# Answer
I think everyone already covered most of the major answers but it is worth noting that if all of your effects are additive then order dependency is no longer a problem.

As soon as you introduce an alpha-blend (or even adding fog to the particles) then it becomes a big unsolvable mess.
> 0 votes

---
Tags: ogre, transparency, mogre
---


title: Defining the track in a 2D racing game

text:
# Question
Title: Defining the track in a 2D racing game
I am designing a top-down racing game using canvas (html5) which takes a lot of inspiration from Micro Machines. In MM, cars can move off the track, but they are reset/destroyed if they go too far.

My maths knowledge isn't great, so I'm finding it hard to separate 3D/complex concepts from those which are directly relevant to my situation. For example, I have seen "splines" mentioned, is this something I should read up on or is that overkill for a 2D game?

Could I use a single path which defines the centre of the track and check a car's distance from this line? A second path might be required as a "racing line" for AI.

Any advice on methods/techniques/terms to read up on would be greatly appreciated.

# Answer
It really depends on what you want your game to "feel" like. You could go with the Micro Machines method of using a tilemap to generate the track.

However, if I were you I'd go with the "cool" solution: a spline.

First, you should realize that a spline is nothing but a set of points. It has a beginning and an end. A straight line is a form of spline. However, when you have more than 2 points, you can do interesting things, including using intermittent points to deform the line.

http://en.wikipedia.org/wiki/B\_spline

I wouldn't bother looking at the Wikipedia explanation (it's filled with dragons and maths), but this image explains it rather well:

Here you have a set of points in a graph and you use a spline function to smooth out the transition between bars. Depending on the function, you will get a different spline.

So, for your game:

* Make a tileset with different types of corners (90 degrees, 45 degrees, etc.)
* Generate a set of points, where one point starts where a car enters a piece of track and another point where a car exits a piece of track. For example, if your track consists of four 90 degree corners and 18 straight bits, you will have a set of (4 * 2) + (18 * 2) = 44 points.
* With some tweaking, fit a spline through the points to match the underlying road.

Now you have a (hopefully) automatically generated line in the center of the road. You can then use the distance to this line as a way to determine how far along a car is in the race and if it doesn't run off the track.

However, that math depends on heavily on your implementation.
> 5 votes

# Answer
Although Bezier curves are the usual thing people go for, I'd recommend considering circular arcs (and maybe elliptical arcs) unless you really need Bezier curves or splines:

1. It's nice to be able to evenly space things along the curve. For example you might want to draw lane markers or you might want to calculate a path in curve coordinates. *A straightforward use of Bezier curves (and splines) leads to an uneven spacing*, whereas circular arcs work nicely here. You can generate evenly spaced angles and get back evenly spaced points on the curve. With Bezier curves you end up doing extra work to get approximately even spacing.
2. It's nice to be able to generate “offset curves”. These are the curves that match the original, but are at some offset from it. For example, given the center of the road, the edges of the road are offset from it. The lane markers are also an offset from the center. *Offset curves from a Bezier curve are not themselves Bezier curves.* With circular arcs it's very easy to calculate another arc. With Bezier curves you end up doing extra work to get approximate offset curves. With circular arcs it's very easy to calculate distance from the player to the arc (it's just distance to center minus the arc radius, with a range check for angles). With Bezier curves distances are a little bit more work to calculate.

Circular arcs are simpler to work with. However, they may not be able to represent all the shapes you want. (On the other hand, splines can't represent all shapes either.) Bezier curves are the next step; Bezier splines or B-splines are even more flexible. Use the simplest thing that works for your game.
> 3 votes

# Answer
I'd go for a much more simple approach:

Predefine the tracks in some editing tools of your choice; export them using a graphics program, defining colours for different areas of the track.

Using a bitmap (not necessarily the same resolution as your actual display; it can be lower) colour pixels for different effects e.g.:

* black = on the track, maximum grip
* grey = off the track less grip
* green = on the grass, even less grip
* white = "out of bounds" - player's car position is reset to last "on track" position.

Then your game can just read the pixels from an offscreen canvas based on the location of the player.

There is no need to do any fancy maths, unless you want to. And you can do all of the "fancy maths" ahead-of time, i.e. not build it into the game.

NB: you should NOT render this bitmap (except maybe in debug mode), it's for internal use only.
> 2 votes

# Answer
If you're using a tileset, you can use the tile IDs to determine what terrain the car is on, and go from there. If you're not, you can do essentially what MarkR suggested to accomplish the same thing (Some basic skills with GIMP or Photoshop can pixelate and even boil down colors for you so it'd be pretty straightforward)

The problem with this method is that tight corners, hairpins, overpasses, etc might not work as expected. It's been a long time since I played Micro Machines, but as I recall you were prevented from taking major shortcuts even if you never went fully off the track. You couldn't just drive off an overpass onto the track below to skip half the track. One possible solution to this is to add essentially "checkpoints" along the track, that are invisible to the player. There could be 50 or even 500 of them on a single course. The player has to get within X distance (which could be pretty far away, essentially your *reset car to track* distance) to "activate" the checkpoint, and if they activate checkpoint 32 without activating checkpoint 29~31 first, **boom**.

The mini-checkpoints is a somewhat complex solution, but it gives you a lot of flexibility elsewhere in your game. Now you can more easily track distance to the finish line, use them for your AI logic, use them as the reset points when the car gets blown up, etc. (Actually I think the reset is especially valuable since you can just back them up 5 or 10 checkpoints as a simple way of penalizing them, and there's no nasty track calculations to do)

Edit: To that end, might make sense to have the checkpoints be vectors, so you can point the cars in the right direction, and detect "wrong way" before a bunch of checkpoints are crossed in reverse.
> 2 votes

---
Tags: html5, html-canvas, racing
---


title: XNA 4 game for both profiles

text:
# Question
Title: XNA 4 game for both profiles
I am writing game in XNA 4 and this version have two profiles hi-def and reach. My problem is that I need to have my game code for each of these profiles and is very uncomfortable to have two projects and do all changes in both of them. My idea was to use preprocessor directive (i am not sure about name of this, http://msdn.microsoft.com/en-us/library/ed8yd1ha%28v=vs.71%29.aspx) and use IF statement at places with problems with profile. There is only problem that program needs to be compiled two times (for each profile) and manually changed directive and project settings to another profile. And my questions are: Is that good way? Is there better and cleaner way how to do this?

# Answer
I got this working, but you need to use some MSBuild magic to do it. **I strongly recommend you backup your project, as you might easily break something if you do this wrong.**

First things first, you need to open up the configuration manager(`ALT + B + O`).

Then you need to create four build configurations for your game project. I chose to name mine `DebugReach`, `ReleaseReach`, `DebugHiDef` and `ReleaseHiDef`.

After doing this, you save your project, right-click the project in the solution explorer and then hit `Unload Project`. Now, you right-click the project again, and hit `Edit <projectname>.csproj`. This is the raw MSBuild configuration of your project.

In the first `PropertyGroup` node, you need to find the child node `XnaProfile` ann then delete the line. Next you need to find the `PropertyGroup` nodes that look like this:

* `<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'DebugReach|x86' ">`
* `<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'ReleaseReach|x86' ">`
* `<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'DebugHiDef|x86'">`
* `<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'ReleaseHiDef|x86'">`

Into `DebugReach` and `ReleaseReach` you add the following node:

* `<XnaProfile>Reach</XnaProfile>`

Into `DebugHiDef` and `ReleaseHiDef` you add the following node:

* `<XnaProfile>HiDef</XnaProfile>`

After that, you save the file, close it, then right-click the project and click reload. Now depending on the build configuration you use, you'll either use Debug or HiDef. **Please note that opening up** `Properties` **does not reflect the difference, but you can test it when you build.**
> 5 votes

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


# Question
Title: Disposing of ContentManager increases memory usage
I'm trying to wrap my head around how memory management works in XNA 4.0 I've created a screen management test and when I close a screen, the ContentManager created by that screen is unloaded. I have used ANTS Memory Manager to look at how the memory usage is altered when I do this, and it gives me some results which makes me scratch my head.

The game starts with loading two textures (435kB and 48,3kB) which puts the usage at about 61MB. Then, when I delete the screen and runs Unload on the ContentManager, the memory usage drops to 56,5MB but instantly after goes up to 64,8MB.

Am I doing something wrong or is this usual for XNA games? Do I have to dispose of everything the ContentManager loads seperatly or do I need to do something more to the ContentManager?

Thanks in advance!

# Answer
I suppose it all depends on what actually happens after screen deletion. In general all (at least standard) resources loaded by `Load<T>` method of `ContentManager` are automatically disposed, so you need to dispose additionally only any other resources.

P.S. Even simple CLR Profiler allows you to see what objects actually allocated in memory, that's what profilers are for! Why not to see it yourself?
> 0 votes

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


title: Continuous Movement of gun bullet

text:
# Question
Title: Continuous Movement of gun bullet
I was using box2d for the movement of the body. When I apply gravity (0,0) the bullet continuously move but when I change gravity to the earth the behavior was changed. I also try to apply continuous force to the bullet body but the behavior was not so good. So please provide any suggestion to continuously move bullet body in earth gravity.

```
currentVelocity = bulletBody.getLinearVelocity();
if (currentVelocity.len() < speed|| currentVelocity.len() > speed + 0.25f) {
    velocityChange = Math.abs(speed - currentVelocity.len());
    currentVelocity.set(currentVelocity.x* velocityChange, currentVelocity.y*velocityChange);
    bulletBody.applyLinearImpulse(currentVelocity,bulletBody.getWorldCenter());
}

```

I apply above code for the continuous velocity of the body. And also I did not able to find any setGravityScale method in the library.

# Answer
> 0 votes
Update your andengine library for the gravity of the body.By implementing body.setGravityScale(0) method in the library the body does not feel any gravity from the physics world.

# Answer
> 0 votes
Bullets are subject to gravity as well, they just usually move so fast that it doesn't matter. Are you trying to make something like a rocket that moves quite slowly but steadily across the screen?

You could go around the problem by continuously applying force equal and opposite to the gravity.

---
Tags: box2d, andengine
---


# Question
Title: Where can I find free or buy "next-gen" 3D Assets?
Usually I buy 3D Assets from sites like turbosquid.com or similar.

My problem is that I have lately implemented glow, normal maps, specular (and specular power) maps and reflection maps and I can't find any models that use those techniques.

So where can I find / buy "next gen" assets (at least models/items with a normal map)?

I have checked for similar posts but those I found are about either free only or 2D or 'ordinary' 3D so I hope this is not a duplicate.

# Answer
It seems there are very few normalmaps out there (I still haven't found any, not more than the occasional brick map anyway) so the solution seems to be that you need to do them yourself.
> 0 votes

# Answer
You didn't really get astounding quality with Crazy Bump...hmm. don't know what exactly you are looking for.

okey, here is another solution. Its called Insane Bump. Its functionality is similar to Crazy Bump. Try it out.

There is an interesting comparison between this two bumpies.

Oh did I mention. Its Free!
> 4 votes

# Answer
Have you tried CrazyBump? It generates normal/displacement/occlusion/specular maps from a single diffuse texture, with astounding quality.
> 2 votes

# Answer
http://cgtextures.com/ has a good deal of free textures, and some of them come with normal/spec maps (not that many, though).
> 1 votes

---
Tags: 3d-meshes, normal-mapping
---


title: Frame independent acceleration

text:
# Question
Title: Frame independent acceleration
To make my game fps independent I move entities with

```
pos += speed * time

```

where time is the delta time since last frame.

That works perfectly well with speed but how do you do that with acceleration?

# Answer
You'll likely be using constant acceleration. So no need to worry! The derivative of constant acceleration with respect to time is 0. That means it doesn't change with respect to time, so it doesn't matter what your frame rate is. If you were using variable acceleration you'd set up your equation like:

```
acc += jerk * time //only needed if your acceleration isn't constant
speed += acc * time //calculates the current velocity given the acceleration
pos += speed * time //calculates the position given the current velocity

```

The jerk is the rate of change in your acceleration.

You may want to check out the equations of motion.

**EDIT**

Since your math is coming back to you, you may remember that using the Euler form above is fairly inaccurate. So you may remember this little integration with respect to time process from physics:

1. a = a
2. v = at + v0
3. s = .5at^2 + v0\*t + s0

Where: a=acceleration, v=velocity, v0=initial velocity, s=position, s0=initial position, t=time

If you derive your position using that equation instead, you'll get far more accurate results.
> 9 votes

---
Tags: movement, frame-rate
---


# Question
Title: Can't remove JPanel from JFrame while adding new class into it
Basically, I have my Frame class, which instantiates all the properties for the JFrame, and draws a JLabel with an image (my title screen). Then I made a separate JPanel with a start button on it, and made a mouse listener that will allow me to remove these objects while adding in a new Board() class (Which paints the main game).

\*Note: The JLabel is SEPARATE from the JPanel, but it still gets moved to the side by it.

Problem: Whenever I click the button though, it only shows a little square of what I presume is my board class trying to run. Code below for the Frame Class:

```
package OurPackage;
//Made By A.K. 5/24/12
//Contains Frame.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.*;
import javax.swing.plaf.basic.BasicOptionPaneUI.ButtonActionListener;

public class Frame implements MouseListener
{
    public static boolean StartGame = false;
    ImageIcon img = new       ImageIcon(getClass().getResource("/Images/ActionJackTitle.png"));
    ImageIcon StartImg = new ImageIcon(getClass().getResource("/Images/JackStart.png"));
    public Image Title;
    JLabel TitleL = new JLabel(img);
    public JPanel panel = new JPanel();
    JButton StartB = new JButton(StartImg);
    JFrame frm = new JFrame("Action-Packed Jack");

    public Frame()
    {
        TitleL.setPreferredSize(new Dimension(1200, 420));
        frm.add(TitleL);

        frm.setLayout(new GridBagLayout());
        frm.add(panel);

        panel.setSize(new Dimension(220, 45));
        panel.setLayout(new GridBagLayout ());

        panel.add(StartB);
        StartB.addMouseListener(this);
        StartB.setPreferredSize(new Dimension(220, 45));

        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frm.setSize(1200, 420);
        frm.setVisible(true);
        frm.setResizable(false);
        frm.setLocationRelativeTo(null);
    }

    public static void main(String[] args)
    {
        new Frame();
    }

    public void mouseClicked(MouseEvent e)
    {
            StartB.setContentAreaFilled(false);
            panel.remove(StartB);
            frm.remove(panel);
            frm.remove(TitleL);
            //frm.setLayout(null);
            frm.add(new Board()); //Add Game "Tiles" Or Content. x = 1200
            frm.validate();
            System.out.println("Hit!");
    }

    @Override
    public void mouseEntered(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseExited(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mousePressed(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseReleased(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

}

```

EDIT: I also created a new Board Object(?) in my Frame class. Will I be able to resize it and such?

# Answer
First of all, ALL component manipulations should run in the Event Dispatch Thread (EDT) or else it WILL cause you trouble. In your case:

```
public static void main(String[] args)
{
    SwingUtilities.invokeLater(new Runnable()
    {
       public void run()
       {
          new Frame();
       }
    });
}

```

As for your problem, i guess it is a layout issue. I suggest you read these tutorials.

\< personal-opinion \> I made a reasonable amount of swing apps, and from my experience, the only layout managers worth using are GridLayout and BorderLayout. \< /personal-opinion \>
> 0 votes

---
Tags: java, graphics, rendering, gui
---


# Question
Title: This code is of chess game. What is represented by 'DISTANCE' in code?
```
package chess;

public class Evaluate {
public static final int PIECE_KING = 0;
public static final int PIECE_QUEEN = 1;
public static final int PIECE_ROOK = 2;
public static final int PIECE_BISHOP = 3;
public static final int PIECE_KNIGHT = 4;
public static final int PIECE_PAWN = 5;
public static final int FULL_BIT_RANK = 4080;
public static final int LAZY_MARGIN = 100;
public static final int ISOLATED_PENALTY = 10;
public static final int DOUBLE_PENALTY = 4;
public static final int[] PIECE_VALUE = { 0, 9, 5, 3, 3, 1 };

  public static final int[] PASS_PAWN = { 0, 35, 30, 20, 10, 5 };

  public static final byte[] DISTANCE = {
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 6, 7,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 6, 5, 6, 7,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 6, 5, 4, 5, 6, 7,
    0, 0, 0, 0, 0, 0, 0, 0, 7, 6, 5, 4, 3, 4, 5, 6, 7,
    0, 0, 0, 0, 0, 0, 7, 6, 5, 4, 3, 2, 3, 4, 5, 6, 7,
    0, 0, 0, 0, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7,
    0, 0, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7,
    0, 0, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7,
    0, 0, 0, 0, 7, 6, 5, 4, 3, 2, 3, 4, 5, 6, 7,
    0, 0, 0, 0, 0, 0, 7, 6, 5, 4, 3, 4, 5, 6, 7,
    0, 0, 0, 0, 0, 0, 0, 0, 7, 6, 5, 4, 5, 6, 7,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 6, 5, 6, 7,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 6, 7,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7 };

```

# Answer
> 3 votes
I'm guessing it is the Manhattan distance to the center in a program that uses an 0x88 board representation (that's why it's 16x16).

---
Tags: chess
---


# Question
Title: Where to start creating a 2d rain simulation with OpenGL ES 1.1?
I'm using opengl 1.1 and i'm creating a 2d side scrolling game.How can i render a 2d rain simulation?What is logic for that?

# Answer
> 3 votes
Assuming that you're using OpenGL ES because you're on a mobile platform, I'd say that any rendering technique you use should avoid trying to use alpha, for performance reasons. On a system where fill-rate isn't the limiting factor, you can get some lovely looking effects by using alpha planes and animating textures. With that in mind, you're best off making long, thin opaque raindrop polygons (either lines or elongated droplets). You can probably make them alpha if you want, as they'll only be a couple of pixels wide and so won't cost that much fill-rate. But you're going to need a fair amount of them.

The best performance would be to simply have one drop poly and just render it multiple times, but that might look a bit weird. You'd probably get better results having a few droplet polys of differing lengths.

So each droplet is a vertical streak placed somewhere in your scene, and you want to animate it downwards at a relatively constant velocity (maybe \< 20% variation in speeds between droplets), starting from offscreen at the top (so you don't see it pop into existence), and moving along its long axis downwards until it hits something at the bottom (the floor, an object bounding box, etc.). Doesn't have to be straight down, you can angle the rain as well to simulate wind.

I'm also going to assume that although you say '2D side scroller', what you actually mean is some sort of faux-3D effect (think Streetfighter or Double Dragon), as I don't think I've ever seen a 'pure' 2D side scroller. That means you've got some sense of perspective on your scene: even though you can't move in 3D, the scene you draw has some sense of back and front, with the player somewhere in the middle.

With that in mind, you probably already have 'layers' in your rendering (first you draw a backdrop (far away), then you draw things which are nearer but still 'behind' the player, then you draw the player, then you draw things which are in front of the player. Each of those layers will have some notional Z distance, but more importantly, they will each have a distance up the screen where the floor is (sort of a perspective effect). So items in the front-most layer have a floor at the very bottom of the screen, but the layer containing the player has a floor some distance up from the bottom of the screen.

So every so many frames, a new rain droplet will be spawned into a layer, at a random horizontal position, and the droplets should be randomly distributed between the layers. You track the droplet by where its lower edge is, and when it hits the floor, you want to start clipping the lower edge of the droplet (so the top of the droplet continues to move downwards, and the drop itself gets shorter and shorter until it disappears). Once the droplet is completely gone (the top edge has also hit the floor), you remove the droplet from the simulation.

You don't really need a full fledged physics engine for this, because the raindrops probably don't conform to natural physics anyway (they just spawn, move in one direction, then die once they hit something). Detecting when they hit something should be straightforward if you are following normal conventions of making a 2D side scroller.

---
Tags: opengl-es
---


# Question
Title: Finding inspiration / help for making up (weapon) names
I'm really bad with words, especially with English words. Currently I'm struggling to make a good weapon names for my game, it needs to display the weapon functionality (weak/strong/fast/ballistic etc) correctly as well. For example the best weapon in a (futuristic) game cannot be called just with the name "Laser", it's just too boring, right?

Are there any tools, websites or anything that helps me finding good names for weapons? (or anything else similar).

I was thinking to use scientific names, but noticed that they are really hard to write, and they get very long, and I also lack information about science, I only know I could use the atomic sub-particles names in the weapons for example.

How do I get started with becoming good with making up names? (this could apply in generally to any naming problems).

# Answer
Hire a writer.

There really is no way around this. You need creative names for stuff? You need a creative person who can name stuff for you. You can try to learn how to be a writer yourself, but if you aren't clever with words then you won't be clever at naming things.

But in a general direction, remember: If you want to make an apple pie, first you must create the universe. For the names of things to feel right, they need to fit with the rest of your game. They need to be part of a cohesive world. The fastest way to make your game generic is to assume the world is our own world. Do some world building. Design how the universe your game takes place in works. This is easier than thinking up names in a vacuum.

Once you know that your game takes place in Sanctuary, a world torn apart by the endless battle of Godly Angels and horrific Demons, you can start to get a feel for what your weapons should be. If your world is "generic scifi #35406" your weapons will be generic "Laser Gun." That's just how it's gonna be.

This is why freelance writers exist.
> 11 votes

# Answer
Most tools are simply designed to combine existing words. Like this one:

http://www.wordlab.com/gen/acme-namemaker.php

That sort of thing may be helpful. But as someone who comes from a theater/playwriting background, there's a real art to coming up with a good name. A good character name includes some onomatopoeia, where the name sounds like the item or its effect. A lazer gun probably has a 'z' sound or something similar. A slimy bad guy's name often has 's' noises in them, something that just makes them sound.... icky. Think of the stereotypical hero with a name like Dash Headstrong... that's a pretty blatant example, but it's the idea I'm trying to get across.

I know that may not be much help. Professional playwrights and writers and even designers often spend months on final decisions like this.

Another possible option may be to look at a Wiki for the game Sid Meier's Alpha Centauri. It's the spiritual successor to Civ 2 and has seven distinct races that all have distinct sounds to their weaponry and culture. Maybe that would give you some inspiration?

Good luck!
> 4 votes

# Answer
This isn't much different than the generation of any other content. It takes creativity. If English isn't your first language make up names in your native language and translate them or get someone to translate them. You can create lists and combine them to form new names. For example:

```
Fantastic    Pew Pew      Hand Gun
Scary Good   GigaLaser    Rifle
Weak         Boom Maker   Chest Cannon
Average

```

Pick one from each column to make a new gun name and type. This can make your job easier, but you would also have to ensure that it's a logical name that's produced. Additionally, it's really only the center column that is special, the other columns are just modifiers. But it does give the perception of a larger pool of names.
> 1 votes

# Answer
There's lot of good general advice in this thread, but in specific advice, for some solid base material in helping name weapons in a futuristic game, you can do a lot worse than to go buy a copy of *GURPS Ultra-Tech* and read it cover to cover.

Because it's intended as a genre sourcebook, much of what it contains is workups of well-established science fiction tropes that you need not concern yourself overmuch with stealing, as opposed to concepts specific to the GURPS system or any particular setting. (An exception would be "electrolasers", which are a very-particular-to-GURPS way to avoid saying "phaser".)
> 1 votes

# Answer
For some game with fixed equipment, we used wikipedia to find good names: choose a category of animals or plants and select the good latin names you see. Like for big armors I think we used the elephant family (Proboscidea) and started browsing from there. We also used a lot of different mythologies for weapons and equipments.
> 0 votes

---
Tags: content-generation
---


# Question
Title: Arbitrary projection matrix from 6 arbitrary frustum planes
A projection matrix represent a tranformation from the camera view space to the rendering system clip space. In other words, it defines the transormation between a 6-sided frustum to the clip cube.

The glOrtho and glFrustum use only 6 parameter to define such a projection, but impose several constraints on the frustum that will get projected to the clip cube: the near and far planes are parallel, the left and right planes intersect on a vertical line, and the top and bottom planes intersect on a horizontal lines, both lines being parallel to the near and far planes.

I'd like to lift these restrictions. So, from the definition of the 6 frustum side planes (in whatever representation you see fit), how can I compute a general projection matrix?

# Answer
> 0 votes
I'm going to go ahead and be the one to say that it's not possible to condense arbitrary contortions of space into a standard projection matrix which, by its nature, works with regular sides without being able to rotate them. Using your shadow map example, there's a reason the Digital/VFX industry hasn't done this already =)

You need a deeper set of equations than what a 4x4 matrix can represent. I'd suggest looking at implementing either a deformation matrix on top of the base projection frustum or a cage mesh deform.

deformation is complex

Blender visualization of a caged mesh deform

# Answer
> 1 votes
What you are asking is possible, but perhaps not in the way you had hoped (at least, to the best of my knowledge). Here is the problem, and a potential solution:

First of all, you cannot define six arbitrary planes with a single projection matrix, because the matrix really has nothing to do with planes. The matrix simply moves a given point around based on some matrix multiplication -- it transforms it, rotates it, and performs a perspective projection on it (expanding or shrinking its distance from the focal point). Thus, a projection matrix behaves in a more or less "symmetrical" manner - it is only capable of defining rectangular prisms, where one face of that prism is (potentially) larger than the other, along the axis of projection (not sure what you would call that shape?).

Now, here is what you could perhaps do to achieve what you want to do:

Rather than focusing on the 6 planes, focus on the eight corners of the view frustum. Give each corner its own projection matrix. Then, in the vertex shader, compute the new point eight times, one for each matrix. Then do several linear interpolations. Lets say the corners are set up like this:

```
Front:
A B
C D

Back:
E F
G H

```

Based on the x position of the point (scaled from 0 to 1), do a linear interpolation between A and B, then C and D, then E and F, then G and H. (Lets represent this with a "." character. You will now have this:

A.B C.D E.F G.H

Now take the y value (0 to 1) and do the following linear interpolation:

```
(A.B).(C.D)
(E.F).(G.H)

```

And last but not least:

```
((A.B).(C.D)).((E.F).(G.H)).

```

This will give you one final point. The interesting thing about this is that you could do some really crazy transformations, stuff that should not be physically possible. If you tied in some animation you could create really interesting effects, even though this is not the purpose of what you want this for.

# Answer
> 0 votes
This is more of a series of suggestions than an answer, but:

To my knowledge a 4x4 matrix is capable of representing this type of transformation, but the math escapes me.

Some things to consider

Even if that's not right I hope it leads you in the right direction!

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


title: Delaying a Foreach loop half a second

text:
# Question
Title: Delaying a Foreach loop half a second
I have created a game that has a ghost that mimics the movement of the player after 10 seconds. The movements are stored in a list and i use a `foreach` loop to go through the commands. The ghost mimics the movements but it does the movements way too fast, in split second from spawn time it catches up to my current movement. How do i slow down the foreach so that it only does a command every half a second? I don't know how else to do it. Please help

this is what i tried : The foreach runs inside the update method

```
DateTime dt = DateTime.Now;

        foreach ( string commandDirection in ghostMovements )
        {
            int mapX = ( int )( ghostPostition.X / scalingFactor );
            int mapY = ( int )( ghostPostition.Y / scalingFactor );

            // If the dt is the same as current time
            if ( dt == DateTime.Now )
            {
                if ( commandDirection == "left" )
                {
                    switch ( ghostDirection )
                    {
                        case ghostFacingUp:
                            angle = 1.6f;
                            ghostDirection = ghostFacingRight;
                            Program.form.direction = "";
                            dt.AddMilliseconds( 500 );// add half a second to dt
                            break;

                        case ghostFacingRight:
                            angle = 3.15f;
                            ghostDirection = ghostFacingDown;
                            Program.form.direction = "";
                            dt.AddMilliseconds( 500 );
                            break;

                        case ghostFacingDown:
                            angle = -1.6f;
                            ghostDirection = ghostFacingLeft;
                            Program.form.direction = "";
                            dt.AddMilliseconds( 500 );
                            break;

                        case ghostFacingLeft:
                            angle = 0.0f;
                            ghostDirection = ghostFacingUp;
                            Program.form.direction = "";
                            dt.AddMilliseconds( 500 );
                            break;
                    }
                }
            }
        }

```

# Answer
You have a pretty fundamental misunderstanding of what the update loop does.

You have to perform one "tick" of you operations every time update is called. That is to say, the update method itself is the loop that executes your commands.

Try just executing one iteration of your foreach loop, removing that element from the collection, then just doing that as long as the collection is not empty to start.
> 6 votes

# Answer
If your code is in update you shouldn't be using for each loop like that. Update is already a loop and you should avoid using loops inside the update... its very bad for for the performance.

My suggestion is for you to make a variable like to control the last time a action was made by the ghost.

```
int a = 2000; // (2 seconds in miliseconds)

```

then to check if this 2 seconds have been spent since the last time

```
 if (a > 0 && ghostMimic )
 {
    // to decrement the time
    a -= gameTime.ElapsedGameTime.Milliseconds;
 }

if ( a <= 0 )
{
  // do next action here

  // restart the counter
  a = 2000
}

```
> 1 votes

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


# Question
Title: How can I save state from script in a multithreaded engine?
We are building a multithreaded game engine and we've encountered some problems as described below.

The engine have 3 threads in total: script, render, and audio. Each frame, we update these 3 threads simultaneously. As these threads updating themselves, they produce some tasks and put them into a public storage area. As all the threads finish their update, each thread go and copy the tasks for themselves one by one. After all the threads finish their task copying, we make the threads process those tasks and update these threads simultaneously as described before. So this is the general idea of the task schedule part of our engine.

Ok, well, all the task schedule part work well, but here's the problem:

For the simplest, I'll take `Camera` as an example:

```
local oldPos = camera:getPosition()  -- ( 0, 0, 0 )
camera:setPosition( 1, 1, 1 )        -- Won't work now, cuz the render thread will process the task at the beginning of the next frame
local newPos = camera:getPosition()  -- Still ( 0, 0, 0 )

```

So that's the problem: If you intend to change a property of an object in another thread, you have to wait until that thread process this property-changing message. As a result, what you get from the object is still the information in the last frame.

So, is there a way to solve this problem? Or are we build the task schedule part in a wrong way? Thanks for your answers :)

# Answer
If objects are in separate threads and you're treating threads as completely separate processes, the objects must obey one of 2 restrictions:

1. The objects in Thread 1 can work with old data for the objects in Thread 2 (so it doesn't matter that the changed position is 1 frame out of date)
2. The objects in Thread 1 don't care at all about the objects in Thread 2.

Generally speaking, you have a mix of both. You shouldn't be changing things in another thread and expecting to operate on the result instantly - instead, you should just operate on the data you have currently, which will have changed next time.

If you *really* need to be able to tell an object in another thread to update, and then need to perform actions dependent on those changes, then you need to make the dependent actions a new task that is dependent on the update task. Your task scheduler should be able to make 1 task wait until another has completed before proceeding.
> 1 votes

# Answer
You can use double or triple buffering for that case, meaning you store data twice, scripting part works with one series of it and rendering part works with the other. At the end of each frame render thread will copy all those data for next frame use into it's buffer.
> 0 votes

# Answer
I think the way you design your engine is wrong. The camera is an object and you want to change its data. Changing data is not a task.

I think you must use mutex for changing the camera object data. With mutex you can be sure when one thread changes the camera data other threads can't change any data of camera. But I don't know what will happen if you change the camera position in middle of the rendering maybe some objects render with new camera position and some with previous one maybe the renderer must get a copy of camera object before starting to render the scene and use it until the end of the frame.
> 0 votes

---
Tags: architecture, multithreading
---


# Question
Title: Can I run into legal issues with random names?
I'm currently building a game whose NPC's are going to be assigned a random gender and a random name for the right gender. To do this I will be using a "database" of names (actually a text file with tuples). There would also be a list of last names, which will be added to the first name also randomly.
My question is the following. Suppose one such random name is "George Bush", and this person has been randomly assigned the job of president. As you can see, this could easily be seen as having been "copied" from a real-life person.
The main issue is this. Names will be randomly-generated, yes, but the seed for random-number generation will be constant. In other words, the name of an NPC would be randomly-generated, i.e. I wouldn't choose it, but it would be the same for every player. Could this get me in trouble? We cannot verify all possible names, since the generated number of NPC's could be potentially limitless (new NPC's are being created whenever needed).

# Answer
> 28 votes
Legally I would be prepared for "change this name" notices and make it very easy to change that name; no matter how much in the right you think you are, it's just a nice thing to do.

Create and maintain a dictionary of names to avoid, no matter how legal it is anyone who sees "George Bush" in your game will immediately lose their sense of immersion.

Combined with a standard fictitious name disclaimer to cover obscure names you should be good to go.

# Answer
> 23 votes
Add a disclaimer:

> *"All characters appearing in this work are fictitious. Any resemblance to real persons, living or dead, is purely coincidental."*

Use the above to cover yourself. And I'll use the below to cover myself.

> I'm not a lawyer and your legal decisions and consequences are your own.

Of course, since neither of us are lawyers, the amount of covering going on anywhere in there is questionable. So if you want a true answer, seek professional legal advice.

# Answer
> 10 votes
You've already chosen an answer, but I think you're making this more complex than you need to.

A lot of people have the same names as famous people, whether by choice or accident. You don't see the estates of famous people demanding average people change their names to avoid confusion, and there's no reason you should worry about it unless you are explicitly trying to imply that your NPC "Goerge Bush" is somehow supposed to be the real one. And even then, even if it was satire, you can still use the real name.

Seriously, just a simple disclaimer like was posted in another answer and you're fine.

"All characters appearing in this work are fictitious and randomly generated. Any resemblance to real persons, living or dead, is purely coincidental."

# Answer
> 4 votes
As long as you can prove your code (in case of legal action, your code will be used as evidence) is generating those names randomly there will be no problem because depending on the amount of data (names, last names, jobs) it is just a matter of statistics to find the probable chance of having those combinations be the same as a real person.

As Byte56 stated, adding a disclaimer will also prove really helpful. Adding the fact that you are generating the NPCs data randomly to that disclaimer will also be great!

---
Tags: legal, content-generation
---


title: How can I run a .jar file with XNA?

text:
# Question
Title: How can I run a .jar file with XNA?
Could someone help me to develop a method to run any .jar file (with parameters) from in C# with XNA?

# Answer
> 7 votes
Since you give absolutely no details as to why you want to do this or how it would be used. I'll just give you the most straightforward simple answer I can come up with.

Start Java as a process:

```
String pathToJava = @"c:\program files\java\bin\java.exe";//replace with automated method to find java on machine
String jarFile = "myjarfile.jar";
String parameters = "-p1 inputparam";
System.Diagnostics.Process.Start(pathToJava + " " + jarFile + " " + parameters);

```

You'd have to verify they have Java installed and that it's up-to-date. This is totally just a guess, since I don't use C# or XNA so I'm not sure if `Process.Start` is supported in XNA or not. But this is a start for you.

---
Tags: xna, c#, java, software-engineering
---


title: Render full-screen gradient or texture

text:
# Question
Title: Render full-screen gradient or texture
What's the simplest way to fill the background of the screen with a gradient or a texture in Direct3D 10/11?

I'm building a Windows 8 metro app in which the camera never moves and I render some content in D3D, but I need to fill the background with something else than a solid color. Do I need to figure out the size and position of a rectangle and position it in 3D space or can I have some simpler solution?

I don't care about depth at all, I don't use any depth buffer since all my content is sorted back to front, so I could just start by drawing to the background.

# Answer
The usual way is to draw a single triangle that covers the whole screen. You can use a simple vertex shader that just copies the UV and position from a vertex buffer - no matrix transformation; you provide the vertices directly in clip space, so no need to position anything in 3D.
> 1 votes

---
Tags: directx, directx11, directx10
---


# Question
Title: Quaternion Camera Orbiting around a Sphere
Background: I'm trying to create a game where the camera is always rotating around a single sphere. I'm using the DirectX D3DX math functions in C++ on Windows.

The Problem: I cannot get both the camera position and orientation both working properly at the same time. Either one works but not both together.

Here's the code for my quaternion camera that revolves around a sphere, always looking at the centerpoint of the sphere, ... as far as I understand it (but which isn't working properly):

(I'm only going to present rotation around the X axis here, to simplify this post)

Whenever the UP key is pressed or held down, the camera should rotate around the X axis, while looking at the centerpoint of the sphere (which is at 0,0,0 in the world). So, I build a quaternion that represents a small angle of rotation around the x axis like this (where 'deltaAngle' is a small enough number for a slow rotation):

```
D3DXVECTOR3 rotAxis;
D3DXQUATERNION tempQuat;

tempQuat.x = 0.0f;
tempQuat.y = 0.0f;
tempQuat.z = 0.0f;
tempQuat.w = 1.0f;

rotAxis.x = 1.0f;
rotAxis.y = 0.0f;
rotAxis.z = 0.0f;

D3DXQuaternionRotationAxis(&tempQuat, &rotAxis, deltaAngle);

```

...and I accumulate the result into the camera's current orientation quat, like this:

```
D3DXQuaternionMultiply(&cameraOrientationQuat, &cameraOrientationQuat, &tempQuat);

```

...which all works fine.

Now I need to build a view matrix to pass to DirectX SetTransform function. So I build a rotation matrix from the camera orientation quat as follows:

```
D3DXMATRIXA16 rotationMatrix;

D3DXMatrixIdentity(&rotationMatrix);

D3DXMatrixRotationQuaternion(&rotationMatrix, &cameraOrientationQuat);

```

...Now (as seen below) if I just transpose that rotationMatrix and plug it into the 3x3 section of the view matrix, then negate the camera's position and plug it into the translation section of the view matrix, the rotation magically works. Perfectly. (even when I add in rotations for all three axes). There's no gimbal lock, just a smooth rotation all around in any direction.

BUT- this works even though I never change the camera's position. At all. Which sorta blows my mind. I even display the camera position and can watch it stay constant at it's starting point (0.0, 0.0, -4000.0). It never moves, but the rotation around the sphere is perfect. I don't understand that. For proper view rotation, the camera position should be revolving around the sphere.

Here's the rest of building the view matrix (I'll talk about the commented code below). Note that the camera starts out at (0.0, 0.0, -4000.0) and m\_camDistToTarget is 4000.0:

```
/*
D3DXVECTOR3 vec1;
D3DXVECTOR4 vec2;

vec1.x = 0.0f;
vec1.y = 0.0f;
vec1.z = -1.0f;

D3DXVec3Transform(&vec2, &vec1, &rotationMatrix);

g_cameraActor->pos.x = vec2.x * g_cameraActor->m_camDistToTarget;
g_cameraActor->pos.y = vec2.y * g_cameraActor->m_camDistToTarget;
g_cameraActor->pos.z = vec2.z * g_cameraActor->m_camDistToTarget;
*/

D3DXMatrixTranspose(&g_viewMatrix, &rotationMatrix);

g_viewMatrix._41 = -g_cameraActor->pos.x;
g_viewMatrix._42 = -g_cameraActor->pos.y;
g_viewMatrix._43 = -g_cameraActor->pos.z;
g_viewMatrix._44 = 1.0f;

g_direct3DDevice9->SetTransform( D3DTS_VIEW, &g_viewMatrix );

```

...(The world matrix is always an identity, and the perspective projection works fine).

...So, without the commented code being compiled, the rotation works fine. But to be proper, for obvious reasons, the camera position should be rotating around the sphere, which it currently is not. That's what the commented code is supposed to do. And when I add in that chunk of code to do that, and look at all the data as I hold the keys down (using UP, DOWN, LEFT, RIGHT to rotate different directions) all the values look correct! The camera position is rotating around the sphere just fine, and I can watch that happen visually too. The problem is that the camera orientation does not lookat the center of the sphere. It always looks straight forward down the z axis (toward positive z) as it revolves around the sphere. Yet the values of both the rotation matrix and the view matrix seem to be behaving correctly. (The view matrix orientation is the same as the rotation matrix, just transposed).

For instance if I just hold down the key to spin around the x axis, I can watch the values of the three axes represented in the view matrix (x, y, and z axes)... view x-axis stays at (1.0, 0.0, 0.0), and view y-axis and z-axis both spin around the x axis just fine. All the numbers are changing as they should be... well, almost.

As far as I can tell, the position of the view matrix is spinning around the sphere one direction (like clockwise), and the orientation (the axes in the view matrix) are spinning the opposite direction (like counter-clockwise). Which I guess explains why the orientation appears to stay straight ahead.

I know the position is correct. It revolves properly. It's the orientation that's wrong.

Can anyone see what am I doing wrong? Am I using these functions incorrectly? Or is my algorithm flawed? As usual I've been combing my code for simple mistakes for many hours. I'm willing to post the actual code, and a video of the behavior, but that will take much more effort. Thought I'd ask this way first.

# Answer
> 4 votes
> if I just transpose that rotationMatrix and plug it into the 3x3 section of the view matrix, then negate the camera's position and plug it into the translation section of the view matrix

That sounds suspicious to me. It sounds like your rotation matrix is the desired camera-to-world rotation, and you're trying to invert it to get the world-to-camera matrix, but what you described above is not the right way to invert an affine transform. Specifically, transposing the 3x3 part of the matrix is fine (since it's a rotation matrix and thus orthonormal), but you can't just negate the translation part; you have to negate it *and* then multiply it by the transposed 3x3 part.

(Proof: let M be the rotation matrix and V be the translation vector, and x be the point you're trying to transform; then, if x' = M * x + V, you can derive x = M^T * (x' - V) = M^T * x' - M^T * V.)

Since you're leaving out that multiply, you're effectively doing the translation and rotation in the wrong order. That explains why the camera's position rotates even though you're not moving it; the translation is acting in camera space instead of world space.

---
Tags: c++, directx, quaternion
---


# Question
Title: Is it reasonable to write a game engine in C?
Even though C++ appears to be king, from what I've been told C is still widely used in games, especially on the consoles. However, would writing an entire game engine in C be unreasonable today? What are, if any, some advantages that C has over C++? Why would someone possibly want to use C over C++?

# Answer
> However, would writing an entire game engine in C be unreasonable today?

It's reasonable, but the question is what does it buy you? You likely don't need the extreme portability C offers, and it's a shame to give up all of the features C++ offers unless you're really philosophically set against it.

> What are, if any, some advantages that C has over C++?

Better compilation time?

> Why would someone possibly want to use C over C++?

I think it's mostly an aesthetic choice. Many people like C because it's simple and minimal and feels clean. C++ has a lot of nice features (namespaces alone make it worth using), but it's also big and messy.
> 51 votes

# Answer
I have worked extensively with a pure-C game engine that has shipped several products, so it is absolutely possible. Here's my personal experience with working in both C vs C++ engines:

1. Using pure-C structures allows you to take advantage of knowledge about the alignment of structures, and you can then use this information to build your object persistence and serialization layers. The engine I worked with had some simple header parsers that would automatically create this metadata about structures, and it made certain types of data operations trivial. Parsing arbitrary C++ header files is essentially impossible, and as soon as you add inheritance and virtual functions you lose the ability to know exactly where things are in memory
2. Compile time is significantly shorter because you can keep your header files very compact and take advantage of forward declarations of structures.
3. Debugging can be improved because without the use of templates and inheritance it is very easy to figure out exactly what a certain object is and what it's doing.

All of these benefits could also be achieved just as easily using restrained c++ code that refrains from using templates and inheritance on serialized objects, but it was the CTO's decision that it would be easier to enforce the simplicity if the more confusing elements of C++ were not available.

Personally I think this was slightly extreme, as I really missed the ability to sanely declare variables in for loops and the many completely legitimate uses for inheritance. But, it really didn't cost us much productivity in the end all things considered
> 61 votes

# Answer
I am rewriting a 2D game engine written in C++ and Lua into C and Lua. So far the experience have been quite good. Obviously doing vector and matrix operations don't end up as nice looking in C. But apart from that I have found the experience quite refreshing after spending 10+ years as a C++ developer.

C has a number of advantages over C++:

1. The compiler will make sure that no code is run at static initialization time. That makes it completely safe to statically allocate global data like strings used as keys e.g.
2. Transparency. In C assignment or allocating or defining a variable is not going to cause loads of code to run. C++ will auto generate copy constructors for you so you have less control over what gets executed when doing assignment.
3. A lot of debugging **can** be easier to due to not getting function names mangled
4. It is usually okay to use **memcpy** in C, but it will easy cause trouble in C++, because copy constructors will not be run. Given that **memcpy** is a lot faster than **std::copy** that matters.

Apart from that there are a number of advantages to getting into the C way of thinking. In C++ I often find myself making things a bit overgeneralized and abstract. In C I usually cut out things like get-set methods and often preallocate fixed sized arrays rather than use dynamic arrays. Often I end up with shorter and more easily debugged code in C. The data structures are usually flatter and easier to view in a debugger.

To be fair I would never make an app exclusively in C. The reason it works it that I combine it with a higher level language like Lua which can complement C very well, were C is not so strong.

Id software writes most of their engines in C I believe, you can look at Return to castle Wolfenstein which was written in C.

I wrote about some of my experience on scalability of C vs C++ and downsides of STL vector compared to plain arrays.
> 21 votes

# Answer
As someone else pointed out, C++ brings the advantage of big shoulders on which you can stand (BOOST, STL etc.). In the end, it is a personal choice, but I would choose C++ because of the available resources. If there are features in C++ that you don't wish to use, then don't use them.
> 7 votes

# Answer
I'll give you a couple more reasons why it would be unreasonable to write a game engine in C instead of C++ today: STL and BOOST.

I can't imagine how it would be worth writing yet another `list` implementation when you could rely on code that works out of the box (and that you don't have to write!)
> 5 votes

# Answer
Writing a game engine in C is reasonable. It's fast and can be ported to multiple systems. For example you could use for Android (with the use of the NDK). You could use it for the iPhone (Objective c is just an extension of c). You could also use it for and of the main OS such as Linux, Mac or Windows. If you feel comfortable with c, I suggest you give it a try!
> 5 votes

# Answer
I don't think anyone uses C exclusively these days, it's usually mixed together with a higher level language.

Programming in C has some benefits over, say, programming in C++. C++ *can* do lot of things under the hood that are invisible to the user, which can hurt performance if you're not careful. C++ *can* also be terrible when it comes to cache usage, which again can hurt your performance.

So it may bring some benefits to write the performance critical parts of a game in a C-like way, rather than in a traditional C++ way. I've never heard of anyone, in recent years, actually writing an entire game in C however.

On some platforms, like the iPhone, using C++ can increase your executable size with a certain chunk of kilobytes (I forgot how much, sorry), which is a reason why some iPhone developers choose to write their code in a mix of C and Objective-C.
> 3 votes

# Answer
Of course it's reasonable. I personally wouldn't do it, and most of the C fans I know actually just write C-like code in .cpp files. But the languages are similar enough to where it doesn't really matter.

As for why someone would choose to do this, I think it's mostly down to anti-C++ philosophy. Personally I still don't think this is a good reason to choose C over "C-style C++". typedef struct craziness is a good enough reason to steer clear of C, and there are a number of others.

Unfortunately C and C++ are both pretty terrible languages when we get down to it. That's one reason people have been trying to do a lot of their code in script in recent years.

If you're looking for examples of people working in C, you can ignore id as I recall reading that they've abandoned C long ago. Cryptic Studios (Star Trek Online) does all their engine development in C, though. As far as I can tell, yes, it's because of philosophy more than because of any tangible advantage.
> 2 votes

# Answer
C code is normally valid C++ code.

The main issues with C++ are using it incorrectly (Linus Torvalds hate it for this reason, he also had some other issues with library portability and so on buy he is working at the operating systems level and has to be able to run things on every random chip out there).

For example there's almost no advantage to using a cstyle array\[\] over a c++ std::vector\<\> (or similar container).

The vectors are typesafe and can be bounds checked (you can access elements using either get() or \[\], even if you don't use the array checked method you can still query the size rather than carting it around with the pointer).

But vectors *can* be slower if, for example, you don't declare the default size in the constructor. Also adding things to a vector can cause slowdowns if it then needs a resize. C++11 adds many advantages too such as uniform initialization (you can now declare and initialize vectors using the same syntax) and there are move constructors that can allow you to avoid copying. You can even make your own custom initializers (if you wanted to do something other than using malloc for some reason).

Or course if you do need to resize things, then vectors are still easier to do it with, you don't have to mess around with malloc, manually copy things and so on.

C++ gives you object orientated code. When compiled it's going to be just as efficient since it's really just an abstraction for humans working with the code. Although things like constructors can slow down object creation. But you will either need the constructor to set the default values or otherwise you can initialize objects without using the constructor (by leaving off the ()'s).

But object orientation makes programming games *much* easier. Games often deal with objects.
> 1 votes

# Answer
Yes and no. Yes I have done it a few years back but I needed my game to run in 3D on a unix (not linux) 64 bit remote server with the players on dumb terminals. It was non trivial. C can be nice is you want to integrate LUA but I eventually got lua to work in C++ so I would say yes it is possible but don't do it.
> 0 votes

# Answer
May a possible good answer be "use both" ?

As I heard that panda3d projects could be optimized, killing bottleneck either using some cython or either recode those parts.

Most of the time, the parts which need to be optimized are the part with a lot of iterations and nesting or with a lot of numeric computing, so my (wild) guess is that one fair compromise would be to use both language, using C for parts that include a lot of low-level programming, so you can't do any misuse of the C++ language for the part which need speed, and C++ for the rest of the game.

Ideally you do the fast part of the engine keeping with the high level in mind, and then use a scripting language or C++ which will use much less nest/loops.

Of course you could never make such an engine that would fit all the games developers would need to do, except if you dedicate your engine for a special kind of game...

But don't take my advice for granted since I'm not an experienced game developer nor an experienced developer... I think C forces you to write fast code, while writing good and fast C++ code for a project as big as a game is a different thing...
> 0 votes

# Answer
C worked for John Carmack, you might get a lot of advantages by using C, but until you get there to benefit from them it might take you a while.

Here you can find a list of game engines some of them are written in C, maybe you can get some insights on how to do a C game engine by going through their source code.
> 0 votes

---
Tags: c
---


# Question
Title: Calculating up-vector to avoid gimbal lock using euler angles
I wish to orbit a camera around a sphere, yet the problem is that when the camera rotates so that it is at the north pole (and pointing down) or the south pole (and pointing up) of the sphere the camera doesn't handle itself very well. It spins rapidly until arriving 180 degrees in the opposite direction. I believe this is known as gimbal lock.

I understand you can avoid this problem using quaternions. But I also read in another forum that it's possible to avoid this easily using euler angles as well. Which I would prefer to do. It was said that all you need to do is "calculate a proper up-vector every frame, and that avoids the problem entirely."

Well, I tried aligning the up-vector with the vertical axis of the camera whenever the camera changed orientation, but this didn't seem to work. Meaning that the up-vector followed exactly the orientation of the camera's y-axis (or it's up vector), instead of using a constant up-vector aligned to the up-vector of the world (0, 1, 0).

How exactly do I go about calculating a proper up-vector as my camera orientation changes to avoid the gimbal lock problem mentioned above?

# Answer
> 10 votes
That's not gimbal lock: the camera simply aligns itself with the **up vector** and then you get a camera transformation matrix that's rank deficit. In not so mathematical terms, try to mind this: you must rigidly rotate the camera's *lookAt* and *upVector* together (using the same transform/rotation). I repeat, this is totally NOT gimbal lock, but it's quite similar in one aspect: you lose one degree of freedom since you end up with ambiguities when you align the up vector with the look at vector.

Short solution: keep track of both *lookAt* and *upVector* and transform them together. That should work just fine (mathematically, but not necessarily optimized from a computational point of view).

# Answer
> 3 votes
That absolutely is gimbal lock actually, and it's impossible to avoid using Euler angles unless you explicitly have a way to find and use a new up vector to compensate for when the camera is approximately parallel to (0,1,0) i.e. abs(dot(camlook, \[0,1,0\])) is approximately equal to 1. Just check for that case, and then pick a new "up" vector and calculate your rotation with respect to that vector instead.

Quaternions are a way to avoid this, although you could potentially just use rotation matrices as well and concatenate them. What you'd have to do to use quaternions is to take the camera's angular velocity (technically it isn't really angular velocity but whatever) and represent it as a quaternion. Now, a quaternion is nothing more than a representation of an axis and an angle of rotation, so what you need to do is figure out how many radians (or degrees) the camera rotates every second and then what axis it rotates about. Use these two values to compute a quaternion.

Now, take the camera's initial orientation and represent that as a quaternion also (or use the identity quaternion, which is \[0,0,0,1\] for \[x,y,z,w\]). To make rotation happen, all you have to do is multiply the quaternions, however the way you have it represented you would be rotating in some fixed step once per second, which is not smooth at all. There are two ways that you can smooth this out.

The first is that you can instead represent the camera's rotation speed at a smaller unit of time than 1 second, say 1 frame maybe, and then just multiply quaternions. This will work fine if you have a fixed frame rate that never varies and even if it varies a bit, it will probably still look decent.

The other thing you can do is what's called a spherical linear interpolation (SLERP), which is a way of interpolating one quaternion onto another. The way to do this is to take the camera's quaternion and then multiply it by the rotation quaternion as before, and store that in a temporary variable. This will be the position that the camera will be in after 1 second. Now, SLERP interpolates between 0 and 1, and in this case you have the camera's current position, which is at the current time, so no change in time i.e. 0, and then the camera's position after 1 second, so conveniently enough you have those two values, so if you use SLERP and give it a value that is the change in time from the last time you updated, that will allow you to compute a new quaternion, which will be the rotation amount that you want for this frame, and then you just multiply that new quaternion by your camera's current quaternion and you're done.

You ultimately need a rotation matrix though for the camera, but turning a quaternion into a rotation matrix is not particularly difficult (it's just math). Don't forget, if you're orbiting a point that isn't at the origin, you'll need to first do a change of basis on the camera so that it's position/rotation/scale/etc. is in the basis of the object that it's rotating about. If the camera's rotation is independent of the sphere i.e. the sphere is not rotating or if it is rotating, the camera doesn't care about that, then just subtract the sphere's world position from the camera's position, then apply your rotation, then add the sphere's world position back to the camera's position. I don't know what math library you're using, but directx math has the necessary quaternion functions that you'll need including SLERP. If you just want to implement these on your own, you'll have to look up the necessary math but it isn't particularly difficult to do (although it's very hard to actually understand what it's doing and why it works, at least in my opinion).

---
Tags: camera, gimbal-lock
---


# Question
Title: Loading levels from .txt or .XML for XNA
I'm attemptin to add multiple levels to my pong game. I'd like to simply exchange a few elements with each level, nothing crazy. Just the background texture, the color of the AI paddle (the one on the right side), and the music.

It seems that the best way to go about this is by utilizing the StreamReader to read and write the files from XML. If there is a better, or more efficient alternative way then I'm all for it. In looking over the XNA Starter Platformer Kit provided by MS it seems that they've done it in this manner as well. I'm perplexed by a few things, however, namely parts within the Level class which aren't commented.

```
/// <summary>
    /// Iterates over every tile in the structure file and loads its
    /// appearance and behavior. This method also validates that the
    /// file is well-formed with a player start point, exit, etc.
    /// </summary>
    /// <param name="fileStream">
    /// A stream containing the tile data.
    /// </param>
    private void LoadTiles(Stream fileStream)
    {
        // Load the level and ensure all of the lines are the same length.
        int width;
        List<string> lines = new List<string>();
        using (StreamReader reader = new StreamReader(fileStream))
        {
            string line = reader.ReadLine();
            width = line.Length;
            while (line != null)
            {
                lines.Add(line);
                if (line.Length != width)
                    throw new Exception(String.Format("The length of line {0} is different from all preceeding lines.", lines.Count));
                line = reader.ReadLine();
            }
        }

```

What does ***width = line.Length*** mean exactly? I mean I know how it reads the line, but what difference does it make if one line is longer than any of the others?

Finally, their levels are simply text files that look like this:

```

....................
....................
....................
....................
....................
....................
....................
.........GGG........
.........###........
....................
....GGG.......GGG...
....###.......###...
....................
.1................X.
####################
```

It can't be that easy..... Can it?

# Answer
The reader wants to ensure that all your lines are the same width as the first line. So it avoids situations like:

```
....................
....................
....................
....................
.......................
....................
....................
.............GGG........
.........###........
....................
......GGG.......GGG...
....###.......###...
......................
.1................X.
####################

```

It's just a simple check to make sure everything is in order. Basically it wants to make sure that you created your "map" file properly. You don't really have to throw an exception, you could just ignore the extra characters, but there would probably be more code involved in that.

I assume you know what each character represents since you have the rest of the code.
> 6 votes

# Answer
There's no reason it couldn't be that easy. It looks like they encoded the level in ASCII graphics. .'s represent empty space, G's represent something (perhaps gold coins?), #'s represent platforms, 1 is the player, and X is the player's destination. You couldn't have a level with an uneven set of widths because it would cause some parts to be drawn off-screen.
> 2 votes

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


# Question
Title: Missing z-axis rotation for transforming between two vectors
I'm trying to rotate a cube so that it's facing up, but am getting hung up on the final implementation details. It now reliably will rotate the x,y axis to the correct side, but the z-axis is never rotating (See photos of before and after rotation). When I'm using the code below I always get '0' for my rotationVector.z. What am I missing here?

```
// Define lookAt vector
lookAtVector = GLKVector3Make(0,0,1);

// Define axes vectors
axes[0] = GLKVector3Make(0,0,1);
axes[1] = GLKVector3Make(-1,0,0);
axes[2] = GLKVector3Make(0,1,0);
axes[3] = GLKVector3Make(1,0,0);
axes[4] = GLKVector3Make(0,-1,0);
axes[5] = GLKVector3Make(0,0,-1);

CGFloat highest_dot = -1.0;
GLKVector3 closest_axis;

for(int i = 0; i < 6; i++) {
    // multiply cube's axes by existing matrix
    GLKVector3 axis = GLKMatrix4MultiplyVector3(matrix, axes[i]);
    CGFloat dot = GLKVector3DotProduct(axis, lookAtVector);
    if(dot > highest_dot) {
        closest_axis = axis;
        highest_dot = dot;
    }
}

GLKVector3 rotationVector = GLKVector3CrossProduct(closest_axis, lookAtVector);

// Get angle between vectors
CGFloat angle = atan2(GLKVector3Length(rotationVector), GLKVector3DotProduct(closest_axis, lookAtVector));

// normalize the rotation vector
rotationVector = GLKVector3Normalize(rotationVector);

// Create transform
CATransform3D rotationTransform = CATransform3DMakeRotation(angle,  rotationVector.x, rotationVector.y, rotationVector.z);

// add rotation transform to existing transformation
baseTransform = CATransform3DConcat(baseTransform, rotationTransform);
return baseTransform;

```

Before 3d Rotation

After 3d Rotation

Implementation based on this post

# Answer
> 2 votes
> ```
> lookAtVector = GLKVector3Make(0,0,1);
> (...)
> GLKVector3 rotationVector = GLKVector3CrossProduct(closest_axis, lookAtVector);
>
> ```

In 3D and higher dimensions, a cross-product returns a vector which is perpendicular to the two input vectors.

`lookAtVector` is defined as (0,0,1).

Hence, if you use it in a cross-product, no matter what the value of `closest_axis` might be, the result will have 0 as its z component, **because if it did not, it would not be perpendicular to `lookAtVector`**.

You don't say what you're actually trying to do, so I can't go on and explain how to actually do whatever your intent was. But I hope that the explanation of the maths is enough to help you solve your own issue, here!

# Answer
> 0 votes
I don't think this is your entire problem, but you do at least need to be doing this:

```
CGFloat highest_abs_dot = 0.0;
GLKVector3 closest_axis;

for(int i = 0; i < 6; i++) {
    // multiply cube's axes by existing matrix
    GLKVector3 axis = GLKMatrix4MultiplyVector3(matrix, axes[i]);
    CGFloat abs_dot = fabsf(GLKVector3DotProduct(axis, lookAtVector));
    if(abs_dot > highest_abs_dot) {
        closest_axis = axis;
        highest_abs_dot = abs_dot;
    }
}

```

# Answer
> 0 votes
Remember that there are 4 possible orientations of the cube for any given face 'up'.

I made a game of rotating cubes before (search 'Obecolo').

To avoid floating point approximation errors accumulating in each cubes model matrix, I set up a multiply-linked list of the 24 possible orientations. I.e., each entry would have links to the 'adjacent' orientations obtained by rotating +-90 degrees on each axis.

I built the list on startup, one antry at a time, by multiplying basic 'building block' matrices (i.e., 90, 180 or 270 rotation on X, Y or Z).

To write the code above, it helped a lot to have a cube on my desk with the faces labeled 'TOP', 'BOTTOM', 'LEFT', 'RIGHT', 'FRONT' and 'BACK'. Also, texturing the cube faces with colors that provide a visual cue: RED for +X (cyan for -X), GREEN for +Y (magenta for -Y) and BLUE for +Z (yellow for -Z).

---
Tags: 3d, mathematics, ios, objective-c
---


title: rotating an object on an arc

text:
# Question
Title: rotating an object on an arc
I am trying to get a turret to rotate on a 90 degree arc (rotating about 2 orientations about the y-axis), and have hit a wall.

I have 8 possible starting orientations (multiples of 45 degrees about the y-axis) for the turrets, and want them to rotate on a 90 degree arc. I currently take the starting orientation of the turret, and then from that derive the positive, and negative boundary of the arc. because of engine feature/restriction (Unity) I have to do all of my tests against a value which is between \[0,360\], and due to numerical precision issues I can not test against specific values, but should only limit tests to greater, and less then operators.

I would like to write a general test without having to go in, and jury rig cases

```
//my current test is:
// member variables
public float negBound;
public float posBound;

// found in Start() function (called immediately after construction)
/* because Unity uses a Quaternion for orientation of object they offer
 * the ability to work with them in the form of eulerAngles.
 * eulerAngles.y is the the degree measure of the starting y rotation */
negBound = transform.eulerAngles.y-45;
posBound = transform.eulerAngles.y+45;
// insure that values are within bounds
if(negBound<0){
    negBound+=360;
}else if(posBound>360){
    posBound-=360;
}

// called from Update() when target not in firing line
void Rotate(){
    // controlls what direction
    if(transform.eulerAngles.y>posBound){
        dir = -1;
    }
    else if(transform.eulerAngles.y < negBound){
        dir = 1;
    }
    // rotate object
}

```

follows is a table of values for my different cases (please excuse my force formatting) read as base is the starting rotation of the turret, neg is the negative boundry, pos is the positive boundry, range is the acceptable range of values, and works is if it performs as expected with the current code.

```
| base | neg | pos |       range        | works |
|    0 | 315 |  45 | 315->0,   0->45    | no    |
|   45 |   0 |  90 | 0->45,    54->90   | yes   |
|  135 |  90 | 180 | 90->135,  135->180 | yes   |
|  180 | 135 | 225 | 135->180, 180->225 | yes   |
|  225 | 180 | 270 | 180->225, 225->270 | yes   |
|  270 | 225 | 315 | 225->270, 270->315 | no    |
|  315 | 270 |   0 | 270->315, 315->0   | no    |

```

I will need to do all tests from derived, or stored values, but can not figure out how to get all of my cases to work simultaneously.

```
//I attempted to concatenate the 2 tests:
if((transform.eulerAngles.y>posBound)&&(transform.eulerAngles.y < negBound)){
    dir *= -1;
}

```

this caused only the first case to be successful

```
// I attempted to store a opposite value, and do a
void Rotate(){
    // controlls what direction
    if((transform.eulerAngles.y > posBound)&&(transform.eulerAngles.y<oposite)){
        dir = -1;
    }
    else if((transform.eulerAngles.y < negBound)&&(transform.eulerAngles.y>oposite)){
        dir = 1;
    }
    // rotate object
}

```

this causes the opposite situation as indicated on the table.

What am I missing here?

# Answer
> 1 votes
The main problem with your approach is that you're forgetting that when one of the min/max values are outside of the \[0,360\] bounds, there are actually two possible ranges for values to be valid.

Your case one (Base 0):

```
0    45     315 360
[+++++]-----[+++++]

```

As such, in these cases, we need to compare against both ranges.

```
// Returns true if the current Y-axis rotation of this object is within the
// minBounds and maxBounds members wrapped to the [0,360] range, false otherwise.
private bool IsInBounds(){
    float rot = transform.eulerAngles.y;

    // First case, if the positive bound is greater than 360 degrees
    if ( posBound > 360f ) {
        // return (within lower bounds) OR (within higher bounds);
        return  ( 0f < rot && rot < posBound - 360f ) || ( negBound < rot && rot < 360f );

    // Second case, if the negative bound is less than 0 degrees
    } else if ( negBound < 0f ) {
        // return (within lower bounds) OR (within higher bounds);
        return ( 0f < rot && rot < posBound ) || ( negBound + 360f < rot && rot < 360f );
    }

    // Neither bounds are outside of the [0,360] range, only one range to check
    // return (within bounds);
    return ( negBound < rot && rot < posBound );
}

```

This code returns true if the value rot is in a bound. **Note that I did not do any checking when generating posBound and negBound on turret creation;** I let them stay out of the \[0,360\] range.

I only added in the extra variable for readability, in your actual code `rot` should be replaced with `transform.eulerAngles.y`

...Unless Unity doesn't cache the Euler angle representation of the rotation, in which case it's probably much faster to store the angle locally. On that note of caching, I'm not certain if caching the full bounds and the correct in-bounds function as a delegate instead of the if comparisons would be worth the memory, but it's something worth thinking about.

The public fields are making my C# encapsulation sense tingle. You should probably make those private, and create public properties if you REALLY need to access those two variables outside the class, unless Unity can't cope with properties.

---
Tags: unity, rotation, logic
---


# Question
Title: How should bots be recognised in a game?
I'm interested in how bots are usually written.

Here's my situation:

I plan to make an online 2D mecha game in HTML5, and the server-side will be done with node. It is intended to be multiplayer, but I also want to make bots in case there aren't enough players.

How does my game logic see them, as players or as bots? Is there a standard by which I should make them? Also, any general tips and hints will be OK.

# Answer
It depends on your game logic but I would say: neither!

Your game should see the players as Mechs and the bots as Mechs, and deal with Mechs accordingly. If your bots see an enemy Mech, what's it matter whether it's a player or a bot? Shoot it!

Your game should differentiate between a Mech who's a player and a Mech who's a bot only when it's necessary - otherwise it shouldn't really need to care! Same with differentiating between a Mech who's on one side and a Mech who's on another.

This could tie into component oriented design where your Mechs might be similar entities but one might just happen to have a player control component and another has an AI control component - it would circumvent any inheritance issues.

Note: Mechs and Mecha are a similar thing with two very different design ideologies and I know the question states Mecha but I've just gone with the Mech term in this answer
> 7 votes

---
Tags: software-engineering, ai, networking, multiplayer
---


# Question
Title: OpenGL align grid like glOrtho but with gluPerspective?
Using `gluPerspective` makes OpenGL's grid really messy and rather hard to use especially when trying to do mouse input. The grid that perspective uses is completely messed up compared to the grid you get with the mouse. When using `glOrtho` the grid is fixed to the mouse grid, but then you can only do 2D work, how would I set up perspective to get the same results as if I were using `glOrtho`?

# Answer
If you want to use a perspective matrix for rendering, but an orthographic projection for retrieving mouse input, why not set up both?

```
// this example uses the free and open source OpenGL Mathematics library
// you can get it here: http://glm.g-truc.net/

glm::mat4x4 perspective = glm::perspective(90.f, 640.f / 480.f, 0.1f, 1000.f);
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(glm::value_ptr(perspective));

// <render game here>

// get mouse in world coordinates

glm::vec3 mouse = GetMousePosition3D();
glm::mat4x4 camera = GetCameraMatrix();
glm::mat4x4 orthographic = glm::ortho(0.f, 640.f, 480.f, 0.f);
glm::vec4 viewport(0.f, 640.f, 0.f, 480.f);

glm::vec3 mouse_world = glm::unProject(mouse, camera, orthographic, viewport);

```
> 4 votes

# Answer
Both glOrtho and gluPerspective are deprecated: OpenGL expects you to construct, manipulate, and use matrices in your own programs and shaders.
> 1 votes

---
Tags: opengl, grid, glut
---


# Question
Title: How to play the sound of an object sliding on another object for a variable duration
I would like to add sound effects to a basic 2D game. For example, a stone sphere is rolling on wood surface. Let's say I have a 2 second audio recording of this. How could I use the sample to add sound for an arbitrary duration ?

So far I have two solutions in mind:

a/ record the sound for an amount of time that is greater than the maximum expected duration, and play only a part of it;

b/ extract a small portion of the sample and play it in a loop for the duration of the move; however I'm not sure if it makes sense with an audio wave.

# Answer
> 4 votes
The typical method is to have a sample with loop points in the middle. It loops for as long as necessary then it can cross-fade into the end of the sample when it is supposed to stop. To do this, you need to know the loop points within your sample, and know where the end section of the sample is, and you need a sound library capable of doing these operations (which depends on the language and platform you're using).

# Answer
> 1 votes
Answer to your question depends on the audio API you're using in your project.

If an API allows you to use wave samples of an arbitrary length and play them with specified volume and pitch, you can make a sliding sound volume and pitch depend on the speed of a sliding object. The faster object slides, the louder the sample plays and it's more pitched up.

For a length of a sample - I would use a looping sample of longer duration, let's say 10s, with extra texture in it (e.g. a mixed grain of sand in a friction sound for a sliding cube, or some louder bumps in sound of a rolling sphere on a wooden surface). It would improve overall quality of this trick. Short samples tend to be perceived as repeatable.

# Answer
> 0 votes
Your ideas are good. I would attempt to go with something of a mixture between option A and B. Make a sound that's long enough for most scenarios, but also loopable. This way you can get a sound that doesn't sound like it's on a tight loop, but which won't get "cut off" if you were to have a situation where the sound might play too long. I haven't started the sounds part of my game yet, so I don't know a lot about what tools are available. There are a few that I have bookmarked for future use, which might be useful.

1. bfxr This one and number two are for generating sounds effects. I have no idea what 75% of the sliders do, but I just slide them around until I get something like what I want.
2. sfxr
3. Dynamically composing music and sound effects \- Don't follow that one *too closely* ;)
4. Creating and playing synthetic sound \- Just something to get started with, then create algorithms for the sounds I want.
5. Audacity I use this now for editing the voice overs on my videos, great program. Unfortunately it doesn't help the feeling that I sound weird to myself.

---
Tags: sound-effects
---


# Question
Title: Why do I get an exception when playing multiple sound instances?
Right now, I'm adding a rudimentary sound engine to my game. So far, I am able to load in a WAV file and play it once, then free up the memory when I close the game. However, the game crashes with a nice **ArgumentOutOfBoundsException** when I try to play another sound instance.

> Specified argument was out of the range of valid values. Parameter name: readLength

I'm following this tutorial pretty much exactly, but I still keep getting the aforementioned error. Here's my sound-related code.

```
/// <summary>
/// Manages all sound instances.
/// </summary>
public static class Audio
{
    static XAudio2 device;
    static MasteringVoice master;

    static List<SoundInstance> instances;

    /// <summary>
    /// The XAudio2 device.
    /// </summary>
    internal static XAudio2 Device
    {
        get { return device; }
    }

    /// <summary>
    /// Initializes the audio device and master track.
    /// </summary>
    internal static void Initialize()
    {
        device = new XAudio2();
        master = new MasteringVoice(device);

        instances = new List<SoundInstance>();
    }

    /// <summary>
    /// Releases all XA2 resources.
    /// </summary>
    internal static void Shutdown()
    {
        foreach(SoundInstance i in instances)
            i.Dispose();
        master.Dispose();
        device.Dispose();
    }

    /// <summary>
    /// Registers a sound instance with the system.
    /// </summary>
    /// <param name="instance">Sound instance</param>
    internal static void AddInstance(SoundInstance instance)
    {
        instances.Add(instance);
    }

    /// <summary>
    /// Disposes any sound instance that has stopped playing.
    /// </summary>
    internal static void Update()
    {
        List<SoundInstance> temp = new List<SoundInstance>(instances);
        foreach(SoundInstance i in temp)
            if(!i.Playing)
            {
                i.Dispose();
                instances.Remove(i);
            }
    }
}

/// <summary>
/// Loads sounds from various files.
/// </summary>
internal class SoundLoader
{
    /// <summary>
    /// Loads a .wav sound file.
    /// </summary>
    /// <param name="format">The decoded format will be sent here</param>
    /// <param name="buffer">The data will be sent here</param>
    /// <param name="soundName">The path to the WAV file</param>
    internal static void LoadWAV(out WaveFormat format, out AudioBuffer buffer, string soundName)
    {
        WaveStream wave = new WaveStream(soundName);

        format = wave.Format;

        buffer = new AudioBuffer();
        buffer.AudioData = wave;
        buffer.AudioBytes = (int)wave.Length;
        buffer.Flags = BufferFlags.EndOfStream;
    }
}

/// <summary>
/// Manages the data for a single sound.
/// </summary>
public class Sound : IAsset
{
    WaveFormat format;
    AudioBuffer buffer;

    /// <summary>
    /// Loads a sound from a file.
    /// </summary>
    /// <param name="soundName">The path to the sound file</param>
    /// <returns>Whether the sound loaded successfully</returns>
    public bool Load(string soundName)
    {
        if(soundName.EndsWith(".wav"))
            SoundLoader.LoadWAV(out format, out buffer, soundName);
        else
            return false;

        return true;
    }

    /// <summary>
    /// Plays the sound.
    /// </summary>
    public void Play()
    {
        Audio.AddInstance(new SoundInstance(format, buffer));
    }

    /// <summary>
    /// Unloads the sound from memory.
    /// </summary>
    public void Unload()
    {
        buffer.Dispose();
    }
}

/// <summary>
/// Manages a single sound instance.
/// </summary>
public class SoundInstance
{
    SourceVoice source;
    bool playing;

    /// <summary>
    /// Whether the sound is currently playing.
    /// </summary>
    public bool Playing
    {
        get { return playing; }
    }

    /// <summary>
    /// Starts a new instance of a sound.
    /// </summary>
    /// <param name="format">Format of the sound</param>
    /// <param name="buffer">Buffer holding sound data</param>
    internal SoundInstance(WaveFormat format, AudioBuffer buffer)
    {
        source = new SourceVoice(Audio.Device, format);
        source.BufferEnd += (s, e) => playing = false;

        source.Start();
        source.SubmitSourceBuffer(buffer); // THIS IS WHERE THE EXCEPTION IS THROWN
        playing = true;
    }

    /// <summary>
    /// Releases memory used by the instance.
    /// </summary>
    internal void Dispose()
    {
        source.Dispose();
    }
}

```

The exception occurs on line 156 when I am playing the sound:

```
source.SubmitSourceBuffer(buffer);

```

# Answer
> 1 votes
The call to `SubmitSourceBuffer` will attempt to convert the managed `AudioBuffer` to its native representation and then invoke the native function. Assuming the exception is not thrown from a callback into your own code, the likely place for this error to come from is the call to `Utilities::ReadStream` that occurs with `AudioBuffer`'s `ToUnmanaged` function.

The conversion process is attempting to read `buffer.AudioBytes` worth of data from `buffer.AudioData`, which is of type `System.IO.Stream`.

You probably need to set `buffer.AudioData.Position = 0` prior to calling `SubmitSourceBuffer`.

---
Tags: c#, slimdx, xaudio2
---