# Question
Title: Where can I access the installed Maya Bonus Tools?
I installed Maya 2013 Bonus Tools... checked plugin manager... don't know what plugin to load to use UV Align feature.

Where can I access the installed Bonus Tools?

# Answer
> 1 votes
From the Bonus Tools page:

> If you have installed Bonus Tools but can not see the menu then you may need to update your userSetup file. See below...
>
> Copy C:\Program Files\Autodesk\MayaBonusTools2012\scripts\userSetup.mel Copy C:\Program Files\Autodesk\MayaBonusTools2012\python\userSetup.py
>
> Paste both in C:\users\name\My Documents\maya12-x64\prefs\scripts

Also don't forget to run `userSetup.mel` script from Maya.

---
Tags: maya
---


# Question
Title: Issues calculating frame independent movement
I'm developing a Breakout style game in C++ using SDL. The problem so far is that the ball slows down and speeds up for no particular reason.

The slowdowns usually last a few seconds.

EDIT : When running fullscreen I noticed that the ball movement seems to be a tiny bit jerky as well. This leads me to believe that the timing should be more finely granulated. But at the same time, it shouldn't be necessary to have µs precision...

Here is my code for calculation the movement of the ball :

```
double deltaMovement = tick * speed;

rect.x += static_cast<int> ( deltaMovement * dirX );
rect.y += stnecessearyatic_cast<int> ( deltaMovement * dirY );

```

I tried changing it to help prevent float to in truncation, but this affects the speed to much, making the ball move only move horizontally or vertically ( which never happens with the above code. )

```
double movementX = ( deltaMovement * dirX );
double movementY = ( deltaMovement * dirY );

movementX += ( movementX > 0.0f )? 0.5f: -0.5f;
movementY += ( movementY > 0.0f )? 0.5f: -0.5f;

rect.x += static_cast<int> ( movementX );
rect.y += static_cast<int> ( movementX );

```

`rect` is an `SDL_Rect` and holds the ball's position. `dirX` and `dirY` are `double` and holds the direction of the ball, the values range from `-1.0` to `1.0`

I'm not sure if the issue is with the `float` to `int` conversion. I guess it could also be something with SDL internally, but I am quite sure SDL should be capable of smooth animation.

---

Here's my main game loop ( I have removed some irrelevant parts of it ) while ( !quit ) { while ( SDL\_PollEvent( &event ) ) { // Handle input, move paddle, check if user pressed esc // Yes I have a means of escaping the outer while loop. } double delta = timer.GetDelta( );
```
    // Update the ball, check for collisions with wall/paddle/tiles
    UpdateBalls( delta );

    // Redraws everything
    UpdateGUI();
}

```

---

I'm quite sure the issue is not with my delta time, since it's fairly consistant at 1 - 4 msec. And even if it did change a lot, it shouldn't matter. But just in case, here's the code I use for calculating delta time :
```
double Timer::GetDelta( )
{
    timespec tmCurrent;
    clock_gettime( CLOCK_MONOTONIC_RAW, &tmCurrent);

    // Get current time in nanoseconds
    unsigned long long deltaCurrent = static_cast< unsigned long long > ( tm.tv_sec * 1000000000 + tm.tv_nsec );

    // Get diff. Delta is an unsigned long long that holds previous tick ( see below)
    unsigned long long diff = deltaCurrent - delta;

    // Convert into ms and assign to a double
    double deltaMSec = static_cast< float > ( diff / 1000000.0f );

    // Reset delta so that it can be used the next time delta is calculated
    delta = deltaCurrent;

    return deltaMSec;
}

```

---

What am I doing wrong?

# Answer
I don't think your issue is timing related. If you change your object velocity so that the amount of movement per update is very low (i.e. less than 0.5 units per update) my guess is that your object will never move at all!

Currently, you are tracking a moving position over time as an integer (SDL\_Rect is integer based). Any fractional movement associated with each update is lost due to the casting to an integer. Over time, these missing fractional movements add up and lead to jittery, non-smooth movement of the object overall. This is especially obvious for slower moving objects where the rounding doesn't average out as well and the discarded fractional portion represents a larger part of the overall movement.

The solution is to track your positions in floating point coordinates, then convert to integer coordinates only when rendering.
> 3 votes

---
Tags: c++, mathematics, physics, floating-point
---


# Question
Title: Saving instances of classes, then recreating the instances
I have many types of entities, each type has a lot of `if instanceof Spider` (for example ) then do this in the game code... Now I got to the part where I want to save each type.

They all are based on the same class, Entity but implement some of their own methods. When I save them, lets say for now I just want their position and their health.

So I do write position the write health, to a file with all the entities.

Now here is the problem, When I want to load it, How will I know it's a spider and then create a Spider instance?

An easy fix is to create toString method then writing it before the position and health. But the problem with this is that when I load I will have to have this big switch statement for each type and I will have to manually add the case for a new type that I create. This is not very mod friendly.

What would be a way to read a name of a class and then create an instance of that class without having a big switch case?

# Answer
> 8 votes
I would avoid using reflection for something like this, and use a language-agnostic tagged blob format, or something like this (just one possible method for entity serialization):

Have an `ISaveable` interface with a method that produces an `Entity` given a hunk of save data, and produces a hunk of save data given an `Entity`.

```
public interface ISaveable {
    public SaveHunk save(Entity e);
    public Entity load(SaveHunk sh);
    public GUID getClassID();
}

```

Create anonymous instances of `ISaveable` for each entity type (ie. `Spider`, `Player`, `Box`, etc.) and have these know how to consume a hunk of save data (raw string, XML, JSON, etc.) and create the appropriate entity, how to convert that entity back into a hunk of save data.

```
ISaveable spiderSaveable = new ISaveable() {
    @Override
    public SaveHunk save(Entity e) {
        if (e == null) return null;
        if (!(e instanceof Spider)) {
            return null;
        }
        SaveHunk hunk = new SaveHunk(getClassID(), e.getEntityID());
        Spider spider = (Spider)e;
        hunk.put("pos", spider.getPosition().toString());
        hunk.put("vel", spider.getVelocity().toString());
        // and so on
        return hunk;
    }
    @Override
    public Entity load(SaveHunk hunk) {
        if (hunk== null) return null;
        if (!hunk.getClassID().equals(getClassID())) {
            // The GUIDs don't match, may want to handle this in the manager
            return null;
        }
        Spider spider = new Spider(hunk.getEntityID());
        spider.setPosition(Vector3.parse(hunk.get("pos")));
        spider.setVelocity(Vector3.parse(hunk.get("vel")));
        // and so on
        return spider;
    }
    @Override
    public GUID getClassID() {
        return Spider.UNIQUE_CLASS_ID;
    }
};

```

Have a manager class which can have `ISaveable` instances attached to it for a globally unique ID that represents a single class (ie. `Player`s are always 1, `Spider`s are always 2, `Box`es are always 3, so on.)

```
saveManager.addSaveable(spiderSaveable);

```

When you save, pass all entities in the world into the manager, fetch the `ISaveable` corresponding with their class ID, and pass them into that `ISaveable`'s `SaveHunk save(Entity e)` method, which downcasts the entity and converts its important values to a hunk of save data, and write that hunk to a file following the class ID.

```
for (Entity e : world.getEntities()) {
    ISaveable saveable = saveManager.getSaveable(e.getClassID());
    if (saveable != null) {
        saveFileWriter.writeHunk(saveable.save(e));
    } else {
        // Log a warning
    }
}

```

When you load, read the file starting from the class ID, fetch the corresponding `ISaveable` for that class, then pass the hunk of save data from the file into the `ISaveable`'s `Entity load(SaveHunk sh)` method.

```
for (SaveHunk hunk : saveHunksFromFile) {
    ISaveable saveable = saveManager.getSaveable(hunk.getClassID());
    if (saveable != null) {
        world.loadEntity(saveable.load(hunk));
    } else {
        // Log a warning
    }
}

```

### LIMITATIONS

Note that this is only one single approach, and has its (drastic) limitations. Hooking all of the `ISaveable` instances for each class type is nasty, and takes time to iterate across all entity classes. Plus, it has to be done at some point before creating the world, or you won't be able to load stuff into said world. In addition, if you change the ID for a class (say you want to remove an enemy type), then your save files all become broken or corrupted if they have that enemy type (which may be desirable or undesirable, depending on how well you handle that; my code just does nothing special in that situation).

This also limits how you use base classes and subclasses for entities; if you break out `Spider` into `CaveSpider` and `FieldSpider`, for example, then which `ISaveable` do you use? It effectively means you can't/shouldn't have branch classes be instantiated in your world, or that if you want a `Spider`, then it has to have its own leaf class, like `CommonSpider`, instead of using the more generic `Spider`, otherwise you end up complicating your loaders and duplicating code between them. You could have a multi-step `ISaveable` hierarchy, where stuff passes the rest of a hunk of save data down to more generic `ISaveables` for base classes, but it raises the complexity of the system dramatically, since entities now have to know all of their own base classes.

### ADVANTAGES

With this approach, or an approach similar to this, there are a number of advantages over using straight reflection.

* By using a factory-style approach to loading and saving, you avoid the need for a standard initialization procedure for all entity classes, since the knowledge of a class' creation and initialization is left up to the `ISaveable` instance for that class.
* You use a GUID and avoid using the fully-qualified class names in your save files, which allows for obfuscation and reduced save file size, not to mention easier porting of save files between languages (if needed for external development tools).
* There is a separation of concerns being observed between the Entity classes (which should only be concerned with the game itself) and the save/load system (which should only be concerned with saving and loading data).
* This method is easily adaptable to other architectures (ie. Component-Entity-System model) with only minor modification.
* By using a uniform construct for representing save data (ie. `SaveHunk`), you can easily switch the format of the actual save file, and retain the same code base.
* The switch-case is avoided in favor of a map lookup.

# Answer
> 4 votes
The toString() part on its own doesn't seem so bad. I think one way of handling the re-loading of the objects would be through use of Reflection.

```
// an example of a forName argument: "java.util.Map"
Class loadedObjectClass = Class.forName(xml.getElementValue("clazzName"));
Object loadedObject = loadedObjectClass.newInstance();

```

I'll also note some people are going to be concerned over excessive use of type-checking; that's eventually going to lead you to the massive switch statements you were trying to avoid. Example: Instead of having a player collision method that checks if something is a spider, and damages the player, try having an `onTouch()` method for each object, that does nothing for most objects, and damages the touch-er inside the `Spider` class. (then, if the touch-er can't be damaged, you can just have their `damage()` method do nothing)

Finally, be wary of savvy users hacking the game if they see class names inside of the plaintext save files. There's no need to forcibly make single-player hacking impossible, but you might just want to obfuscate the save files a little bit to make it difficult.

# Answer
> 0 votes
first of java has good OO let it shine

each time you used `instanceof` create a new instance method and reimplement in the subclass

you can also use getter methods that return parameters like base movement speed for use in standard methods

do the same for the saving and loading (like @shotgunninja does but each entity is ISavable)

and when loading have the hashmap (or just an array if you can ensure the order will remain the same ;) ) contain the Entity factories that creates a blank entity on which you can call `load(SaveChunk)` which will configure it (as a bonus this allows pooling when GC pauzes becomes too much for ya)

---
Tags: java, loading, savegame
---


# Question
Title: What is the state of the art of ray tracing on the GPU?
I think ray trace rendering had to be done on the CPU for a long time. But since we have compute shaders in OpenGL 4.3 now, it might be possible to move the computations on the GPU and perform passable real time rendering.

What approaches for GPU based ray tracing are there already? Can it compete with rasterization rendering nowadays?

# Answer
You can get more than passable real time rendering. The main problem is that a very high end machine is required. The Octane Renderer is a real time renderer aimed at stand alone rendering (think movies). Theres also the Brigade engine (by the same people) which is not currently public. You can find impressive videos of it running on this blog.

They were at siggraph'12 with this demo (video). As you can see, if the scene and camera are still the image converges very quickly and looks quite impressive, but constant movement causes grain artifacts, presumably from limiting the number of bounces per frame. It isn't competitive with rasterization because of this grain and the hardware requirements, but I think it will only become more viable as video cards get cheaper and more powerful.
> 2 votes

# Answer
Nvidia's OPTIX library for CUDA is probably about as fancy as it gets for fast GPU rendering. Here is a demo that Pixar recently did showing off the use of full film assets in an unreleased renderer doing real time previews inside of Katana. It uses Optix for the ray tracing (and quite a lot of GPU horsepower) to do very rapid preview rendering with lighting that is quickly nearly on par with actual film renders.

http://www.cgchannel.com/2013/08/see-pixars-gpu-lighting-workflow-on-monsters-university/
> 3 votes

---
Tags: rendering, raytracing, gpgpu
---


# Question
Title: 2D Island generator algorithm - chances of tile becoming land
I am developing my first island generator (in c#). I am using this algorithm as my basic idea : http://www.funstormgames.com/blog/2012/09/procedural-island-generation-for-ludum-dare-24/

Basically you loop around the tiles in a spiral shape, adding land based on chances - the more land the current tile is touching, the more chances of this tile becoming land. However, I don't know how to work with the chances - whatever I put I am never satisfied with my result.

If you havent worked using this algorithm, you can't really help me with the numbers, but a recomendation for a new approach would be great!

I am using a function to determine each tile - passing an argument called potentialChance. For the first "circle" or round around the starting island I put a 25 potential chance.

This potential chance was at first multiplied with the number of land tiles the current grid we are potentially changing into land is touching. So, if a grid has 3 surrounding tiles of land, its chance would be 75% (I generate a random number up to 100 and compare).

I was not satisfied with too many islands I got, and I was changing the potential chance while testing. So instead of multiplying the number of tiles with the potential chance - I tried a different approach.

I would have a quotient of ie 0.7, and for each surrounding land tile, I would multiply the quotient by ie 1.5, and then multiply that number with the potential chance. Still, I was not too satisfied.

I know my algorithm works properly (I have debugged and seen the results), but my numbers are not too good.

If anyone worked with this same logarithm, I would love to see the approach and numbers! Otherwise, would you suggest working on a new algorithm? I'm new in game development so...

# Answer
> 3 votes
Both of these ideas require a test bed that lets the program run over and over with different parameters fed into it at each iteration:

If you want a "really out there" idea build a little genetic algorithm that works with your parameter set and let it run; at each result give the genes a Yes or No, eventually you'll approach something you like =)

Alternate version of the genetics would be to set all the parameters randomly, then as before give each iteration a Yes or No. Keep track of parameters that get more Yes and limit the randomness to nearby values, and so on.

Either would let you exhaust the possibilities of your current algorithm fairly quickly to help you decide on a winner or to move on to another procedure.

# Answer
> 1 votes
You could try to build your own algorithm around Perlin-Noise, it´s basically an algorithm used to create random shapes which look somewhat like clouds and is often used for random terrain generation (heightmaps).

http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series4/Perlin\_noise.php
(XNA and C# and in this case not utilised for your problem, but it still explains the Idea, i recommend to do some research on the topic on your own)

If you create the random map in a smart way and tweak all the parameters for the noisemap generation and maybe apply a mask to make sure you wont have any land on the edges of your map you will come up with a great island shaped map.

Perlin Noise might seem hard to control but in fact you can define the outcome very well if you know what youre doing. Just play with the factors for each scale of the map and see what gives you the desired results. You can allways do some non-random tweaking for example making values close to the center of the map generally higher then those close to the edges or calculate an exponential function for every value in the noisemap to get sharper edges, which might be a good thing in your case.

The next step will be to actually create the diffrent locations for the tiles from that map, but that shouldn´t be too hard. One way would be to say that every tile with a noisemap value lower than e.g. 0.1 is water and everything above is land. Very high values around 0.9 can be mountain rocks or whatever you may need, you will have to work out the details yourself here, it really depends on what you need. For things like forrest you can create one noisemap that generally defines where land and where water is and then a second which defines where forrest is, then multiply both together and you have a nice noisemap within your islands area.

These are just some ideas, there are plenty of ways to do this, just learn about perlin noise and see what works best in your case, Good Luck!

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


# Question
Title: Rotate an object smoothly on the Y axis in Unity
I am attempting a simple script to swing a door open in Unity. This requires a smooth rotation of 90 degrees around the Y axis. I have seen that one way to do this is using Unity's Quanternion object. I believed that this should work:

```
public class DoorOpenScript : MonoBehaviour
{

    public float smooth = 20;

    // Use this for initialization
    void Start ()
    {
        SwingOpen ();
    }

    // Update is called once per frame
    void Update ()
    {

    }

    void SwingOpen()
    {
        Quaternion newRotation = new Quaternion(transform.rotation.x,transform.rotation.y,transform.rotation.z,transform.rotation.w);;
        newRotation *= Quaternion.Euler(0, 90, 0); // this add a 90 degrees Y rotation
        transform.rotation= Quaternion.Slerp(transform.rotation, newRotation,20 * Time.deltaTime);

    }

}

```

However, this just opens the door completely. I have tried playing with the third parameter to `Slerp` but with no results. What am I doing incorrectly?

# Answer
> 5 votes
Think about what you need to do, open the door over time. It's not going to happen all in one call in the `Start` function. You'll need to add a little more rotation each frame to rotate the object smoothly. Something like the following will rotate the object from 0 to 90 degrees over time:

```
void Update () {
    SwingOpen();
}

void SwingOpen()
{
    Quaternion newRotation = Quaternion.AngleAxis(90, Vector3.up);
    transform.rotation= Quaternion.Slerp(transform.rotation, newRotation, .05f);
}

```

Notice it's using the `Update()` function instead of `Start()`. That's because we want to change it a little each frame. Using `Slerp` you'll notice that the object swings fast at first, then slower until finally reaching its rotation. The last parameter controls that rate of change, with `1` being instantly and `0` being never.

Perhaps this is your intended behavior, if not you can also perform a constant rotation over time with something like the following:

```
public float rotationDegreesPerSecond = 45f;
public float rotationDegreesAmount = 90f;
private float totalRotation = 0;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    //if we haven't reached the desired rotation, swing

    if(Mathf.Abs(totalRotation) < Mathf.Abs(rotationDegreesAmount))
        SwingOpen();
}

void SwingOpen()
{
   float currentAngle = transform.rotation.eulerAngles.y;
   transform.rotation =
    Quaternion.AngleAxis(currentAngle + (Time.deltaTime * degreesPerSecond), Vector3.up);
   totalRotation += Time.deltaTime * degreesPerSecond;
}

```

In this case, the rotation of the door will take 2 seconds to reach 90 degrees.

And just a tip, setting the variables to `public` will allow you to edit them from the Unity editor. This means you can apply this same script to multiple objects, but change the values for each object without editing the script.

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


# Question
Title: Edges drop out when rendered at a long distance
I have this weird effect when rendering small objects at a long distance. I already tried using anisotropic filtering but maybe I am not doing it right.

Material script:

```
material Platform/Border
{
  technique
  {
    pass
    {
      ambient 0 1 0.824 1.0
      cull_hardware none
      cull_software none
      lighting on
      texture_unit
      {
        filtering anisotropic
        max_anisotropy 8
        texture white-pixel.png
      }
    }
  }
}

```

Screenshots:

How to solve this?

# Answer
> 3 votes
This will happen if you use textures for outlines instead of actual primitives (i.e. lines). You are fighting with twice the aliasing when you use textures to achieve this.

First the sample rate of filled primitives decreases with distance given perspective projection and second the effective sample neighborhood used for texture filtering becomes larger with distance. It can become so large, in fact, that a thin (i.e. single-texel wide) detail is completely lost despite filter interpolation.

The ideal solution would be to implement *bilateral* filtering for your textures (this usually gives better results than even SSAA or MSAA in this special case), but the far simpler solution is simply to use lines for the outline. Alternatively, you could use a technique I have outlined in an answer on Stack Overflow.

Now, since you're using Ogre, I have a feeling that none of the more sophisticated solutions I outlined are going to work for you. One last ditch effort would be to exaggerate the width of the border in your outline texture in lower mipmap levels (assuming Ogre gives you control over the mipmaps). Also make sure you use a `clamp to edge` address/wrap mode.

I should also point out that if Ogre lets you control mipmap LOD bias, you might try a negative bias for the outline texture.

---
Tags: 3d, rendering, ogre
---


# Question
Title: The View-Matrix and Alternative Calculations
I'm working on a radiosity processor in DirectX 9. The process requires that the camera be placed at the center of a mesh face and a 'screenshot' be taken facing 5 different directions...forward...up...down...left...right...

...The problem is that when the mesh face is facing up( look vector: 0, 1, 0 )...a view matrix cannot be determined using standard trigonometry functions:

```
Matrix4 LookAt( Vector3 eye, Vector3 target, Vector3 up )
    {
        // The "look-at" vector.
        Vector3 zaxis = normal(target - eye);
        // The "right" vector.
        Vector3 xaxis = normal(cross(up, zaxis));
        // The "up" vector.
        Vector3 yaxis = cross(zaxis, xaxis);
        // Create a 4x4 orientation matrix from the right, up, and at vectors
        Matrix4 orientation =
        {
            xaxis.x, yaxis.x, zaxis.x, 0,
            xaxis.y, yaxis.y, zaxis.y, 0,
            xaxis.z, yaxis.z, zaxis.z, 0,
            0,       0,       0,     1
        };

        // Create a 4x4 translation matrix by negating the eye position.

        Matrix4 translation =
        {
            1,      0,      0,     0,
            0,      1,      0,     0,
            0,      0,      1,     0,
            -eye.x, -eye.y, -eye.z,  1
        };
        // Combine the orientation and translation to compute the view matrix
        return ( translation * orientation );
    }

```

The above function comes from http://3dgep.com/?p=1700...

...Is there a mathematical approach to this problem?

# Answer
> 5 votes
You can check if `cross(up, zaxis)` is too close to zero (use an epsilon like 1e-4 or something like that), and switch to an alternative up-vector if so. For instance, if your usual up-vector is (0, 1, 0), you could switch to (1, 0, 0).

---
Tags: c++, directx, transformation
---


# Question
Title: How can I make a clickable menu in WP 7/8?
I'm trying to make a clickable menu for my XNA Windows Phone game. If the player makes a tap gesture on a button(rectangle), something will happen. For example, the game will start if you touch the START button. But I always have difficulties with collision detection. If the player touches a button, the collision is not always working. If the player touches the left border or the top of the button, nothing happens. But on the other hand, if the player touches the area next to the right side or next to the bottom of the button, the collision happens. I want that the collision just happens when the player touches the button, and not when the player touches the area next to it.

What is wrong? How can I solve the problem? Is there a better way to make a clickable menu?

```
while (TouchPanel.IsGestureAvailable)
        {
            GestureSample gs = TouchPanel.ReadGesture();
            switch (gs.GestureType)
            {
                case GestureType.Tap:
                     {
                    tapState = new Rectangle((int)gs.Position.X, (int)gs.Position.Y, 1, 1);
                    nextmenu = true;
                     }
                break;
            }

                if (nextmenu == true)
                {
                 if (buttonBounds.Intersects(tapState))
                {
                    jchangetomenu = true;
                }
                 nextmenu = false;
                }
        }

```

# Answer
See this related answer https://stackoverflow.com/questions/18168807/xna-hold-screen-to-move-object

Check collision with button here `case TouchLocationState.Pressed:`.Alson you can make rectangle to represent your button bound and check collision with it using http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.rectangle.contains.aspx Put your change menu state logic here `case TouchLocationState.Released:`.
> 0 votes

---
Tags: xna, c#, windows-phone-7
---


title: Animate Using setScale()

text:
# Question
Title: Animate Using setScale()
I want to animate my player from **bigger size to smaller size** and then **smaller size to bigger size** continuously. We can use **setScale()** method to re-size any sprite but is there any way to animate with it?

And one more thing, if I scale any sprite **after creating it's physics body**, the sprite is visually scaled but the physics body **does not** scaled.

So is there any optimum solution to animate the physics body from bigger to smaller and then smaller to bigger?

# Answer
> 3 votes
You have to use entity modifier for this purpose.

For example,

```
sprite.registerEntityModifier(new LoopEntityModifier(new SequenceEntityModifier(new ScaleModifier(1,1,1.5),new ScaleModifier(1,1.5,1))));

```

Above code can become useful to you. If you found any mistake then please make it correct because I don't check it.

And now turn for body, as per my suggestion you have to create different body each time to show scale up and down. You can write this code in managerUpdate method. One thing also you can check that change fixturedef of the body and try to create new body in that way also. Whatever choice you like.

# Answer
> -3 votes
`sprite.registerEntityModifier(new LoopEntityModifier(new SequenceEntityModifier(new ScaleModifier(1,1,(float)1.5),new ScaleModifier(1,(float)1.5,1))));`

---
Tags: android, andengine
---


title: What does Rectangle.Intersect means/do?

text:
# Question
Title: What does Rectangle.Intersect means/do?
Ok I have two rectangles one is the ball and other is the paddle.

```
1.    if(ball.rectangle.intersects(paddle.rectangle))
          y = -Math.Abs(y);

```

and

```
2.   if(paddle.rectangle.intersects(ball.rectangle))
        y = -Math.Abs(y);
       // y is y-axis of ball

```

are both of them same. I used the (1.) code and when my bouncing ball touches the paddle it reflects as I want it too but when I use the (2.) code my bouncing ball it sticks with the paddle for some milliseconds then bounces off as I want it too. I don't understand why they aren't the same. Can anybody tell me the difference between them?

# Answer
> 2 votes
These are exactly the same and should be executed the same. The intersects method only returns a bool when 2 rectangles intersect, it does nothing more.

If the result isn't the same, it might have something to do with your other code. Maybe you can post it?

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


title: Cartesian Coordinates & Layout

text:
# Question
Title: Cartesian Coordinates & Layout
The way cartesian coordinations are presented and used is kinda confusing.

When working with 2D the vertical axis is Y, though when working with 3D the vertical axis is Z and Y becomes the "depth" axis.

Basically I'm thinking the correct way, and best way would be to use the layout of axis.

Though Blender (3D modelling program) and other program, a lot games, present the axis in the "weird order" (my opinion)

Also if you read on Wikipedia about cartesian coordinates, your are presented with that layout of axis.

Wikipedia Cartesian Coordinates

Is there any specific or logical reason for this "flip" of axis?

# Answer
There is no 'flip' here; both coordinate systems are exactly the same. Instead, the two images have been created using two differently oriented cameras. Which direction is 'up' is not defined by the coordinate system, but by an arbitrary mental note you make.
> 2 votes

---
Tags: game-design, camera, coordinates, perspective
---


title: Port libgdx application to iOS

text:
# Question
Title: Port libgdx application to iOS
I made my game using libgdx which is a cross-platform framework which supports desktop, Android and html5 (using Google Web Toolkit). What could be a possible route to port my game to iOS?

# Answer
Now you can port your game to iOS. The steps to do this (as described here) are:

1. Make sure you have all prerequisits for libgdx development for iOS, except Xamarin.iOS/Monotouch!
2. Open Eclipse, and install the RoboVM plugin from here. This will install everything you need.
3. Get the libgdx source and import all projects into Eclipse.
4. Right click any of the xxx-robovm projects in Eclipse, select Run As, then iOS Device App, or iOS Simulator App.
5. See things running on your iOS simulator or device! (Note that you need to provision your device to be able to run anything on it, which costs you 90$/year. Thanks Apple!)

But there are some issues. Read all the information here.
> 5 votes

# Answer
Perhaps you could port to GWT and then use something like GWT on PhoneGap to get the app into iOS. (Hmm... I'm not sure if the GWT on PhoneGap link above is for running GWT on PhoneGap, or for porting PhoneGap apps to GWT?)

I have no experience with either of these steps, so I can't say what wouldn't work. But like a game of "telephone" I suspect each step will degrade the experience slightly, so the result may not be worthwhile.
> 1 votes

# Answer
The creator of libGDX, **Mario Zechner**, himself says in the following blog post that libGDX games require a MonoTouch license for running games written in libGDX to run on iOS! See First libGDX game on iOS and here are some, Screenshots of libGDX iOS Demos. Hope this helps :)
> 0 votes

---
Tags: ios, libgdx
---


# Question
Title: Make some black pixels transparent in Love2D
Is it possible to put a black opaque rectangle over my game screen and then change transparency on some pixels?

For example I have black rectangle on screen represented by 1

```
1111111111111111111111
1111111111111111111111
1111111111111111111111
1111111111111111111111
1111111111111111111111
1111111111111111111111
1111111111111111111111

```

and then I would like to make several pixels transparent represented by 0

```
1111111111111111111111
1111100000000000011111
1111111100000011111111
1111111111001111111111
1111111100000011111111
1111100000000000011111
1111111111111111111111

```

Would that be possible using blend modes?

P.S. I'm using version 0.8.0. of Love2D

# Answer
You want a **stencil**.

Stencils let you flexibly define regions that `love.graphics` operations won't affect.

Here's an example. It does this:

1. Draw some colourful circles.
2. Set an inverted stencil made of two triangles.
3. Draw a black rectangle over everything.

See how the black rectangle *doesn't actually* cover everything? It's cut out where the triangles were. That's the stencil.

Here's the code I for that:

```
love.graphics.setBackgroundColor(255,255,255)

function love.draw()
    local rect  = love.graphics.rectangle
    local circ  = love.graphics.circle
    local col   = love.graphics.setColor
    local poly  = love.graphics.polygon

    -- reset stencil
    love.graphics.setStencil(nil);
    -- draw some colorful circles
    col(255,0,0)
    circ("fill", 75,30, 20)
    col(0,0,255)
    circ("fill", 10,30, 30)
    col(255,0,255)
    circ("fill", 70,70, 20)
    col(255,255,0)
    circ("fill", 30,60, 30)

    -- set stencil to an hourglass shape
    love.graphics.setInvertedStencil(function()
        poly("fill", 10,10, 50,50, 90,10)
        poly("fill", 10,90, 50,50, 90,90)
    end)
    -- draw a black rectangle
    col(0,0,0)
    rect("fill", 0,0,100,100)
end

```
> 5 votes

---
Tags: transparency, love2d
---


title: What are 3D textures?

text:
# Question
Title: What are 3D textures?
Google has failed me, I could not find anything informative. So perhaps GameDev can :).

* What are 3D textures?
* When are they used?
* Performance costs?
* How are they stored?

I have many vague ideas, but no 'definitive' definition.

Any references to examples or tutorials is appreciated, especially in rendering particle systems via 3D textures.

# Answer
> 40 votes
3D texture works like regular texture. But it is truly 3D. 2D textures has UV coords, 3D has UVW (you had to use them propably). Texture coords are unit cube (0 - 1, 0 - 1, 0 - 1).

**Possible usage**:

* volumetric effects in games (fire, smoke, light rays, realistic fog)
* caching light for realtime global illumination (CryEngine for example)
* scientific (MRI, CT scans are saved into volumes)

**Performance**:
Same as regular texture - super fast (fastest memory access in gpu). Cached for threads and optimized for the situation when near threads (pixel shaders) are looking for near values.

Can be read as point or used linear sampling (native tri-linear interpolation. Eq bi-linear interpolation in 2D texture).

They are stored in memory like a array of 2D textures.

Mipmapping on 3D texture:

# Answer
> 15 votes
3D textures or 'Volume textures' are a series of normal textures arranged as slices, like a deck of cards. These are used in volumetric rendering which often takes real world data such as CT scans and then manipulates them. In games and graphics it's sometimes for volumetric effects like smoke where you trade the flexibility of a particles system for the fixed cost and easy (and easily parallelisable) calculation of a volume texture. It's really easy in a volume texture to find the nearest neighbours but this can be a problem is a more traditional particle system made up of loose points.

Also, some complex object benefit from using volume textures, such as grass:

Nvidia's smoke in a box is a great example:

http://www.youtube.com/watch?v=9AS4xV-CK14

Also, rendering light scattering is easier when you have a volume to render through

# Answer
> 7 votes
Apart from the existing answers, I like how 3D textures can be created procedurally as well (actually it makes more sense than a 2D procedural texture), like noise and fractals which will provide good and non-deformed texture details to any angle surfaces without having to select a projection model (UV, planar, cylindrical, spherical and so on).

Instead of sampling a bitmap layer in 3D space, you get a distinct value for each point in 3D space with a basic algorithm - which basically gives you infinite texture resolution and no problems with stretched textures on angled polygons. This is 3D "textures" or rather surface shading to me ^^

I'm actually pretty tired of all the bitmap texture snuff in game development, when I want to dirty down a space ship, I want to apply a few layers of noise formulas and not have to paint a limited resolution bitmap. An old 3D buff can dream, can't he ;)

*Right now, pre-baking these sweet oldschool 3D movie surface solutions into color, normal and specular UV bitmaps are about the only fun I get and it feels annoyingly limited. The demo scene (as always) tend to (pre)generate textures procedurally for real-time 3D but it feels hard to find good tools to support this workflow from design to run-time. Most game dev procedural approaches seems to be about mesh generation. Wonder how much the shader pipeline with the help of a depth map/deferred rendering could handle of oldschool 3D noise algos?*

> ...rather than trying to figure out how to map a texture image parametrically onto the surface of your shape, the volumetric nature of noise-based textures allows you simply to evaluate them at the (x, y, z) locations in your pixel shader. In this way, you are effectively carving your texture out of a solid material, which is often much more straightforward than trying to work out a reasonable undistorted parametric mapping.
>
> These sorts of volumetric noise-based procedural textures have long been mainstays of feature films, where shaders do not require real-time performance... all special-effects films today make heavy use of noise-based procedural shaders... is highly dependent on the extensive use of the noise function within pixel shaders written in languages such as Pixar's RenderMan. With a good implementation of the noise function available for real-time use in GPUs, I look forward to seeing some of the exciting visual ideas from feature films incorporated into the next generation of interactive entertainment on the desktop and the console. http://http.developer.nvidia.com/GPUGems/gpugems\_ch05.html

# Answer
> 0 votes
3D texture patterns are applied to voxels of a volumetric body very much the same way like 2D texture patterns are applied to the pixels of a 2D polygon. Here is an example of a 3D volumetric texture in JavaScript (requires WebGL):

http://kirox.de/test/Surface.html

press \[v\], rotate the body and change the gradient of the generated texture with the mouse wheel

---
Tags: 3d, textures
---


# Question
Title: What is the logic behind a 3D Projection 'Camera Perspective'?
Suppose I had a 3D Cube on a 2D plane (screen). And I wanted to use the keypad to move and rotate it.

Without referring to a 3D Game Engine that could do this for me can you explain me the logic or link me to a tutorial on how to rotate the cube or *change the camera view?*

I tried to look online for a tutorial but its hard to exactly determine what is happening and its relevance to my scenario.

# Answer
I'm assuming you know how basic matrix math works, so I'm not going to cover that in my answer.

What you eventually want to do is transform the vertices of the object you want to render from the virtual 3D world to the "real" 2D world (your monitor screen). You do that by multiplying the vertices of the object with a camera matrix (some people may use other terms for this, but it all comes down to basically the same thing). This camera matrix consists of two parts: an external (extrinsic) part and an internal (intrinsic) part.

The extrinsic part is a matrix that transforms the vertex from a 3D world coordinate system to a 3D camera coordinate system. Think this as positioning the camera inside your 3D world. Before the the transformation the vertex is viewed from the origin of the 3D world and after the transformation the vertex is viewed from the origin of the camera. So this is basically part of the answer to your question. If you want to move the camera, you manipulate the extrinsic parameter of the camera matrix (I will come back to this later).

The intrinsic part of the camera matrix is a matrix that transforms the camera coordinate system to an image coordinate system. So this is where the perspective projection takes place.

**View Matrix**

The extrinsic part of the camera matrix is often called the View matrix (World and Model matrices are related, but are not part of the view matrix). The view matrix is a 4X4 matrix that consists of a 3X3 rotation matrix and a 1x4 translation matrix (as seen below). The rotation matrix determines the orientation of the camera and the translation of the matrix describes the origin of the camera (so this is the camera's position in the virtual 3D world).

**Projection Matrix**

The intrincis part of the camera matrix is often called the Projection matrix. This is the matrix that does the actual projection from a 3D coordinate system to a 2D coordinate system. It projects everything in the camera's view frustum to a 2D plane (your monitor).

Now the perspective transformation is defined as follows:

Where: Xim and Yim are your screen coordinates, Fx and Fy define the aspect ratio, S is a skew parameter and Xo and Yo define the focal length (please correct me if I'm wrong about this, my knowledge is kind of rusty for these parameters).

**Vertex to screen**

So in the end, if you want to transform a vertex coordinate to a screen coordinate you will end up with this:

So, in the end if you want to rotate and move your camera, you need to need to modify the camera's View matrix.

P.S.: From a coding perspective: if you want to know how to construct the View matrix I refer you to this site, which does an excellent job of explaining how to create a LookAt matrix using OpenGL and C++.
> 5 votes

---
Tags: 3d, game-design, architecture, graphics, perspective
---


# Question
Title: How to handle player input in online game with ping jitter?
I'm currently working on an online game and basing my networking architecture around this Source Multiplayer Networking article. However, I'm a little stuck on how the user input works. The article describes that a snapshot of the keyboard/mouse state is sent from the client at the same tick rate the server is running. I am doing this in my game, which seems to me working pretty good, but the simulation on the server is slightly different then the client prediction resulting in the clients player eventually becoming out of sync with the server. I believe this discrepancy is a result of ping jitter.

For example, if the client is sending input every 25ms, theoretically if the server is receiving input every 25ms it will have an identical simulation. However, with any jitter, the server might not receive any input for 30ms for example. This means it will not be able to process the input until the next tick because it didn't arrive on time, and the entity on the server will become out of sync with the client eventually.

What are some methods for solving this issue? Maybe I'm missing something in the Source Multiplayer networking example. If anyone could explain better or provide any advice it would be much appreciated.

Thanks

# Answer
The general gist is that you have two concepts of "state".

* Local state (your client)
* Ghost state (the server)

You take input from your client, and update your local client state (and send this to the server). You then "predict" what happens to everyone else, assuming some amount of spatial consistency to last frame.

When you get information from the server, you update the "ghost" state. This is effectively the authoritative state of the world according to the server (n ms ago)

What happens next is that you end up always lerping your "local" state towards the "ghost" state. If the differences are beyond a certain threshold you can snap players into position, but in most cases the visual discrepancy to their actual position will be acceptable. Whether you perform authoritative actions against the local, or ghost state is up to you, but these days I *think* things such as hit detection are done on ghost position.
> 2 votes

# Answer
I ended up solving this based on a few things:

Firstly, I made the mistake of predicting input on the client based directly off the keyboard. I changed it so the client predicts movement based off of keyboard states it sends to the server (every 25ms). This gives it a much more accurate prediction.

Secondly, I previously had the server simulating players based off the latest input received. I've implemented a queue of input so the server will simulate all input that hasn't been processed yet, instead of only simulating the latest input snapshot.

As of right now, the client prediction is pixel perfect with the server simulation which is what I was aiming for.

Thanks to anyone who provided input/suggestions.
> 0 votes

---
Tags: networking, online, latency
---


# Question
Title: Limiting a player's movement to the screen's dimensions
I have a player, that I can control using WASD. And I don't want him to leave the screen.

So I've tried the following:

```
if (player1.getX()+5 < 974 && player1.getX()-5 > 0) {
    if(Keyboard.isKeyDown(Input.KEY_D)) {
        player1.addForce(5, "d");
    }
    if(Keyboard.isKeyDown(Input.KEY_A)) {
        player1.addForce(5, "a");
    }
    if(Keyboard.isKeyDown(Input.KEY_W)) {
        player1.addForce(5, "w");
    }
    if(Keyboard.isKeyDown(Input.KEY_S)) {
        player1.addForce(5, "s");
    }
} else if(player1.getX() >= 974) {
    player1.addForce(5, "a");
} else if(player1.getX() <= 0) {
    player1.addForce(5, "d");
}

```

It actually works, but the player gets stuck at the edge of screen, and can't move anymore. Any ideas why? Or rather, how do I make a proper collision detection?

NB: 1024 is the width of screen. And my player is 50 pixels wide, thus the 974. I am only working with X at the momemnt, to try getting it to work.

# Answer
What that code is doing is limiting motion to only if you're inside the screen. What you should instead do is something like this:

```
//control code here

if(player.getx() > 1024){
    player.setx(1024);
}else if(player.getx() < 0){
    player.setx(0);
}

```

that way if the player exceeds the bounds of the screen the position will be set back to the bounds.
> 6 votes

# Answer
Try this:

```
 if(player1.getX()+5 < 1024 && player1.getX()-5 > 0) {

        //Player 1
        if(Keyboard.isKeyDown(Input.KEY_D)) {
            player1.addForce(5, "d");
        }
        if(Keyboard.isKeyDown(Input.KEY_A)) {
            player1.addForce(5, "a");
        }
        if(Keyboard.isKeyDown(Input.KEY_W)) {
            player1.addForce(5, "w");
        }
        if(Keyboard.isKeyDown(Input.KEY_S)) {
            player1.addForce(5, "s");
        }
    } else if(player1.xlocation>=1024) {
        player1.addForce(5,"a");
    } else if(player1.xlocation<=0) {
        player1.addForce(5,"d");
    }

```
> 1 votes

# Answer
Compute for the future position first before updating the position of your player:

```
if( RIGHT is pressed )
{
    var futurePositionX = currentPositionX + increment;

    if( futurePositionX < rightScreenBound )
    {
        currentPositionX = futurePostionX;
    }
    else
    {
        // if futureposition will exceed bound, set position to bound
        // (rightScreenBound is the rightmost possible position)
        currentPositionX = rightScreenBound;
    }
}

```
> 1 votes

# Answer
Flickering behavior is correct. It is like throwing ball at the wall and when it bounces away, you punch it back to the wall. It is because you are setting forces instead of positions.

First, you must decide, wheter you want to control the position, or force (speed = derivative of position). If you want to set forces, then:

* you can not simply add force when button is down. It may grow to infinity.
* when object reaches the border, set force to zero! don't add force in another direction!
> 0 votes

# Answer
The reason it's flickering is probably because you update the possition, then update the image then check for collision then update the possition again and then update the image again.

Instead try to put the collision detection before you update the image.
> -1 votes

---
Tags: 2d, java, lwjgl, slick, screen
---


title: Delaunay triangulation. Where to start?

text:
# Question
Title: Delaunay triangulation. Where to start?
I'm trying to learn procedural generation technique's. Specifically for dungeons. I started off with a 2D array and I generate my rooms fine. Each room contains wall tiles as seen in the screenshot below.

Right now I use A\* to link the rooms together. But this has some paths go straight through other rooms or around rooms. Having done some googling I found this demo which game me the idea of using Delaunay Triangulation to properly connect the rooms without going through already existing connections/rooms.

But how to apply it to my 2D array setup? My initial thinking is that I should think out side of the box (2d array haha) and grab my rooms and create a complete graph from this and then apply the Delaunay Triangulation.

I've never done anything with graphs before. So what I would to know is a) is my thinking correct in creating the graph with all the rooms linked and then to apply the triangulation and b) where should i start?

\[small edit\]after some more looking around stackoverflow i found this post explaining Graphs more in depth. https://stackoverflow.com/questions/15306040/generate-an-adjacency-matrix-for-a-weighted-graph

# Answer
> 10 votes
That is a neat demo. The best reference for Delaunay triangulations and Voronoi diagrams that I've found is Jonathan Shewchuk's book and **lecture notes**. The book is significantly more advanced than the lecture notes, and talks more about *mesh refinement*. I suggest you start with the lecture notes.

Do you need to go to grad school to generate a Delaunay triangulation? Heck no! A delaunay triangulation is just the unique triangulation such that each triangle's circumcircle (scroll down to Shewchuk's answer) encloses only the 3 vertices of each triangle, and nothing more.

(Picture from Shewchuk's lecture notes, linked above)

# Algorithms

A paper outlining Two Algorithms for Constructing a Delaunay Triangulation is a good place to start.

The main way you'll see people talk about is first creating the Voronoi diagram.

## Fortune's algorithm

I can only give you a few pointers here, having started working with Fortune's algorithm but abandoning the project because Fortune's code is extremely difficult to grok. There is a javascript implementation here.

A couple of other Fortune resources:

I know I posted a lot of links here, **but my advice is to avoid Fortune's algorithm**. An easier way to do it is to use flipping edges, described below.

## Flipping edges

A **much easier** way to do it is called Flipping Edges. What you do is start with **any triangulation**, then simply "flip edges" so every triangle becomes "Delaunay" (circumcircle of each triangle contains no other points other than its own 3 vertices). Once all the tris are Delaunay, you have the Delaunay triangulation.

---
Tags: path-finding, procedural-generation, graph, triangulation
---


# Question
Title: In Corona SDK, how do you extract the x1, y1, x2, and y2 coordinates from a line display object?
I used this command to create a line:

```
local myLine = display.newLine( 0,-110, 27,-35 )

```

How can I get the coordinates from `myLine`? I've looked here and here but the closest thing I could find is `myLine.x` and `myLine.y`, which appear to be `x1` and `y1` (not sure), but I can't figure out how to get `x2` and `y2`.

I want this information in order to detect if two lines intersect on the screen.

# Answer
I have never used Corona before but reading through the documentation I believe you can't easily retrieve these coordinates back from the generated display object. From what I read, `display.newLine` returns a vector display object to which you can `append` as many vertices as you want, but there's no way to access those values.

I guess you could use `line.contentBounds` to get back the size of the rectangle that encompasses the line, but this wouldn't tell you which diagonal to pick.

What I would suggest is to encapsulate this behavior in your own separate `Line` class (if that's possible in Corona) which stores the vertices, provides access to them, and generates the display object for you. Since I'm not familiar with Corona I'll use another language, but try to think of it as pseudocode.

I hope you can understand the general idea and can adapt it to some Corona *equivalent*. Let me know if there's something you don't understand:

```
class Line
{
     public Line(int x1, int y1, int x2, int y2)
     {
         this.x1 = x1;
         this.y1 = y1;
         this.x2 = x2;
         this.y2 = y2;
     }

     public int x1, y1, x2, y2;

     public DisplayObject GetDisplayObject()
     {
         return display.newLine(x1, y1, x2, y2);
     }

     public bool Intersects(Line other)
     {
         // Line segment intersection algorithm
     }
}

```
> 1 votes

# Answer
A simpler solution could be to add yourself the properties to your line

```
local line = display.newLine( x1,y1, x2,y2 )
line.x1 = x1
line.x2 = x2
line.y1 = y1
line.y2 = y2

```

then later you can grab `line.x2, line.y2`
> 0 votes

---
Tags: corona-sdk
---


# Question
Title: Box2D Bicycle Wheels Motor Problem - Flash 2.1a
I have made a bicycle with Box2D using several polygons for the frame at different angles connected using weld joints, and I have revolute joints on the wheels with a motor.

I have made some basic terrain (straight ground and a small ramp) and added keyboard input to control the bicycle with torque to balance it. All of this is done in with Box2D's Debug Draw.

When the bicycle is on its back wheel but diagonally forward (kinda like this position -\> /) the motors just cause it go spinning backwards over when in reality it should either stay on its back wheel or go down onto both wheels.

Here's my code the revolute joints:

```
            //Front Wheel Joint

        var frontWheelJointDef:b2RevoluteJointDef = new b2RevoluteJointDef();
        frontWheelJointDef.Initialize(frontWheelBody, secondFrameBody, frontWheelBody.GetWorldCenter());
        frontWheelJointDef.enableMotor=true;
        frontWheelJointDef.maxMotorTorque=10000;
        frontWheelJoint = _world.CreateJoint(frontWheelJointDef) as b2RevoluteJoint;

        //Rear Wheel Joint

        var rearWheelJointDef:b2RevoluteJointDef = new b2RevoluteJointDef();
        rearWheelJointDef.Initialize(rearWheelBody, firstFrameBody, rearWheelBody.GetWorldCenter());
        rearWheelJointDef.enableMotor=true;
        rearWheelJointDef.maxMotorTorque=10000;
        rearWheelJoint = _world.CreateJoint(rearWheelJointDef) as b2RevoluteJoint;

```

And here's the relevant part of my update function:

```
            // up and down control wheels motor
        if (up) {
            motorSpeed-=0.5;
        }
        if (down) {
            motorSpeed += 0.5;
        }
        // left and right control cart torque
        if (left) {
            middleCentreFrameBody.ApplyTorque( -3);
            gearBody.ApplyTorque( -3);
            firstFrameBody.ApplyTorque( -3);
            secondFrameBody.ApplyTorque( -3);
            rearWheelToChainBody.ApplyTorque( -3);
            chainToFrontFrameBody.ApplyTorque( -3);
            topMiddleFrameBody.ApplyTorque( -3);
        }
        if (right) {
            middleCentreFrameBody.ApplyTorque( 3);
            gearBody.ApplyTorque( 3);
            firstFrameBody.ApplyTorque( 3);
            secondFrameBody.ApplyTorque( 3);
            rearWheelToChainBody.ApplyTorque( 3);
            chainToFrontFrameBody.ApplyTorque( 3);
            topMiddleFrameBody.ApplyTorque( 3);
        }
        // motor friction
        motorSpeed*=0.99;
        // motor max speed
        if (motorSpeed>100) {
            motorSpeed=100;
        }

        rearWheelJoint.SetMotorSpeed(motorSpeed);
        frontWheelJoint.SetMotorSpeed(motorSpeed);

```

Any ideas what might be causing this?

Thanks

# Answer
> 1 votes
maxMotorTorque(10000) seems too much for me.

I don't think giving torque to each part separately will work.why don't you make one bike body and create parts as fixtures of it. Then give torque to the bike body.

---
Tags: flash, box2d
---


# Question
Title: Colouring greyscale images/sprites for HTML canvas
What is the best method to colour in sprites at runtime using the canvas element and javascript? I know there are various blending modes using globalCompositeOperation, but I don't know how best to utilise this.

I'll break my question down into the following:

* Is there an optimum way to export greyscale images so they can be easily re-coloured later? (At the moment, the images are created with colour in Photoshop or a similar package and then turned into a greyscale and exported from there before I even touch them)
* With these greyscale images in place, what method makes colouring them with any colour possible? (They must retain the shading etc)

I've tagged this with HTML5 and Javascript, but any advise from other platforms would be helpful.

Edit: Here's an example greyscale output of the image on the left. I want to be able to restore it to the same colour, but also be able to blend it with other colours for different shades of skin.

# Answer
> 3 votes
There are several ways to achieve what you want. The easiest way would be to paint a colorized rectangle above your grayscale image and use one of the following blend-modes: `multiply`, `screen` or `overlay` (which is a combination of screen and multiply).

Here's how these blend-modes look (red rectangle over grayscale image, using multiply, screen and overlay):

The blend modes don't seem to be supported in all browsers, so maybe you'd have to implement them yourself. This should be quite straight-forward by iterating through all pixels and mix them with your desired color. Here's a list of formulas for the most common blend-modes.

# Answer
> 8 votes
## Getting the raw pixel data

You can get the raw pixel data with the function `context.getImageData(x, y, width, height)`. The return value is an ImageData structure. This structure will have a field `data` which is an UInt8ClampedArray where each pixel is represented by four values between 0 and 255 (red, green, blue, alpha).

## Converting an image to greyscale

In order to reduce three color channels (R, G, B) to one, there are different approaches. Which one is the best depends on your use-case.

* Using the highest value (intensity)
* Using the average between the highest and the lowes value (luminosity)
* Using the average of all three (brightness)
* A color-psychological approach: For the human eye, yellow (255, 255, 0) seems brighter than blue (0, 0, 255) and green (0, 255, 0) seems brighter than red (255, 0, 0). You could experiment with a conversion-function which accounts for this.

## Converting greyscale back to color

Depending on which algorithm you decided to use, you will now have a greyscale value between 0 and 255 for each pixel. To converte these to RGB-values depending on your target-colors RGB, there are also different methods.

* Multiplication: A greyscale value of 0 is black, a greyscale value of 255 is equal to your target-color
* Overlay: A greyscale value of 0 is black, a value of 127 is your target-color and a value of 255 is white
* Screen: A greyscale value of 0 is your target-color, a greyscale value of 255 is white

The values in between are interpolated linearly. The best method depends on the effect you are aiming for, what algorihm you've chosen for greyscaling and what your target-color is.

## Writing the raw pixel data back to the canvas

To copy the imagedata structure with the modified array back to the canvas, you can use `context.putImageData(imagedata, x, y)`.

## Some performance considerations

Keep in mind that working with raw image-data is an expensive operation. Usually all canvas operations can be done on the GPU. But in this case the canvas texture must be serialized, copied to RAM, processed by the CPU and then copied back to the video memory. This is quite slow. Usually too slow to do it with everything on the screen and still keep a steady framerate. So when you intend to draw the resulting colored sprite more than once, you should buffer the result of the recoloring on an invisible background-canvas and use this as an image source for `context.drawImage` when the recolored sprite needs to be drawn again.

# Answer
> 3 votes
Adding to what @Philipp said (especially the "caching blended result"). You can reverse calculate the second image from the `blend(grey,????) = colored` equation for the multiply,overlay and screen functions. The problem is that the range of the `?????` image may be out of the range of `0-255`. So you might need to save them as a different format or encode something like a signed int into the 4 bytes of the RGBA values in one pixel for each channel.

As others said you can also use other color-models for help. HSV is the one that appears to be the obvious choice and it will look like this:

But as you can see the separated saturation and hue image still contains a good amount of the shading information, so a color model like YUV might seem more appropriate. It would look like this:

The problem here is that the inter-relationship that the RGB values in your blending source have with the final image might not always be so apparent.

Using just the raw components of these color models though has the issue of not being able to make image darker whatsoever. So I'd say use the reverse blending modes or combine the other color-spaces with the blending modes to get it done.

**Edit**: to visualize what I meant with the multiplication look at these examples:

The top 2 use multiplication with the regular color spectrum (0-255 mapped to 0-1), you can see that the image can only be made darker, making the red channel bright enough for a natural skin tone is basically impossible within the default spectrum. However if you look at the lower example of brightening it, then you can see that if you multiply it with values over 1 you can once again recreate the original result

Btw. if you're worried about the underwear being colored too, you need to mask it out (just use the grey base image where you don't want any coloration):

To calculate the scale value lets take for example the gray scale has the color \[120 , 120, 120\] at one point and the colored image has the color \[152 107 74\] at the same spot then the scale factors would be s\_red = 152/120 = 1.27 , s\_green = 107/120 = 0.892 and s\_blue = 74/120 = 0.617, so \[1.27 0.892 0.617\].

You could reasonably map the re-color RGB value from \[0-255\] to \[0-2\] or something like that to easier use existing structures as well as limit the brightening to reasonable values. So your setup would look something like this (with the masking applied of course):

Don't forget to clamp your resulting image to \[0-255\] though.

---
Tags: javascript, html5
---


# Question
Title: Rectangle collision doesn't work on WP 8
Collision detection is not working correctly when my 64x64 pixel block touches a bigger block. The big(rect2big) block measures 128x128 pixel. The falling block should change it's color to black when it touches another block, but that's not working if it touches the big block. The falling block changes it's color far too late when it touches the big block. You can see that in this video: http://www.vidup.de/v/QFeTK/

What is wrong? Why is collision detection not working correctly when the falling block touches the big block?

```
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    Texture2D rect, rectbig;
    Rectangle rect1, rect2, rect2big;
    bool rectcollision = false;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        TargetElapsedTime = TimeSpan.FromTicks(333333);
        InactiveSleepTime = TimeSpan.FromSeconds(1);
        this.graphics.PreferredBackBufferWidth = 480;
        this.graphics.PreferredBackBufferHeight = 800;
        graphics.IsFullScreen = true;
    }

    protected override void Initialize()
    {
        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        rect = Content.Load<Texture2D>("block64");
        rectbig = Content.Load<Texture2D>("block128");
        rect1 = new Rectangle(200, 0, rect.Width, rect.Height);
        rect2 = new Rectangle(200, 200, rect.Width, rect.Height);
        rect2big = new Rectangle(200, 400, rectbig.Width, rectbig.Height);
    }

    protected override void Update(GameTime gameTime)
    {
        rect1 = new Rectangle(rect1.X, (int)(rect1.Y+1.0f), rect.Width, rect.Height);

        if (rect1.Intersects(rect2) || rect1.Intersects(rect2big))
        {
            rectcollision = true;
        }
        else
            rectcollision = false;

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
        spriteBatch.Draw(rect, rect2, null, Color.White, 0, new Vector2(rect.Width / 2, rect.Height / 2), SpriteEffects.None, 1);
        spriteBatch.Draw(rectbig, rect2big, null, Color.White, 0, new Vector2(rectbig.Width / 2, rectbig.Height / 2), SpriteEffects.None, 1);
        if (rectcollision == true)
          spriteBatch.Draw(rect, rect1, null, Color.Black, 0, new Vector2(rect.Width / 2, rect.Height / 2), SpriteEffects.None, 1);
        else
            spriteBatch.Draw(rect, rect1, null, Color.White, 0, new Vector2(rect.Width / 2, rect.Height / 2), SpriteEffects.None, 1);
        spriteBatch.End();
        base.Draw(gameTime);
    }
}

```

# Answer
> 0 votes
The rectangles are actually colliding properly but you are drawing them at a location other than where you they actually are. If you change the origin parameter in your draw call to be Vector2.Zero your collision code should work as expected. By specifying a non-zero origin you are drawing your rectangles at an offset location from the position where you are performing your collision detection.

---
Tags: xna, c#, collision-detection, windows-phone-8
---


title: Skybox with deferred shading

text:
# Question
Title: Skybox with deferred shading
I've looked at this technique, but it strongly sounds like he has to do some ugly hacks involving branching in his lighting shaders just to correctly draw a skybox. This seem awfully wasteful.

How can I most efficiently implement a skybox with a renderer that uses deferred shading?

# Answer
> 7 votes
The skybox should be drawn after all lighting has been done. It's done exactly the same way as in a forward-shaded renderer; it shouldn't go into the G-buffer at all, and the lighting shaders shouldn't need to know anything about it.

I don't think there's any need to fiddle around with the viewport depth range or stencil either. If you use a projection matrix with an infinite far plane, you can just draw it after everything else, using a vertex shader that sets w = 0 before transforming by the view and projection matrices.

Alternatively, if it's just a texture and you don't need to draw actual geometry, you could do it as a postprocess - a full-screen pass, where the vertex shader sets z = w = 1 to draw the full-screen pass at the far plane. Here's the skybox code I use, which takes this approach:

```
TextureCube<float3> g_texSkybox;

void vsMain(in Vertex i_vtx, out float3 o_vecView : VIEW, out float4 o_posClip : SV_Position)
{
    // Set z = 1 to draw skybox at the back of the depth range
    o_posClip = float4(i_vtx.m_pos.xy, 1.0, 1.0);

    float4 vecView = mul(o_posClip, g_matClipToWorldNoTranslation);
    o_vecView = vecView.xyz / vecView.w;
}

float3 psMain(in float3 i_vecView : VIEW) : SV_Target
{
    return g_texSkybox.Sample(g_ssTrilinearRepeat, i_vecView);
}

```

Here `g_matClipToWorldNoTranslation` is the inverse projection matrix, multiplied by the inverse of the rotation part of the view matrix. It converts a point in clip space to the corresponding direction in world space.

---
Tags: deferred-rendering
---


title: When should I start designing levels?

text:
# Question
Title: When should I start designing levels?
I'm working on a puzzle game. I thought of a core mechanic, implemented it, tuned it and now I have something I'm happy with.

I'd really like to build a few levels before I work on stuff like UI and sound, however, I'm not sure if I should sort out some other things first:

**Story**

The game has a story (as opposed to many other puzzle games). The thing is, I just have a basic idea of what it should be, nothing detailed and nothing's written down.

Should I work out the story in some detail first? Figure out what arc I want to tell in the first 5 levels before I build them? Or is the story somewhat orthogonal in puzzle games and I can just go ahead and build some levels?

**Elements**

I've thought of a rather minimal set of gameplay elements, i.e. objects you can interact with, to evaluate the core mechanic.

I'd really like to keep things minimal and see how far I get with just those, but is that sane? Should I think long and hard about what elements I need upfront or should I add them when I feel that something's missing in a level I'm building?

**Bottom line: What should I do before designing the first few levels?**

# Answer
> 13 votes
**As soon as possible.** Making levels will not only give you much needed practice at making levels, it will give you a good idea of if/how your game play mechanic might need further changing.

A rough storyline and the core mechanics implemented should be all you need to begin making your levels. Creating the levels will be a great interactive way to further develop the story and learn what you want from the levels.

Typically, when creating levels, designers will start somewhere in the middle. You don't want the rough "still learning" levels to be the first thing the player sees, nor do you want it to be the last thing the player sees. So your rough storyline should be somewhere in the middle of your story. Create the levels for that part first, then expand out from there.

# Answer
> 2 votes
I recall Extra Credits covering some of this in an episode on indie games.

I'm not sure if I'd agree that you should start on levels as soon as possible. Maybe a core few - what you feel are going to be your most fun levels. But as long as you feel you can vary your puzzles in enough imaginative ways, I'd say it's not a bad thing to have 70% of your levels un-made some time into development.

The obvious issue you're trying to avoid (and nevertheless, will fall into by definition of "iterative process") is that the work you do on levels will need to be re-done when your mechanics change. If you have a core few levels, that's not a big task. If you have 90% of your levels done when you realize your character doesn't jump high enough, then you've got a lot of work ahead. To try to put it simply, game design is an iterative process that can take a long time to "find the fun". Once you have found the fun, you can being the arduous task of nailing the details in place, and making a suite of levels that make use of the mechanics.

Minimal gameplay elements sounds like a great idea - simplicity makes these things very easy to understand. However, around the time that testers would begin to get bored, you should probably think about "what interesting twist might breathe new life into this?"

It's hard for me to give much advice on the story without knowing what it is, but I will say you should try to be careful about letting it influence your game mechanics too much. The end goal, easier said than done, is story elements that fit well with their accompanied twist to the gameplay (you found a lost, distressed girl - maybe the two of you can work together through the next 18 puzzles to find your way home!) If that becomes too difficult of a goal, I don't think too many people would blame you for amounting your story to simple cutscenes between level-blocks.

---
Tags: game-design, level-design, process
---


# Question
Title: List of 2d action games with level editors
Action game level design is hard. If you want to hone your skills at designing action game levels, the problem is that first of all you have to make a good game, with good controls, interesting enemies, not to mention all the more basic code like collision, rendering, and of course the level editor (okay, so you could use an engine for a lot of that, but it's still a lot of work). Even once you have that, if your game isn't any good, that'll hinder any potential practice you might get from designing levels.

So I'm looking for **2d action games with level editors**. In addition to reducing your work load and allowing you to focus on level design, having a complete game means that you can play the professionally-made levels first and have something to compare your work to.

Personally I'm thinking of sidescrolling action/platformers, but **2d action includes any 2d game that is primarily execution-based**, ie reflexes and knowledge of the controls. So, Super Mario Bros. counts as 2d action in this instance.

My own examples are on the PC, but console games are fine too (although I think PC games usually have better level editors, maybe that's changing though).

PS: I hope this question is acceptable, even though there's obviously no single right answer. I noticed there's no "big-list" tag here, but I've seen questions like this on other SE sites, and it'll be plenty useful to future readers, which is part of the point of SE questions.

# Answer
> 1 votes
Well, since I'm not one of the more strict members of SE, I guess I'll give my take. A few games I know of:

* Braid - Has an in-game level editor
* Super Meat Boy - comes with Steam version
* Unity3D - Much more involved, but more flexible; there are doubtless some scripts you can use to put placeholder artwork in a 2D-movable world (and the physics can be constrained to two dimensions as well)
* Stealth Inc., AKA Stealth B\_*_*\__d: Have not played this one, but I can see it includes a level editor.
* Aquaria - Somewhat old by now. This game is an "Ecco the Dolphin"-type exploration game, not a platformer. Still, it has its fast-paced action moments.

The trend I notice is that they're often available for newer indie games, many of which (even the unpopular ones) should not be ignored.

# Answer
> 0 votes
Here are my own contributions.

**Super Mario World** has a fully graphical level editor called Lunar Magic, which I've never used, but it's very popular. You'll have to download a ROM and an Emulator, I think Lunar Magic outputs patches for the ROM.
*Platform: Windows*
*Free*

**Super Metroid** has a similar level editor called SMILE, which I've also never used. This one is less well-known and I'm not sure if it's as stable or functional.
*Platform: Windows*
*Free*

**Knytt Stories** is a free Windows platformer that comes with a fully graphical level editor. The game tends to be more exploration driven than platforming and action, but I've seen pretty good action platforming levels made for it. The level editor is great as long as you don't need to do any complex scripting. Support community is still very much alive on the forums.
*Platform: Windows*
*Free*

---
Tags: 2d, level-design, platformer
---


# Question
Title: Will there be any more books in the Game Programming Gems series?
It's been more than three years now that the last Game Programming Gems book was published. The official website isn't updated anymore, and this page of Mark DeLoura's website seems to imply that the series is over.

Was there ever an official statement about this? Was number 8 the last book?

The Game Programming Gems were one of the most (if not *the* most) important resource for me and probably thousands of developers around the globe, did the Internet kill them?

# Answer
> 23 votes
Hey so I know this is a month late response, but I thought you'd be interested in an answer that's more than "I don't know." or "maybe."

The comments on this post made me think to go to the source, so I sent an email to their info email and this the response I got (I guess I could take a screen shot as proof if needed; my inquiry email is first):

> Hello,
>
> I'm wondering if there will be a Game Programming Gems 9.
>
> Thanks a lot,
>
> Valencia

And this is the response I received:

> Unfortunately, no. The later Gems books didn’t sell well enough to warrant a new edition. I’m so sorry.

# Answer
> 21 votes
First of all, your hard data and facts. All the game programming gems sold fairly well, each ranking around the 200k mark on Amazon bestsellers list.

* Gems1: 198,126
* Gems2: 209,933
* Gems6: 200,574
* Gems8: 202,163

So based on that data I wouldn't say lack of sales is a good reason to stop.

But what about the content. "Game Programming Gems" was like a really fat magazine that came out every couple of years and costed $60-$80. After they covered the basic topics that everyone can understand in the first couple of books (quaternions & slerp, basic AI architecture), the articles seemed to get more and more advanced. Just look at a couple of title from the TOC of GPG 1:

Gems 1:

* 1.1 Object-Oriented Programming
* 2.0 Predictable Random Numbers
* 3.1 A Finite-State Machine Class
* 3.2 Game Trees
* 3.3 A\* for path finding

Gems 3:

* 3.4 Terrain Analysis in an RTS - the hidden giant
* 4.4 Fast and Simple Occlusion culling
* 6.6 Stochastic Synthesis of Complex sounds

Gems 4:

* 2.4 Nonuniform Sprites
* 3.6 Interactive Water Surfaces
* 5.9 Fast Sepia Tone Conversion
* 5.12 Hardware skinning with quaternions

Gems 8:

* 1.3 Multi-Resolution Deferred Shading
* 2.5 Improved Numerical Integration with Analytical Techniques
* 3.5 Applying Control Theory to Game AI and Physics

So you can see, as the series goes on, 2 things happen:

* The topics get more advanced, which means the articles take more effort to write, *and* the book will no longer appeals as much to total beginners
* The topics get more narrow and specific, because they are so advanced, which means you'd probably find a smaller proportion of the later books in the series useful, unless you have **really wide** interests (and abilities).

So although I think that shouldn't PREVENT additional installments into the series, I do think that in a way the series raises its own bar higher and higher all the time (both barrier to write an article, and barrier to read/understand an article).

In conclusion, I dunno. You'd have to ask Mark DeLoura.

---
Tags: software-engineering, books
---


# Question
Title: How should I handle the relationship between my Player and keyboard input classes?
Just a quick one really, as I can't find anything definative.

Started developing in Java, to learn and take on a bit of Game Dev. Have a PHP background, and I'm a massive sucker for best practices, etc.

Basically in my `Game::update()` method I can handle keyboard input and move the `Player`, this is what I want to avoid.

So should my `Keyboard` class have a dependancy of `Player`, or the other way around? Also would the `Keyboard` class handle the management of `Player` states or would the `Player` class handle that itself.

OR...

Should I look into introducing an Event System to the Game Engine?

This is a very broad question and down to opinion. I'd just rather do things the right way, than end up with a steaming pile of mess.

# Answer
I like to use a callback based input manager. The `Player` class calls the static `register` method of the `input manager` with the input to register (either some hard coded values like `W` or an alias like `Forward`) and a method to call back when the event happens.

In Java this will probably be programmed with an anonymous overloaded object of a callback class, or a lambda function.

This has the benefit of being a very flexible system, as the player does not control itself but rather is controlled by the input.
> 3 votes

# Answer
This is entirely subjective to the design requirements of your game but, generally speaking, usually most systems use an event-based system where objects register for events. It allows for a pretty flexible system where you can design anything from HID input to timers to trigger events.

If you would like to see a pretty strong example of how this can be done in a managed language, check out the source code for the Delta Engine. It's in c# but c# is incredibly easy to interpret in a java sense.

Delta Engine Source code
> 1 votes

# Answer
I think that the Player should have a dependency on keyboard. Image some of the meta-tasks like Player creation / managing multiple Players for a single user, finding servers, or configuring graphics and sound. None of these things should be routing all keyboard events through a single Player.

There is an extra concern. What if your game is on a tablet or PS3/XBOX/...? No keyboard. The user input system should still not be tied to a single instance of Player; however, it's not a keyboard.
> 0 votes

---
Tags: java, objects
---


title: What does HLSL's tex2D return at (0,0)?

text:
# Question
Title: What does HLSL's tex2D return at (0,0)?
I'm trying to understand the mapping of texels to pixels, especially in the context of pixel shaders. I already found out the following:

* When I define a standard quad with vertices at **integer** positions (texture coordinates ranging from 0 to 1), a pixel shader for the upper left pixel will be called with texture coordinates `(0,0)`
* When I subtract 0.5 from the vertices' coordinates (as it's recommended when drawing sprites), the pixel shader for the upper left pixel will be called with texture coordinates `(1/(2*quadWidth), 1/(2*quadHeight))`

My question is about the behaviour of the tex2D function in HLSL:

I would have assumed that it just returns the color of the upper left pixel of the texture when called with texture coordinates of `(0,0)`. But obviously this is not the case, since the second of the above-mentioned variants actually leads to the desired 1:1 mapping.

So is it correct that `tex2D` returns the original pixel values of a texture when given the following texture coordinates?

# Answer
Short answer: yes, that formula is correct.

Longer answer: if you think of a texture as being a grid of little squares, one for each texel, the actual color value stored in the texture can be thought of as being located at a point at the *center* of each texel square. So, in UV coordinates where the texture ranges from (0, 0) to (1, 1), the color samples are located at 0.5/texWidth, 1.5/texWidth, 2.5/texWidth, etc. along the U axis, and similarly along the V axis with texHeight.

This applies to bilinear filtering, clamp-to-edge, etc. So if you call `tex2D` at (0, 0), or any other position that corresponds to an *integer* number of texels, with bilinear filtering you'll get a blend of four adjacent texels. If called at a position corresponding to an *integer-plus-half* number of texels, you'll get one texel exactly.

Unfortunately, in D3D9 this convention applies to textures but not to render targets. As you mentioned, when you draw on the screen, the points at which a pixel shader is evaluated are at integer coordinates, not integer-plus-half coordinates. This affects how attributes are interpolated, and you end up with attribute values (including UVs) evaluated as if at the *corner* of a pixel square instead of its center. And this messes things up when you're trying to draw a texture exactly 1:1 onto the screen. Hence the infamous half-pixel offset that you need to apply to vertex positions in D3D9.

In D3D10 they fixed this (and in OpenGL it was never broken in the first place) so that pixel shaders are evaluated at integer-plus-half coordinates, i.e. at pixel centers instead of corners, just as texels are.
> 8 votes

---
Tags: directx, hlsl, directx9
---


# Question
Title: SDL 2.0 setup on code::blocks using gcc(MinGW) on win7
I have recently installed code::blocks on my system running windows 7 home premium 64-bit, and wanted to start learning SDL. The code::blocks executable is the one installed by the "*codeblocks-12.11mingw-setup.exe*"- setup wizard, which also installs gcc and MinGW as implied by the name. I proceeded to download the precompiled version of SDL 2.0 development files "*SDL2-devel-2.0.0-mingw.tar.gz*" from the SDL site, created a new empty project, pointed the compiler to the /include directory and the linker to the /lib directory of the 32-bit version of SDL 2.0 using the project specific search directories and set the IDE to treat the project as a GUI application instead of a console application. However, trying to build the project always results to a build error of the form:

```
`SDL_main':
undefined reference to `SDL_Init'
undefined reference to `SDL_Quit'
undefined reference to `WinMain@16'
=== Build finished: 3 errors, 0 warnings (0 minutes, 0 seconds) ===

```

Which is understandable since I have not specified any linker flags, but adding the flags `-lmingw32 -lSDLmain -lSDL` to "other linker options" in the IDE results in the error:

```
ld.exe  cannot find -lSDLmain
ld.exe  cannot find -lSDL
=== Build finished: 2 errors, 0 warnings (0 minutes, 0 seconds) ===

```

Implying it did indeed recognize the flag `-lmingw32`. I tried to copy the appropriate SDL dev files directly to MinGW/include and MinGW/lib, and placed the runtime DLL in the project directory to no avail. Do I have the wrong linker options for SDL 2.0, are they in the wrong order, or am I missing something else?

EDIT: checking all the involved files revealed that libSDLmain.a has been replaced by libSDL2main.a etc. in SDL 2.0. After replacing the linker options with `-lmingw32 -lSDL2main -lSDL2` the linker stopped complaining about not finding missing statically linked libraries. However it now again fails to find the definition of the various SDL routines called in the program, giving the same output as stated in the first case (undefined reference to X).

EDIT2: Just found out i'm not alone with this problem, there is an old, unanswered question about the exact same problem on stackoverflow: https://stackoverflow.com/questions/17011028/i-can-compile-with-sdl1-2-but-not-with-sdl2-cb

---

Source code:

```
#include <SDL2/SDL.h>

int main(int argc, char* argv[])
{
  SDL_Init(SDL_INIT_EVERYTHING);
  SDL_Quit();
  return 0;
}

```

Build log from building the project after adding the aforementioned linker options and SDL files directly in MinGW's /include and /lib directiories and removing the search directories from the project's options:

```
-------------- Build: Debug in newProject(compiler: GNU GCC Compiler)---------------

mingw32-g++.exe  -o bin\Debug\newProject.exe obj\Debug\newProject\newProject\main.o   -lmingw32 -lSDLmain -lSDL   -mwindows
c:/program files (x86)/codeblocks/mingw/bin/../lib/gcc/mingw32/4.7.1/../../../../mingw32/bin/ld.exe: cannot find -lSDLmain
c:/program files (x86)/codeblocks/mingw/bin/../lib/gcc/mingw32/4.7.1/../../../../mingw32/bin/ld.exe: cannot find -lSDL
collect2.exe: error: ld returned 1 exit status
Process terminated with status 1 (0 minutes, 0 seconds)
2 errors, 0 warnings (0 minutes, 0 seconds)

```

# Answer
> 2 votes
After exhaustively troubleshooting everything, I finally noticed that I had accidentally linked the program to the 64-bit version of SDL while compiling for 32-bit, and now the project compiles and links effortlessly.

# Answer
> -1 votes
The correct flags for SDL 2.0.0 are -lSDL2main and -lSDL2

---
Tags: c++, sdl, mingw
---


# Question
Title: Combining rotation,scaling around a pivot with translation into a matrix
In short: I need to combine rotation (in the form of a quaternion), scaling around a pivot point along with translation into a transformation matrix.

The long: I am trying to implement a proprietary model format. This format includes animations. Part of that animation involves generating a matrix which combines rotation (in the form of a quaternion) and scaling around a pivot point, with translation into a transformation matrix. I am using OpenGL and the OpenGL math library (GLM)

Someone else has already implemented parts of the proprietary model format using DirectX. The part in question was implemented in directX like this:

```
D3DXMatrixTransformation(&BaseMatrix, &ModelBaseData->PivotPoint, NULL, &ScalingVector, &ModelBaseData->PivotPoint, reinterpret_cast<D3DXQUATERNION*>(&RotationVector), &TranslationVector);

```

I found the WINE implementation of this function and attempted to duplicate it like this:

```
mat4 m1, m2, m3, m4, m5, m6, m7, p1, p2, p3, p4, p5;

m5 = glm::translate(0,0,0);
m7 = glm::translate(pivot+translationVector);
m1 = glm::translate(-pivot);
m3 = glm::scale(scalingVector);
m6 = glm::mat4_cast(rotationQuaternion); //Convert quaternion to a matrix

//m2 & m4 are identity
p1 = m1;// * m2
p2 = p1 * m3; //Apply scaling first
p3 = p2;// * m4;
p4 = p3 * m5;
p5 = p4;
p5 = p4 * m6;
mat4 result = p5 * m7;

```

(I realize glm::translate(0,0,0) is the identity matrix) Unfortunately neither the scaling nor the rotation seems to work correctly like this. So I took another approach based off of this ordering of translation, rotation and scaling.

```
mat4 result = glm::scale(scalingVector) * glm::translate(pivot) * glm::mat4_cast(rotationQuaternion) * glm::translate(translationVector);

```

However the scaling does not appear to be around the pivot point and I'm not entirely sure about the rotation. Does anyone have any tips on how to accomplish this?

# Answer
Rotation/scaling is around the origin. To both scale/rotate around a pivot, you apply a negative translation to move the pivot point to the origin, apply your scale and rotate, and then move your pivot point back.

```
mat4 result = glm::translate(-pivot) *
              glm::scale(..) *
              glm::rotate(..) *
              glm::translate(pivot) *
              glm::translate(..);

```
> 7 votes

---
Tags: opengl, mathematics, matrix, glm
---


# Question
Title: How to open prerequisite retrieval application
I have an application that cannot use OneClick publishing.

I still want to access those nice prerequisite (applications?) that install .NET and XNA for you when you create a OneClick publisher.

I can check if the frameworks are needed via the registry, but is there anyway to get something similar to what the setup.exe consists of in a publish?

# Answer
ClickOnce creates a "setup.exe" that checks for prerequisites (like the .NET Framework and XNA), downloads and installs them from Microsoft's servers, and then invokes your ClickOnce manifest. **It is possible to create a setup.exe that installs just prerequisites and then does nothing.**

The best way to do this is to with an MSBuild script. The creation of "setup.exe" is performed by the `<GenerateBootstrapper>` task. The MSDN entry gives the various parameters you can customise (and also a minimal MSBuild example).

Because Visual Studio project files *are* MSBuild scripts, I find it convenient to embed it in one, as you can then just drop it into your solution. **Here is a complete project file that does what you need:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Generate</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">x86</Platform>
    <ProductVersion>8.0.30703</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{B65DD26E-6A17-47E0-A21B-E7AF0F156610}</ProjectGuid>
    <OutputType>Library</OutputType>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Generate|AnyCPU' ">
    <OutputPath>bin\Ignore\</OutputPath>
  </PropertyGroup>
  <ItemGroup>
    <None Include="Readme.txt" />
  </ItemGroup>
  <!-- Unused, in theory -->
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <ItemGroup>
    <BootstrapperPackage Include=".NETFramework,Version=v4.0,Profile=Client">
      <Visible>False</Visible>
      <ProductName>Microsoft .NET Framework 4 Client Profile %28x86 and x64%29</ProductName>
      <Install>true</Install>
    </BootstrapperPackage>
    <BootstrapperPackage Include="Microsoft.Xna.Framework.4.0">
      <Visible>False</Visible>
      <ProductName>Microsoft XNA Framework Redistributable 4.0</ProductName>
      <Install>true</Install>
    </BootstrapperPackage>
  </ItemGroup>
  <Target Name="Build">
    <GenerateBootstrapper
        BootstrapperItems="@(BootstrapperPackage)"
        ApplicationName="Install Prerequisites"
        OutputPath="Installer\" />
    <Copy SourceFiles="Installer\setup.exe" DestinationFiles="Installer\Install Prerequisites.exe" />
    <Delete Files="Installer\setup.exe" />
  </Target>
</Project>

```

(Put the above in a text file and give it a `.csproj` extension. It's tested in Visual C# Express 2010. I've also put in some tasks to rename the output to something nice.)

Typically `<BootstrapperPackage>` is used to indicate items to the `BootstrapperItems` parameter (like in regular projects using ClickOnce), but this naming is arbitrary. The above project file generates an install for XNA 4 and .NET 4 Client Profile. If you wanted to change these, you could copy them from a dummy project with ClickOnce configured.

If you want to have your installer launch a program, after it is done installing prerequisites, you can set the `ApplicationFile` parameter.

(Note that the `GenerateBootstrapper` task, as used by ClickOnce, won't appear in your regular project files - it's invoked somewhere inside `Microsoft.CSharp.targets`.)
> 4 votes

---
Tags: xna, c#, .net
---


# Question
Title: What concepts are used to procedurally generate video game content using music like in Audiosurf, Beat Hazard & Symphony?
I'm curious as to how video games like Audiosurf, Beat Hazard and Symphony procedurally generate content using music. What are the common concepts used to accomplish this? And in what way is the music read and interpreted into data that can be used in the game?

Also, I plan on using Java, so if there are any Java-specific information anyone can share, that would be greatly appreciated.

# Answer
> 1 votes
The way to go is to transform and use parts of the music that are usable.

You can use the volume (wave height at a given time). Audiosurf use the volume to adjust speed.

You can compute a FFT of the music, then trigger some events when some pre-defined wave lenght are heard. Audiosurf generate lights flashes when drums sounds are heards (this is easy to detect using FFT)

You can use a Pseudo random generator seeded using some value taken from the track to generate the rest of your gameplay.

---
Tags: java, procedural-generation
---