title: HTML5 mobile game storing data

text:
# Question
Title: HTML5 mobile game storing data
I am developing an mobile application (in HTML5) that will run on multiple platforms and will eventually have both single and multiplayer options. The current issue I have is the best method for storing many rows of data so that the user can access it either in single (no internet) or multiplayer.

I have a relational database for the multiplayer users to access the data, however I'm concerned about performance (keep trying to access to the server). I was wondering if there is any reasonable method (apart from localstorage and websql - as I understand, localstorage can't hold a lot of data and websql is only available on certain platforms) to store a lot of data locally on a mobile device so that any non-internet users can still access their data and do so quickly?

# Answer
It depends, whether you game will run in browser or wrapper (such as PhoneGap, or your custom). In latter case you can simply use device storage to store anything you need.
> 1 votes

---
Tags: html5, mobile, data, storage
---


# Question
Title: How to squash stretch the Bounding box so as to get Good Physics effect
I have Surrounded a game Object with a rectangular Box and applied Physics properties to that Box so that load on the computation gets reduced. But i have a problem, whenever in animation if the Game objects body part goes out of the Box then it will not collide, Is there any solutions?

# Answer
> 1 votes
You can either change the size of your bounding box to encompass the entire object and all it's possible sizes (not very realistic). Or you can make multiple physics objects for the game object. The physics boxes would surround all the moving parts of the game object, and move with those parts in animations.

---
Tags: bullet-physics
---


# Question
Title: How to draw sprite according to Player position when button is pressed?
How do I draw a sprite right at my Player sprite's position when I pressed Spacebar?

```
protected void playerInput() {
        KeyboardState key = Keyboard.GetState();

        if (key.IsKeyDown(Keys.Escape)) this.Exit();
        if (key.IsKeyDown(Keys.Up))     playerPos.Y -= 5;
        if (key.IsKeyDown(Keys.Down))   playerPos.Y += 5;
        if (key.IsKeyDown(Keys.Left))   playerPos.X -= 5;
        if (key.IsKeyDown(Keys.Right))  playerPos.X += 5;
        if (key.IsKeyDown(Keys.Space))  bSpawnSandbag = true;
    }

protected override void Update(GameTime gameTime) {
        playerInput();
        base.Update(gameTime);
    }

 protected override void Draw(GameTime gameTime) {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin();
        spriteBatch.Draw(player, playerPos, Color.White);

        if (bSpawnSandbag) {
           spriteBatch.Draw(sandbag, new Vector2(playerPos.X + 3, playerPos.Y + 3), Color.White);
        }

        spriteBatch.End();

        base.Draw(gameTime);
    }

```

If I use the code above, the "sandbag / the sprite I want to draw" will move with my Player position and I don't want that. I want it to draw at THAT specific position my Player was once at when I press Spacebar for 1 time. Any clue? O\_O I want it to be...

Let say, player position = (10, 10) Player pressed Spacebar, draw Sandbag at 10,10 (permanently) Even though Player moved to 12, 10 & not pressing Spacebar , the Sandbag would still be at 10,10

# Answer
> 6 votes
Think for a moment what happens if bSpawnSandbag is true. It will always draw the sandbag. However the only input you are using is the playerPos.X/Y for where to draw it. Of course it's going to draw it at the players position. It's continues and not a one time thing. Code isn't called once unless your structure is specified/setup as such. As long the bSpawnSandbag is true, sandbag will be drawn.

I don't know what properties your sprites has. Simply keep track of the position when space is hit

```
Vector2 bagPos = new Vector2();

protected void playerInput() {
        KeyboardState key = Keyboard.GetState();

        if (key.IsKeyDown(Keys.Escape)) this.Exit();
        if (key.IsKeyDown(Keys.Up))     playerPos.Y -= 5;
        if (key.IsKeyDown(Keys.Down))   playerPos.Y += 5;
        if (key.IsKeyDown(Keys.Left))   playerPos.X -= 5;
        if (key.IsKeyDown(Keys.Right))  playerPos.X += 5;

        //If bSpawnSandbag is not true AND spacebar is down
        if (key.IsKeyDown(Keys.Space) && !bSpawnSandbag)  {

         bSpawnSandbag = true;
         bagPos.X = playerPos.X;
         bagPos.Y = playerPos.Y;

         }
    }

protected override void Update(GameTime gameTime) {
        playerInput();
        base.Update(gameTime);
    }

 protected override void Draw(GameTime gameTime) {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin();
        spriteBatch.Draw(player, playerPos, Color.White);

        if (bSpawnSandbag) {

           spriteBatch.Draw(sandbag, bagPos, Color.White);
        }

        spriteBatch.End();

        base.Draw(gameTime);
    }

```

Here is a link that might be handy for you. Assuming you are a beginner.

Edit:

As for your question in your comment...

( Not tested and it's just to give you an idea )

Let's assume we are using our own created Sprite class. It contains a Texture2D you need to pass through the constructor and a position vector. Which will be both used in the draw function.

```
public class Sprite(){
public Vector2D position{get;set;}
private Texture2D texture;

public Sprite(Texture2D t, Vector2D pos)
{
  position = pos;
      texture = t;
 }

public Sprite(Texture2D t)
{
    texture = t;
}

public draw(SpriteBatch sb)
{
   sb.draw(texture,position);
}

}

```

Now lets say we have a class that manages our sprites somewhere:

```
//Our list that holds sprite objects
List<Sprite> spriteList = new List<Sprite>();

//Draw all sprites in our list
private void drawSprites(){
  for(int i = 0; i < spriteList.Count; i++)
    //Pass our SpriteBatch to our draw function in Sprite
    spriteList[i].draw(spriteBatch);
}

//Create new sandbags
private void createSandBag(Vector2D atPos){
   Sprite sandbag = new Sprite(MY_STATIC_TEXTURE);
  sandbag = atPos;
  spriteList.add(sandbag);
}

```

you then call createSandBag when Space bar is hit and pass the position of your player

---
Tags: xna
---


title: Why does OpenGL >= 3 only allow VBOs?

text:
# Question
Title: Why does OpenGL >= 3 only allow VBOs?
I see that OpenGL versions 3 and up eliminate the use of client-side rendering. Immediate mode has been eliminated, and vertex arrays seem to be deprecated. Instead, if I understand correctly, VBOs are the main way of rendering vertices.

While I see the logic behind having a uniform way of rendering everything, is it the case that VBOs have no major downsides over vertex arrays? I thought VBOs were supposed to be large buffers containing \> 1MB of data, generally. What if I have a scene that has a lot of smaller geometry? I have a scene graph with a large number of nodes, each of which needs its own transform, etc. Each node should also be able to be deleted separately, added to separately, etc. I was using vertex arrays before. So my first question is whether, if I switch to VBOs, there will be a greater overhead to my scene graph objects now because a VBO needs to be allocated for each object.

Another concern is that the geometry I'm rendering can be highly dynamic. In the worst case, there may be times when all geometry needs to be resent every frame for some period of time. Will VBOs have worse performance than vertex arrays in this use case, or do VBOs at worst do just as much work as vertex arrays but no more?

So, in more concise format, my questions are:

1) Is there a substantial overhead to allocating / deallocating VBOs (I mean the mere act of setting up a buffer)?

2) If I'm updating the data from the CPU every frame, can this be substantially worse than if I had used vertex arrays?

And finally, I'd like to know:

3) If the answer to either of the above questions is "yes", why deprecate other modes of rendering that could have advantages over VBOs? Is there something I'm missing here, like techniques I'm supposed to use to mitigate some of these potential allocation costs, etc.?

4) Do the answers to any of these questions change substantially depending on what OpenGL version I'm using? If I refactor my code to be OpenGL 3 or 4 forward-compatible by using VBOs in a way that is performant, will the same techniques be likely to perform well with OpenGL 2, or is it likely that certain techniques are much faster with OpenGL 3+ and others with OpenGL 2?

I asked this question on stack overflow, but I am re-posting here because I realized this site may be more appropriate for my question.

# Answer
> Is there a substantial overhead to allocating / deallocating VBOs (I mean the mere act of setting up a buffer)?

Define "substantial." It is generally wise not to create them in the middle of frames; they should be set up during initialization or wherever. But this is true of most OpenGL objects, like textures, renderbuffers, or shaders.

> If I'm updating the data from the CPU every frame, can this be substantially worse than if I had used vertex arrays?

Can it? Yes. OpenGL defines functionality, not *performance*. You can indeed make things much slower. Or you can make things faster. It all depends on how you use it.

The OpenGL Wiki has a good article on how to properly stream data.

> If the answer to either of the above questions is "yes", why deprecate other modes of rendering that could have advantages over VBOs? Is there something I'm missing here, like techniques I'm supposed to use to mitigate some of these potential allocation costs, etc.?

First, they weren't just deprecated. Deprecation means marking something as "to be removed" in future versions. They were deprecated in 3.0, and **removed** in 3.1 core and above.

Second, the ARB has generally explained the reason they removed stuff from OpenGL. It makes the spec smaller and simpler. It makes the API smaller and more streamlined. It makes it easier to know what APIs you ought to be using; 2.1 had 4 ways to provide vertex data; 3.1+ has 1. It gets rid of a lot of cruft. Etc.

> Do the answers to any of these questions change substantially depending on what OpenGL version I'm using? If I refactor my code to be OpenGL 3 or 4 forward-compatible by using VBOs in a way that is performant, will the same techniques be likely to perform well with OpenGL 2, or is it likely that certain techniques are much faster with OpenGL 3+ and others with OpenGL 2?

More or less no. Only on MacOSX is the difference between 3.1+core and pre-3.0 versions really apparently. The compatibility profile is implemented by all drivers for Linux and Windows, so you can assume that the core profile from these drivers is really just adding checks to prevent you from calling compatibility functions.

Under Mac OSX 10.7, GL 3.2 core is available, but *not* the compatibility profile. That doesn't *necessarily* mean anything for performance techniques on one versus the other. But it does mean that if there are differences, that is the platform you will see them on.
> 22 votes

# Answer
The way OpenGL works, whenever you use non-VBO data, the driver has to make a copy of it - in practice creating a temporary VBO - since nothing stps you from modifying your user-space naked arrays between calls to OpenGL.

There may be some driver-side trickery to make the temp allocation faster, but there's nothing you can do to avoid the copying.

So yeah, as long as you - and the driver developers - do everything right, VBOs should(tm) always just speed things up.
> 18 votes

# Answer
> and vertex arrays seem to be deprecated. Instead, if I understand correctly,

Not quite. Vertex arrays are the foundation for vertex buffer objects. Only the storage moved from client to server side.

> What if I have a scene that has a lot of smaller geometry?

Merge smaller geometry sets into larger VBOs. There's no need to have one VBO per geometry batch. You can perfectly address subsets of a VBO for rendering. Use a nonzereo offset for the gl…Pointer data parameter.

> 2) If I'm updating the data from the CPU every frame, can this be substantially worse than if I had used vertex arrays?

For this there are the GL\_DYNAMIC\_DRAW and GL\_STREAM\_DRAW buffer usage flags.

> If the answer to either of the above questions is "yes", why deprecate other modes of rendering that could have advantages over VBOs?

Because there are no advantages. The geometry data has to be transferred to the GPU in any case. Using a regular client side vertex array will still cause a DMA transfer to GPU, and immediate mode will build a batch to transfer first as well.

There's absolutely no benefit in not using VBOs.
> 9 votes

---
Tags: opengl, performance, vbo
---


# Question
Title: How do I undo changing the color of an image in Slick2d?
This code colors the enemy red:

```
enemies.get(i).image.setColor(0,1,0,0,1);
enemies.get(i).image.setColor(1,1,0,0,1);
enemies.get(i).image.setColor(2,1,0,0,1);
enemies.get(i).image.setColor(3,1,0,0,1);

```

if I set it to:
`enemies.get(i).image.setColor(0,0,0,0,1);`
it turns it pure black, and if I set it to
`enemies.get(i).image.setColor(0,0,0,0,0);`
it turns the enemy invisiable

How do I un-color enemy red? as in return to state as it was before it was colored.

Documentation link.

# Answer
Don't fiddle with the alpha at all if you're not wanting to change it. Use the non-alpha version.

```
enemies.get(i).setCurrentColor(1,0,0);

```

Then create this method:

```
setCurrentColor(int r, int g, int b) {
    image.setColor(0,r,g,b);
    image.setColor(1,r,g,b);
    image.setColor(2,r,g,b);
    image.setColor(3,r,g,b);
}

```

Then when you want to return to no color, just texture, set the enemy to white:

```
enemies.get(i).setCurrentColor(1,1,1);

```

Turns out there's a `setImageColor` function that Eric mentioned in his answer. I checked the source:

```
public void setImageColor(float r, float g, float b) {
    setColor(TOP_LEFT, r, g, b);
    setColor(TOP_RIGHT, r, g, b);
    setColor(BOTTOM_LEFT, r, g, b);
    setColor(BOTTOM_RIGHT, r, g, b);
}

```

So, `setImageColor` is not any different than calling `setColor` on all four corners. Just in case you were wondering.
> 3 votes

# Answer
You need to track the last color set before changing it red, and use that when you want to restore the color.
> 1 votes

# Answer
An `Image`'s default color is 1,1,1,1 (rgba) a.k.a. *opaque* (or *non-transparent*) *white*. Use `Image.setImageColor` to reset it:

```
enemies.get(i).image.setImageColor(1,1,1,1);

```

Be sure to use this method instead of applying `Image.setColor` to each of the image's four corners.
> 1 votes

---
Tags: java, slick
---


# Question
Title: Hide movieclip parts that are out of bounds
I'm making a game where one takes a picture of their face to use on a character. I have them zoom in on the picture, but the bitmapdata extends out of its movieclip. How do I assign bounds to my bitmapdata?

# Answer
> 2 votes
I think you need to dynamically create a shape with the x, y, width, and height of what you want to be visible, make it a mask and then add it to the display list in front of the bitmap data's movie clip. See this article on the subject.

# Answer
> 0 votes
Use the `scrollRect` property of your Bitmap. Here's the API documentation. You might also be interested in the following question/answer.

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


# Question
Title: RGB to xyY color space conversion and luminance
The luminance calculated by following GLSL functions (fragment shaders - tonemap) has different value:

```
float GetLuminance (vec3 rgb)
{
     return (0.2126 * rgb.x) + (0.7152 * rgb.y) + (0.0722 * rgb.z);
}

vec3 RGB2xyY (vec3 rgb)
{
     const mat3 RGB2XYZ = mat3(0.4124, 0.3576, 0.1805,
                               0.2126, 0.7152, 0.0722,
                               0.0193, 0.1192, 0.9505);
    vec3 XYZ = RGB2XYZ * rgb;

    return vec3(XYZ.x / (XYZ.x + XYZ.y + XYZ.z),
                XYZ.y / (XYZ.x + XYZ.y + XYZ.z),
                XYZ.y);
}

```

I used a glm library to calculate an example result. For glm::vec3(2.0f, 3.0f, 8.0f) GetLuminance returns 3.1484. RGB2xyY returns glm::vec3 which z component is equal 3.8144. What is wrong ?

# Answer
> 3 votes
Either the matrix is transposed (i.e. rows and columns swapped) in `RGB2xyY`, or the equation in `GetLuminance` uses the row vector instead of the column vector. The two values just happen to be close by accident.

Here is a Matlab trace showing whats going on. The quote is used to indicate matrix transposition. (The multiplication below is swapped around, of course you could also do `s*v'` and `s'*v'`).

BTW, using tools like Matlab (or Octave) are great for quickly prototyping these types of algorithms and finding bugs like these fast.

```
>> s = [0.4124, 0.3576, 0.1805;
        0.2126, 0.7152, 0.0722;
        0.0193, 0.1192, 0.9505] %assign matrix to s

s =

    0.4124    0.3576    0.1805
    0.2126    0.7152    0.0722
    0.0193    0.1192    0.9505

>> v = [2 3 8] % assign vector to v

v =

     2     3     8

>> v*s         % multiply

ans =

    1.6170    3.8144    8.1816

>> v*s'        % multiply with transposed matrix

ans =

    3.3416    3.1484    8.0002

```

---
Tags: opengl, mathematics, graphics, glsl
---


# Question
Title: How to use D3DXIntersectTri function to find intersected point?
How to calculate direction for D3DXIntersectTri function to find intersected point? And after getting the result in Distance how to get that coordinate(XYZ)?

# Answer
All of this is in the documentation for your function.
> 0 votes

---
Tags: 3d, directx, directx9, intersection
---


# Question
Title: How to achieve smooth movement with a fixed timestep
Previously in the update method of my game I was using a variable time step which provided very smooth movement of a player sprite except when the frame rate would drop, even slightly. At that point I would end up with the sprite making a noticeable lunge forward. I tried averaging the delta to make it less noticeable but wasn't satisfied.

So I've been trying to implement a fixed time step using the code provided in the article http://gafferongames.com/game-physics/fix-your-timestep/ as an example.

```
double t = 0.0;
const double dt = 0.01;

double currentTime = hires_time_in_seconds();
double accumulator = 0.0;

State previous;
State current;

while ( !quit )
{
     double newTime = time();
     double frameTime = newTime - currentTime;
     if ( frameTime > 0.25 )
          frameTime = 0.25;
     currentTime = newTime;

     accumulator += frameTime;

     // ***** Is this where I should add acceleration to the current state velocity? *****
     // current.v += Player::MoveAcceleration * frameTime;

     while ( accumulator >= dt )
     {
          previousState = currentState;
          integrate( currentState, t, dt );
          t += dt;
          accumulator -= dt;
     }

     const double alpha = accumulator / dt;

     State state = currentState*alpha + previousState * ( 1.0 - alpha );

     render( state );
}

```

In this example where would I add to the velocity? As I noted in the code comment, I am currently adding it prior to the integration loop, but the sprite movement is now consistently lunging forward each frame and is not smooth at all. Even when lowering the acceleration it is still there, and is not a solution anyway as I want the player to be able to walk or run.

I hope this makes sense. I have read so many articles over the last couple weeks and tried many combinations but nothing is working smoothly. I figure someone here must have a solid routine to achieve a fixed time step in a game with smooth sprite movement/animation.

Thanks

# Answer
> 4 votes
You are probably updating the velocity twice, since this is usually done in the integration step itself. I expect you implemented the RK4 integration from http://gafferongames.com/game-physics/integration-basics/.

The author defines `Derivative.dv` as the **acceleration** (derivative of velocity) and `State.v` as as the **velocity**

In the `evaluate` function you can then see that the following line updates the velocity using the acceleration `d.dv`:

```
state.v = initial.v + d.dv*dt;

```

and that this line updates the acceleration (calculated by `acceleration`)

```
output.dv = acceleration(state, t+dt)

```

So if you want to change the acceleration, you should change the `acceleration` function to return the acceleration you want (e.g. constant `9.81f` for gravity). The velocity is then changed by the existing code, there is no need to add your own line.

Keep in mind that all of this is **one-dimensional** (position, velocity etc. are given as a single float) so you can only move in a straight line.

# Answer
> 3 votes
Gordonk was absolutely spot on. It now appears that I have silky smooth movement at 60fps. If I cap the frame rate at anything less than 60 I start to see serious stuttering, but I guess that's a separate issue to explore.

So here is the code I am using right now. It hasn't been optimized in any way, it was just to implement a fixed time step. I'm using the cocos2d-x framework. CCPoint is a simple class that contains two floats, x and y.

```
struct State
{
    CCPoint statePosition; // position
    CCPoint stateVelocity; // velocity
};

struct Derivative
{
    CCPoint derivativePosition; // derivative of position: velocity
    CCPoint derivativeVelocity; // derivative of velocity: acceleration
};

double getCurrentTimeInSeconds()
{
   struct cc_timeval currentTime;
   CCTime::gettimeofdayCocos2d(&currentTime, NULL);
   return (currentTime.tv_sec) + (currentTime.tv_usec / 1000000.0);
}

void update(float dt)
{
    if (GetAsyncKeyState(VK_LEFT) & 0x8000) {
        pPlayer->movement = -1;
        pPlayerSprite->setScaleX(1);
    }

    if (GetAsyncKeyState(VK_RIGHT) & 0x8000) {
        pPlayerSprite->setScaleX(-1);
        pPlayer->movement = 1;
    }

    applyPhysics(dt);

    pPlayer->movement = 0;
}

void applyPhysics(float gameTime) {
    const float newTime = getCurrentTimeInSeconds();
    float deltaTime = newTime - currentTime;
    currentTime = newTime;

    if (deltaTime>0.25f)
        deltaTime = 0.25f;

    accumulator += deltaTime;

    int loopCount = 0;
    while (accumulator>=dt)
    {
        accumulator -= dt;
        previous = current;
        integrate(current, t, dt);
        t += dt;
        loopCount++;
    }

    State state = interpolate(previous, current, accumulator/dt);

    pPlayerSprite->setPosition(state.statePosition);
}

State interpolate(const State &previous, const State &current, float alpha)
{
    State state;
    state.statePosition.x = current.statePosition.x*alpha + previous.statePosition.x*(1-alpha);
    state.statePosition.y = current.statePosition.y*alpha + previous.statePosition.y*(1-alpha);

    state.stateVelocity.x = current.stateVelocity.x*alpha + previous.stateVelocity.x*(1-alpha);
    state.stateVelocity.y = current.stateVelocity.y*alpha + previous.stateVelocity.y*(1-alpha);

    return state;
}

CCPoint acceleration(const State &state, float t)
{
    CCPoint tempPoint = CCPointZero;

    tempPoint.x = pPlayer->movement * Player::MoveAcceleration;

    if (pPlayer->isOnGround) {
        tempPoint.x *= Player::GroundDragFactor;
    }
    else {
        tempPoint.x *=  Player::AirDragFactor;
    }

    tempPoint.x = MathHelper::Clamp(tempPoint.x, -Player::MaxMoveSpeed, Player::MaxMoveSpeed);

    return tempPoint;
}

Derivative evaluate(const State &initial, float t)
{
    Derivative output;
    output.derivativePosition.x = initial.stateVelocity.x;
    output.derivativePosition.y = initial.stateVelocity.y;

    CCPoint tempPoint = acceleration(initial, t);
    output.derivativeVelocity.x = tempPoint.x;
    output.derivativeVelocity.y = tempPoint.y;

    return output;
}

Derivative evaluate(const State &initial, float t, float dt, const Derivative &d)
{
    State state;
    state.statePosition.x  = initial.statePosition.x + d.derivativePosition.x*dt;
    state.statePosition.y  = initial.statePosition.y + d.derivativePosition.y*dt;

    state.stateVelocity.x  = initial.stateVelocity.x + d.derivativeVelocity.x*dt;
    state.stateVelocity.y  = initial.stateVelocity.y + d.derivativeVelocity.y*dt;

    Derivative output;
    output.derivativePosition.x = state.stateVelocity.x;
    output.derivativePosition.y = state.stateVelocity.y;

    CCPoint tempPoint = acceleration(state, t+dt);

    output.derivativeVelocity.x = tempPoint.x;
    output.derivativeVelocity.y = tempPoint.y;

    return output;
}

void integrate(State &state, float t, float dt)
{
    Derivative a = evaluate(state, t);
    Derivative b = evaluate(state, t, dt*0.5f, a);
    Derivative c = evaluate(state, t, dt*0.5f, b);
    Derivative d = evaluate(state, t, dt, c);

    const float dxxdt = 1.0f/6.0f * (a.derivativePosition.x + 2.0f*(b.derivativePosition.x + c.derivativePosition.x) + d.derivativePosition.x);
    const float dxydt = 1.0f/6.0f * (a.derivativePosition.y + 2.0f*(b.derivativePosition.y + c.derivativePosition.y) + d.derivativePosition.y);

    const float dvxdt = 1.0f/6.0f * (a.derivativeVelocity.x + 2.0f*(b.derivativeVelocity.x + c.derivativeVelocity.x) + d.derivativeVelocity.x);
    const float dvydt = 1.0f/6.0f * (a.derivativeVelocity.y + 2.0f*(b.derivativeVelocity.y + c.derivativeVelocity.y) + d.derivativeVelocity.y);

    state.statePosition.x  = state.statePosition.x + dxxdt*dt;
    state.statePosition.y  = state.statePosition.y + dxydt*dt;

    state.stateVelocity.x  = state.stateVelocity.x + dvxdt*dt;
    state.stateVelocity.y  = state.stateVelocity.y + dvydt*dt;
}

```

I haven't tried applying any vertical force yet but hopefully it will work the same way.

Thanks again for helping me understand the acceleration method.

---
Tags: c++, movement, cocos2d-x, fixed-timestep
---


# Question
Title: Xna Equivalent of Viewport.Unproject in a draw call as a matrix transformation
I am making a 2D sidescroller and I would like to draw my sprite to world space instead of client space so I do not have to lock it to the center of the screen and when the camera stops the sprite will walk off screen instead of being stuck at the center. In order to do this I wanted to make a transformation matrix that goes in my draw call.

I have seen something like this: https://stackoverflow.com/questions/3570192/xna-viewport-projection-and-spritebatch

I have seen Matrix.CreateOrthographic() used to go from Worldspace to client space but, how would I go about using it to go from clientspace to worldspace?

I was going to try putting my returns from the viewport.unproject method I have into a scale matrix such as:

```
blah = Matrix.CreateScale(unproject.X,unproject.Y,0);

```

however, that doesn't seem to work correctly.

Here is what I'm calling in my draw method(where X is the coordinate my camera should follow):

```
Vector3 test = screentoworld(X, graphics);
var clienttoworld = Matrix.CreateScale(test.X,test.Y, 0);
animationPlayer.Draw(theSpriteBatch, new Vector2(X.X,X.Y),false,false,0,Color.White,new Vector2(1,1),clienttoworld);

```

Here is my code in my unproject method:

```
Vector3 screentoworld(Vector2 some, GraphicsDevice graphics):

Vector2 Position =(some.X,some.Y);
var project = Matrix.CreateOrthographic(5*graphicsdevice.Viewport.Width, graphicsdevice.Viewport.Height, 0, 1);
var viewMatrix = Matrix.CreateLookAt(
  new Vector3(0, 0, -4.3f), new Vector3(X.X,X.Y,0), Vector3.Up);

//I have also tried substituting (cam.Position.X,cam.Position.Y,0) in for the (0,0,-4.3f)

 Vector3 nearSource = new Vector3(Position, 0f);
 Vector3 nearPoint = graphicsdevice.Viewport.Unproject(nearSource,
        project, viewMatrix, Matrix.Identity);

return nearPoint;

```

I would also like to be able to move the camera around without moving my sprite. Before I was doing something like:

```
if(directionofsprite == positive && sprite position is not less than 200)
 {
   sprite-=5;
   map-=5;
 }

```

This would make it appear as though the camera is moving to the right. I just want to simplify all of this by making my sprites draw to worldspace.

# Answer
You wrote in a comment that because you're using Demina, your sprites are forcibly being drawn to client space instead of world space. But although I've never used Demina before, I've just checked its source code and that doesn't seem to be the case.

Instead Demina takes a camera transformation matrix which is used to convert the sprites from world space to view space, but you're passing it the wrong matrix. Here's what I recommend you to do. First add a simple camera class like the following to your project:

```
public class Camera
{
    public Camera(Viewport viewport)
    {
        Origin = new Vector2(viewport.Width / 2.0f, viewport.Height / 2.0f);
        Zoom = 1.0f;
    }

    public Vector2 Position { get; set; }
    public Vector2 Origin { get; set; }
    public float Zoom { get; set; }

    public Matrix ViewMatrix
    {
        get
        {
            return Matrix.CreateTranslation(new Vector3(-Position, 0.0f)) *
                   Matrix.CreateScale(Zoom, Zoom, 1) *
                   Matrix.CreateTranslation(new Vector3(Origin, 0.0f));
        }
    }
}

```

This class automatically sets the origin to the center of your viewport which seemed to be what you wanted. So create an instance of that class at the top of your game, and use the `Position` and `Zoom` properties to scroll or zoom your camera around. If you'd like to lock the camera onto your character just do `camera.Position=character.Position` on the update loop. For more complex operations read this article.

As for rendering you can use the same overload you're already using but pass it a `position` that is defined in world space, i.e. if the character is at 5000x400 pass it *that* value. As for the `cameraTransform` parameter pass it the value of `camera.ViewMatrix` which will take care of the world to view space conversion. There's no need to mess with any projection matrices because the internal orthographic projection matrix created by `SpriteBatch` already takes care of mapping view space to client space. In other words:

```
animationPlayer.Draw(spriteBatch, sprite.Position, false, false,
                     0, Color.White, Vector2.One, camera.ViewMatrix);

```

All the unproject and matrix code you showed on your question is not needed. And now your sprites and camera are completely independent. If you want to move a sprite, just change the sprite's position. If you want to move the camera just change the camera's position.
> 2 votes

# Answer
I think you're over thinking this. You should separate your logic and draw code so that you have world space and client space.

As a camera class you can just use a float called leftOffset. Then use this leftOffset to determine the screen position by drawing at position + leftOffset.

Unless you're also going to do zooming in and out this is all you need :).
> 0 votes

# Answer
I was trying your method after seen that there was an unproject command. But it turns out to be a 3d command.

I then tried this code and works perfectly for me.

var dest = ConvertUnits.ToSimUnits((new Vector2(ms.X, ms.Y) - Util.screenCenter())/Util.camera.Zoom) + ship.\_compound.Position;

Basically, you need mouse position relative to screen center offset. This value should divide by camera.zoom. Camer.zoom = 1 when no zoom is done, =0.4 when zoomed out by a bit and =4 when zoomed in 4x.

You can then convert this value to sim units and plus the known sim world center position of camera.

This code might not work for your original request, but the idea is to unzoom and you can already get the 2d position in sim world.
> 0 votes

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


title: Pixel Shader - apply a mask (XNA)

text:
# Question
Title: Pixel Shader - apply a mask (XNA)
I'd like to apply a simple few masks to few images.

The first mask I'd like to implement is mask like:

```
XXXOOO
```

I mean, that on the right everything is masked (to black), and on the left everything is stayed without changes.

The second mask I'd like to implement is glow mask. I mean something like this:

```
    O
  O***O
 O**X**O
  O***O
    O
```

What I mean, is a circle mask, which in the center everything is saved without changes, and going outside the circle everything is starting to be black

The last mask is irregular mask. For example like this:

```
  OOO*
 O**X**O
  OO**OO**O
    OO*X*O
      O*O
       O
```

Where:
O - to black
* - to gray
X - without changes

I've read, how to apply distortion pixel shader in XNA: msdn

Could you explain me how to apply mute mask on an image? (mask will be grayscale)

# Answer
> 1 votes
How about, after you finished drawing everything else, you draw a sprite that covers the entire viewport (can be a rectangle spanning from (-1,-1) to (1,1), and without a perspective matrix), with z-buffer disabled, alpha blending enabled, and a simple texturing shader, and you set your mask to the alpha value of your texture?

That's what I do to implement fade in/fade out effects in my games.

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


title: Single or Multiple Behavior Trees?

text:
# Question
Title: Single or Multiple Behavior Trees?
I just finished coding a generic Behavior Tree structure for my games. My question is, when creating behaviors for enemy AI's, do I create one large behavior tree with every possible configuration as a node or do I create many multiple Behavior Trees and simply swap them in and out as I need them?

To better understand my question here are some examples:

**One large Behavior Tree might look something like this:**

**Multiple smaller Behavior Trees might look like this:**

In the second tree I would simply swap out different trees depending on when I need them. This is more apparent for things like evading and backing away from obstacles, I feel like that would need to be done alongside many other behaviors like chasing and evading.

I hope that made sense.

# Answer
> 1 votes
Generally there would be no need to "swap" out trees.

Build all your behaviors, add in your sequences and selectors to make your tree for your ai agent.

Then for special case stuff you add decorators to stuff where needed.

One big tree, per agent "type" so a soldier type would have a tree with patrol, attack etc etc and a miner would have a different tree. They would use many of the same objects (ie. go to way point) but you just wire up your tree for each agent you needed.

The first picture you have in your post is the way to go.

# Answer
> 0 votes
Not sure if I understand your question correctly. Do you mean during runtime? Or when you design your trees? Certainly when designing your trees, it helps a lot to create lots of small, reusable, modular trees.

You can try creating the concept of "tree link" nodes. Nodes that just let the traversal jump to a different tree (a whole separate tree, stored in a different file, perhaps), and when that tree finally gives a return value, uses that as its return value.

This way you can have a generic main tree that have branches touching on broad subjects: survival, attack, idle, etc. Then you just add your tree links into those empty branches to create variations. You may have an attack subtree that's designed to keep away and just do ranged attacks. You might have another one that's designed to charge head on and do melee attacks instead.

This way its easy to organize your AI types, by just doing a mix-and-match approach. This is not necessarily for convenience in modifying your trees during runtime, but that can be possible too.

Doing this also makes your trees a lot more readable to fellow teammates. It's essentially using the concept of "abstraction" and "information hiding". Two very powerful concepts in software engineering in helping to keep large systems easy to understand and maintain.

---
Tags: ai, game-mechanics, steering-behaviors, behavior-tree
---


# Question
Title: Which features belong to the engine and which ones to a game?
Right now, I find myself implementing and testing new features for my 2D game engine, by directly coding them into the engine. Simultaneously, I have a showcase game with scripting support, which should call the engines functions. I attach e.g. a fixed tile movement to the Entity class in the engine, rather than scripting this specifically for the game. This is definitely breaking the idea of a general engine used for more than one game.

Are there any best practices to keep focusing on the correct implementation in the right parts (that is engine vs. game)?

# Answer
Well there are a couple ways of thinking about this. One is to list the specific features the engine should have (what you've asked here.) However the other way is to just start making games without worrying too much about the "engine", and then features you find are being reused between multiple games (in particular, features used in *every* game) you should migrate from the source for a specific game into a shared codebase called "engine."

Because in the end, why you want a given feature in the engine rather than in the game is that it's shared between multiple games. Typically that'll be things like drawing commands, input controllers, and networking code. A 2D game engine will have lots of 2D graphics features, like loading images, a display hierarchy with z-order, handling spritesheets, tweening, etc. A lot of games need physics simulation, although on the other hand many don't. Meanwhile more "under the hood" stuff used in almost every game includes timers, event messaging, and even math functions specific to game development (eg. distanceToTarget()

---

Long story short:

A) The engine should have features shared by most games.

B) You learn which features are shared by making a bunch of games.
> 25 votes

---
Tags: 2d, software-engineering
---


title: Behavior Tree Iteration Rate

text:
# Question
Title: Behavior Tree Iteration Rate
How is a Behavior Tree iterated in a game? For example, let's assume you have an extremely large Behavior Tree with about a hundred Actions/Conditions. If we were to run one action or condition every Frame Tick that would take about 100 Frames to reach the very last Action in the Tree.

So my question is, do we iterate the whole tree until we find a "runnable" action, run it, then return. Or do we iterate the whole tree and run as many actions as we can before getting to an action that takes multiple frames/updates to finish running?

# Answer
> 4 votes
This is the way I see it, but really this is a decision you need to make based on what types of conditions/actions/behaviors you have.

* **Actions**: Running a function to process data. For example finding a path with A\*. These happen in the background and aren't seen by the user. They usually happen in a single frame, but can stretch to a few frames if needed.
* **Conditions**: A simple data test. For example testing if enemies are in range. Again, these happen in the background and aren't seen by the user. They happen in a single frame.
* **Behaviors**: An activity in game. For example, following a path. These happen in game, and are usually visible to the user. These will almost never happen within a single frame.

For each iteration on the tree, multiple conditions can be processed. Actions and behaviors are different. This is up to you. You might want actions like finding a path to take place in the same frame as starting to follow the path. Or you may want to find the path, then on the next iteration you start the behavior of following that path.

You may have multiple actions per frame, but since actions can be a bit hefty, you may want to limit some of them. Having ten actions that take "just less than a frame" to run, means you're slowing your game down a lot by running them back to back.

Behaviors will almost always take multiple frames.

So there's an easy solution and a more challenging solution. The easy one is to only ever allow one action per tree iteration. The more challenging is to have a running timer and estimates for how long your actions take to run. If running the next action puts you over budget, then save it for next time.

# Answer
> 1 votes
I simply iterate, in one frame, until the whole tree finishes, or until an action/condition requests to suspend the traversal.

Generally you would design your computation-heavy actions so that they only initiate a request to start their processing (instead of actually doing it there and then), which will then be handled by a different part of the game. You would have some sort of function to check if that computation is finished, then you resume traversing the tree.

Commonly this is done by having a signal called "Running" that your nodes can return (alongside Success or Failure), to indicate to the traversal code that it needs to pause itself.

It also depends on the specifics of your game. If you have a turn-based game, when to traverse is a lot easier to think about (i.e. at the start of the turn).

---
Tags: ai, game-loop, behavior-tree
---


# Question
Title: changing depth stencil state in DirectX11
An example from Frank D Luna's 3d Game Programming with Dx11 shows the following effect technique:

```
technique11 DrawTech
{
pass P0
{
    SetVertexShader(   CompileShader( vs_5_0, DrawVS() ) );
    SetGeometryShader( CompileShader( gs_5_0, DrawGS() ) );
    SetPixelShader(    CompileShader( ps_5_0, DrawPS() ) );

    SetBlendState(AdditiveBlending, float4(0.0f, 0.0f, 0.0f, 0.0f), 0xffffffff);
    SetDepthStencilState( NoDepthWrites, 0 );
}
}

```

Setting depth stencil state, blend states etc (and restoring them to previous state) when the Effects library isn't available is my goal.

I've had a hard time finding examples on this though. Luna sidesteps the issue by using the effects framework in his book.

To complicate the issue, I'm using DXUT11 (for loading in meshes).

Can anyone help with an example or an svn repository that includes an example?

# Answer
> 3 votes
in the ID3D11DeviceContext, there is such function calls.

they are :
ID3D11DeviceContext::OMSetBlendState()
ID3D11DeviceContext::OMSetDepthStencilState()
ID3D11DeviceContext::OMSetRenderTargets()
ID3D11DeviceContext::OMSetRenderTargetsAndUnorderedAccessViews()

if you look at this website all of the things are listed here, and there you find how you use them and how they work.

http://msdn.microsoft.com/en-us/library/windows/desktop/ff476385(v=vs.85).aspx

for restoring to the last state, you have to have some kind of state machine implementation in your code, that stores the last used state. DX does not do this for you.

Eventualy, the effect library is using thees commands aswell, just that it has some extra stuff with it ( which i really hate ), so you can infact build your own effect system with this and use it more efficent than what you have in dx10/11.

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


# Question
Title: How do I make Windows store recognize multiple resolutions?
I'm currently developing a XNA Game for Windows phone 8, it works with every emulator resolution (WXGA, WVGA, 720p). However, when I upload the XAP to the Windows phone store it tells me that only WVGA resolution was detected.

Do I have to add some code to make the app downloadable for WXGA phone owners ?

# Answer
> 2 votes
Since you have to target Windows Phone OS7.1 in order to use XNA for Windows Phone 8 I believe that you are stuck with that profile. One possible way of circumventing that is to use MonoGame to develop it which supports Windows 8 and Windows Phone 8.

# Answer
> 1 votes
XNA for WP7 does not support multiple screen resolutions. As previously mentioned, you will have to move to MonoGame to implement this (in most cases, this is surprisingly easy).

It's easy to think that setting the PreferredBackBufferWidth & Height to different resolutions will have the desired effect, but the resultant buffer is then squashed down to 480 x 800 for drawing on the phone screen (regardless of the device's resolution). As an example, in the WP8 720p emulator the game buffer is being squashed from 1280x720 to 480x800 and then stretched back up to 1280x720 so although it looks like it's working there, really it isn't (I have seen hints that the aspect ratio is kept, so there's a chance it's being squashed to 480x853 - see http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206974(v=vs.105).aspx \- but you get the gist)

If you do want to target WP7 as well as 8 then you can share the vast majority of your code between MonoGame and XNA. Uploading 2 .XAP files to the marketplace targeting the two operating systems will then provide a transparent system for delivering the two versions to different phone users. The marketplace will serve the XNA version to WP7 users, and the MonoGame version to WP8 users.

Unfortunately MS have stated they are ceasing future support for XNA and this includes upgrading it to work nicely with WP8. You could also not write code in native C++ for WP7, so MonoGame is not available for those devices.

---
Tags: xna, screen, resolution, windows-phone-8
---


# Question
Title: AS3: Using singletons for sound managers
Is it necessarily a bad thing to use a singleton for a sound manager?

I am having a really tough time determining whether or not I should go ahead and use a singleton (which is easy/it works) or if I am shooting myself in the foot by deviating away from good OOP principles (since a singleton is basically a glorified single-instance global variable of sorts).

# Answer
> 1 votes
An Interface is more suitable for a sound manager as a singleton can be too restrictive and should be used sparingly; otherwise you run the risk of introducing a global state within your application. As you stated, a singleton is "basically a glorified single-instance global variable" and in some circles, considered an anti-pattern. Singletons are not necessarily 'bad' per se; however, if a more suitable solution exists, use it (the more suitable solution, that is).

# Answer
> 0 votes
While Singleton pattern can be dangerous, there is cases when it's simply more efficient and actually makes sense, in case of sound – absolute majority of devices capable of playing games have single sound output. But even then I would suggest using it's cousin – Multiton pattern. You can check `SharedObject` class in ActionScript to see one of examples, it uses `SharedObject.getLocal(<someIdentifier>)` and creates instances when it's needed.

An advantage is that it gives you more flexibility, consider following example:

```
class SoundManagerFactory {
  private const managers:Dictionary = new Dictionary();

  public function getManager(id:Object = 'default'):ISoundManager {
    if (managers[id] == null) {
      managers[id] = new SoundManager();
    }
    return managers[id];
  }
}
interface ISoundManager {}
class SoundManager implements ISoundManager {}

// Usage
SoundManagerFactory.getManager(); //default manager, works just like singleton

```

In this case, if at some point you decide to break your functionality to say Ambient, Voice, Music, Effects (Pretty common for video games to have separate volume controls for different types of sound).

```
SoundManagerFactory.getManager('ambient');
SoundManagerFactory.getManager('music');
SoundManagerFactory.getManager('effects');

```

And of course, breaking factory apart from singleton pattern allows you to easily use polyphormism to create sound managers that might have different implementation detail if needed.

```
public function getManager(id:Object = 'default'):ISoundManager {
  if (managers[id] == null) {
    managers[id] = createManager(id);
  }
  return managers[id];
}

public function createManager(id):ISoundManager {
  if (id == 'something') {
    return new DefaultSoundManager();
  } else {
    return new StreamingSoundManagerWithLasersAndBlackjack();
  }
}

```

---
Tags: actionscript-3, design-patterns
---


title: Can I use a list to spawn enemies?

text:
# Question
Title: Can I use a list to spawn enemies?
I need to have about 10 enemies in my game, can I use a list to spawn them all in?

This is what I was working on but it only spawns 1 enemy in the coordinates of the last added to the list.

Here are the parts from the main game class that I am working on:

```
public class Game1 : Microsoft.Xna.Framework.Game
{
AI enemy;

List<AI> enemies = new List<AI>();

protected override void LoadContent()
{
  Model hero = Content.Load<Model>("Assets/model");

  enemies.Add(enemy = new AI(hero, new Vector3(0, 0, -550)));
  enemies.Add(enemy = new AI(hero, new Vector3(-580, 0, -400)));
}

protected override void Update(GameTime gameTime)
{
  for (int i = 0; i < enemies.Count; i++)
  {
    enemy.Update();
  }
}
}

```

Here is my AI class:

```
 public class AI
{
    public Model model;
    public Matrix world = Matrix.Identity;
    public Vector3 position;
    public Vector3 direction;
    public BoundingSphere collision;
    Matrix[] transform;

    public AI(Model m, Vector3 iPos)
    {
        model = m;
        position = iPos;
        direction = new Vector3(0, 0, -1);
        transform = new Matrix[m.Bones.Count];
        m.CopyAbsoluteBoneTransformsTo(transform);

        foreach (ModelMesh mesh in m.Meshes)
        {
            collision = BoundingSphere.CreateMerged(collision, mesh.BoundingSphere);
        }
    }

    public BoundingSphere getSphere()
    {
        return collision.Transform(world);
    }
    public void Update()
    {
        world = Matrix.CreateWorld(position, direction, Vector3.Up);
    }

    public void Draw(Matrix projection, Matrix view)
    {
        Matrix[] transforms = new Matrix[model.Bones.Count];
        model.CopyAbsoluteBoneTransformsTo(transforms);

        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.EnableDefaultLighting();
                effect.Projection = projection;
                effect.View = view;
                effect.World = transforms[mesh.ParentBone.Index] * world;
            }
            mesh.Draw();
        }
    }
}

```

Thanks for any help.

***EDIT***

I have managed to get two enemies to spawn in but only one of them goes to the correct position, I will update again when I get it fully working.

Here is the code as it stands now, I made no changes to my AI class only on my game1 class:

```
public class Game1 : Microsoft.Xna.Framework.Game
{

List<AI> enemies = new List<AI>();

protected override void LoadContent()
{
  Model hero = Content.Load<Model>("Assets/model");

  enemies.Add(new AI(hero, new Vector3(0, 0, -550)));
  enemies.Add(new AI(hero, new Vector3(-580, 0, -400)));
}

protected override void Update(GameTime gameTime)
{
  enemies[0].Update();
}

protected override void Draw(GameTime gameTime)
{
        for (int i = 0; i < enemies.Count(); i++)
        {
            enemies[i].Draw(camera.projection, camera.view);
        }
}
}

```

Hope this helps any one and I will edit once again when I get it fully working.

***EDIT***

I have posted an answer below containing the working code.

# Answer
> 1 votes
Take a look at:

```
enemies.Add(enemy = new AI(hero, new Vector3(0, 0, -550)));
enemies.Add(enemy = new AI(hero, new Vector3(-580, 0, -400)));

```

Now imagine if I wrote the same thing like this:

```
enemy = new AI(hero, new Vector3(0, 0, -550));
enemies.Add(enemy);
enemy = new AI(hero, new Vector3(-580, 0, -400));
enemies.Add(enemy);

```

See your problem?

You're setting `enemy` to a new enemy. Then you're adding it to the list. Then you're ***changing*** `enemy` to make **another** new enemy, and adding it to the list again.

Now you have two of the same object in the list. Try this:

```
enemies.Add(new AI(hero, new Vector3(0, 0, -550)));
enemies.Add(new AI(hero, new Vector3(-580, 0, -400)));

```

Then, your `for` loop is nonsense. You're just updating the same enemy every time.

Then you can iterate over all your enemies like this:

```
foreach(AI enemy in enemies) {
    enemy.update();
}

```

# Answer
> 0 votes
In your update method you are calling Update() on enemy. Now I don't know the syntax of C#, but you need something like enemies\[i\].Update()

# Answer
> -2 votes
Ok I got it working, I was forgetting to update for every enemy.

Here is the final code:

```
public class Game1 : Microsoft.Xna.Framework.Game
 {

   List<AI> enemies = new List<AI>();

   protected override void LoadContent()
    {
     Model hero = Content.Load<Model>("Assets/model");

     //ADD MORE ENEMIES HERE
     enemies.Add(new AI(hero, new Vector3(0, 0, -550)));
     enemies.Add(new AI(hero, new Vector3(-580, 0, -400)));
    }

    protected override void Update(GameTime gameTime)
    {
     //HERE UPDATE FOR EVERY NEW ENEMY
     enemies[0].Update();
     enemies[1].Update();
    }

    protected override void Draw(GameTime gameTime)
    {
      for (int i = 0; i < enemies.Count(); i++)
      {
        enemies[i].Draw(camera.projection, camera.view);
      }
    }
}

```

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


# Question
Title: How to create high quality and fast portal effect?
EDIT: So I've gotten the portal visual effect working with no performance hit, and I've got the physics set up of objects with rigidbodies moving through portals seamlessly, and objects with character controllers moving through it seamlessly. The only thing I'm trying to figure out now is blending two camera views to get the proper first person transition effect. Any ideas on how I'd blend those two? I'm thinking something using a depth only shader, or the normalized viewport rect. My main problem is calculating that in real time, and with angles.

So I've been working on creating a portal effect in Unity3D. Obviously I've taken Valve's Portal as a great influence to programming this. Currently I'm simply using a camera's rendertexture to get the graphical effect across, and then some code to do the rest. The problem is at 2048x2048 it looks as high quality as Portal's, but causes heavy FPS loss. To solve this I'd either have to lower the texture quality or the number of times I update the texture.

Valve has accomplished a high quality portal effect without causing high frame rate loss. How can I do the same? Does anybody have any good ideas for rendering to a high resolution texture without causing frame loss?

I'm considering making my own code for rendering to textures rather then using Unity's built in system, it's doable but would definitely be a hassle. So any thoughts, ideas, or suggestions are highly appreciated.

# Answer
> 6 votes
After hours of research and programming I figured out how to properly get the visual effect for this. If you'd like to just buy a portal system that works for visuals and most everything else you need, check out the Portalizer Unity Package.

I program in C# and that package is in JS, but the logic behind it is incredibly useful and well thought out. In general I followed his logical thinking, with some tweaks for my game and a first person controller.

Essentially what you do is use a modified version of This water shader/script. Have two mirrors in the scene, and have a camera render what it sees in each reflection to the other mirror. You'll need to create a modified transformation matrix to account for the relations between the two portals. To help decrease the performance hit, read This article about near plane clipping. This will help you render only what needs to be seen through the portal.

I may create a more detailed tutorial with pictures and source once I figure out how to blend the cameras properly for a FPS teleport. Right now I'm too exhausted and busy to write a full tutorial and this should suffice because it gives you most of the code needed.

---
Tags: unity, valve, portals
---


# Question
Title: Let the Game (singleton) handles the Components to add to the game
I have a class 'Bullet' implementing the DrawableGameComponent. What I want is, that the Bullet add itself to the Game. My Game is a Singleton. So I thought I figured it out, but still getting errors.

The Code:

Bullet.cs

```
 public class Bullet : DrawableGameComponent
{
    public Texture2D Texture { get; set; }
    public Vector2 Position { get; set; }
    public Vector2 Speed { get; set; }

    public Bullet(Game game) : base(game)
    {

    }

    public void Shoot()
    {
        Position += Speed;
        Game1.getInstance().addBullet(this);

    }

    protected override void LoadContent()
    {
        Texture = Game.Content.Load<Texture2D>("Bullet");

        base.LoadContent();
    }

    public override void Update(GameTime gameTime)
    {
        Shoot();

        Position = new Vector2(Position.X, Position.Y);
        base.Update(gameTime);
    }

    public override void Initialize()
    {
        Speed = new Vector2(2, 0);
        base.Initialize();
    }

    public override void Draw(GameTime gameTime)
    {
        Game1.spriteBatch.Draw(Texture, Position, Color.White);

        base.Draw(gameTime);
    }
}

```

And in my Game1.cs which is a singleton, i do the following:

```
public void addBullet(Bullet b)
    {
        Components.Add(b);

    }

```

Unfortunately i'm getting this error: Cannot add the same game component to a game component collection multiple times.

What am I doing wrong?

# Answer
The error is quite clear, did you remove it from the game component collection before trying to add it again ?

Now I think this is a bad idea, on your game you will certainly fire many times per second, adding and removing a game component at such rate is not wise. Also a game component *per bullet* is clearly too much.

Maybe you could do something like the following :

* Create a BulletRendererComponent (or whatever you want to call it) and add it to your game,
* Whenever a bullet needs to be fired, notify that component of it
* Finally, this component should be responsible for drawing alive bullets, discard old ones etc ...

**Update**

My previous sayings might not be optimal, it should rather be a sprite renderer than a bullet renderer, here's a quick and dirty sample of how I think I'd do it, try to innovate on this.

```
// This class would render all your sprites
// You would add only one instance of it to your game
class CharacterRenderer : DrawableGameComponent
{
    public List<Character> Characters;

    void Draw()
    {
        foreach (var character in Characters)
        {
            foreach (var element in character.Elements)
            {
                // Add your logic here, checks etc ...
                DrawElement(element);
            }
        }
    }

    private void DrawElement(Element element)
    {
        // IMO that's all there should be on your renderer, i.e. it just renders
    }
}

// Your sprite
class Character
{
    public List<Element> Elements;
}

// Your sprite elements (or parts)
class Element
{
    private Texture Texture;
    private Vector2 Position;
}

```

So whenever the status of your sprite changes (fires for instance) you would modify its elements, so add an element to its elements list whenever he sends a bullet.

Then the renderer would render all sprites elements blindly (should not care more than drawing or not sprites elements). Letting a character draw itself is generally not good, it's probably better to have a renderer of a certain class of items. (separation of concerns ?)

Note that it's not really following good OOP principles, you might a need a bigger infrastructure if you want to really make things clean.

A few principles here might help you here : http://en.wikipedia.org/wiki/Category:Programming\_principles
> 1 votes

---
Tags: xna
---


title: Get average tile color

text:
# Question
Title: Get average tile color
In my 2D game I have TileSet class that loads the texture and creates Rectangle\[\] array which stores each tile coordinates. Pretty basic stuff. Now I'd like to also calculate and store the average color of each tile. How do I do that in XNA/C#?

My goal is to tint the tile with the color based on its value when highlighted. Or maybe there is some other way to achieve similar effect?

# Answer
Mipmap the texture, generate the miplevels, then read from the smallest (1x1) level. What's particularly cool about this is that you can keep the entire process GPU-side (even do it as a vertex texture if you wish) and not have to worry about reading back the colour, then sending it as a shader constant every time you do a texture change.

How do you know which level is the smallest? You don't need to - just use a stupidly high value for the LOD in your tex2Dlod call and it will auto-clamp to the correct level for you.
> 3 votes

---
Tags: xna, sprites, tiles, color
---


# Question
Title: Discover x,y coordinates given set arc distance and rotation
I have a turn-based car simulation. My vehicles have a maximum speed they can travel in a round, as well as a maximum amount they can change their heading over the course of a round. Say, 20 meters and 45 degrees.

Knowing the starting position of a car (x,y coordinates), and its starting heading (orientation), I want to find the end-of-round coordinates for the car turning its maximum amount and moving its maximum speed. (And values in-between, as well!)

There has to be some simple math formula for this, but I haven't found it yet. I also happen to be working in Unity.

# Answer
> 7 votes
Let's say you want its position after time *t*. Multiply speed by time, an your have your arc length *l*. Multiply the turn speed by time to get the total turn angle *a* (you'll need this in radians). Use these to get your turn radius *r*.

```
r = l / a

```

Using the turn radius, you can find the center *c* of your turning arc by moving left from its starting position, if turning left, or by moving right from its position. To find a certain position on the edge of a circle, you'll need to use some trig. Assuming you were oriented as pictured:

```
    newX = c.x + r * cos(a);
    newY = c.y + r * sin(a);

```

Of course, this only works if you start facing forward and are turning left, but using relative positioning and flipping it for turning right, we can make it work for every situation. In UnityScript:

```
//turnSpeed assumed to be in radians
function CalculateNewPosition(speed : float, turnSpeed : float, t : float){
    var l = speed * t;
    var a = Mathf.Abs(turnSpeed) * t;
    var r = l/a;
    //start by assuming the vehicle is at the origin
    var c : Vector3 = Vector3.zero;
    var newPos : Vector3 = c;
    if(turnSpeed>0){ //turning left
        c.x -= r;
        newP.x = c.x+r*Mathf.Cos(a);
    } else{ //turning right
        c.x += r;
        newPos.x = c.x-r*Mathf.Cos(a);
    }
    newPos.y = r*Mathf.Sin(a);

    //finally, transform it relative to the vehicle (might mess up if your vehicle
    //isn't at a 1x1x1 scale)
    return transform.TransformPoint(newPos);
}

```

# Answer
> 0 votes
You'll likely find that iteration will be the simplest to implement. Essentially you're going to use a `for` loop, and step along the car's path. You can use the same methods that you use for updating the car's position in game.

You will need to ensure that you have enough iterations to maintain reasonable accuracy, but you may not want the same number of points in your sample. You can just iterate more often than you place points in your list.

Take the amount of time you want to look ahead and divide it by the number of iterations you want to perform. This will give you your time step for each iteration. The smaller the time step, the more accurate the result will be. This is similar to a Riemann sum. You'll get a more accurate picture with finer resolution.

For example, if we wanted to look ahead 10 seconds:

```
Vector3 simulationPosition = new Vector3(carCurrentPosition);
Vector3 simulationRotation = new Vector3(carCurrentRotation);
List<Vector3> dataPoints = new List<Vector3>(); //a list to hold all our data points
//drawing a line through all these points will give you your anticipated path
float secondsInMS = 10000;
int iterations = 1000;
float timeStep = secondsInMS/iterations;
for(int i = 0; i < 1000; i++) {
    float deltaTime = (float) (i * timeStep);
    //update the simulation position
    //small time step means more frequent updates and more accurate final position
    updatePositionAndRotation(simulationPosition, simulationRotation, velocity, deltaTime);

    if(i%50 == 2) { //mod by 50 so that our 1000 iterations turns into 20 data points
         dataPoints.add(new Vector3(simulationPosition));
    }
}

```

Where `updatePositionAndRotation` takes the simulation's current position and rotation and calculates the new position and rotation based on the velocity and delta time. You likely have a function for this already, so use that here to update the simulation values.

---
Tags: mathematics, unity, projectile-physics
---


title: camera2d class will not work

text:
# Question
Title: camera2d class will not work
using System; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Input.Touch;

here is the ICamera2D

```
  public interface IFocusable
{
Vector2 Position { get; }
}

 public interface ICamera2D
{
/// <summary>
/// Gets or sets the position of the camera
/// </summary>
/// <value>The position.</value>
Vector2 Position { get; set; }

/// <summary>
/// Gets or sets the move speed of the camera.
/// The camera will tween to its destination.
/// </summary>
/// <value>The move speed.</value>
float MoveSpeed { get; set; }

/// <summary>
/// Gets or sets the rotation of the camera.
/// </summary>
/// <value>The rotation.</value>
float Rotation { get; set; }

/// <summary>
/// Gets the origin of the viewport (accounts for Scale)
/// </summary>
/// <value>The origin.</value>
Vector2 Origin { get; }

/// <summary>
/// Gets or sets the scale of the Camera
/// </summary>
/// <value>The scale.</value>
float Scale { get; set; }

/// <summary>
/// Gets the screen center (does not account for Scale)
/// </summary>
/// <value>The screen center.</value>
Vector2 ScreenCenter { get; }

/// <summary>
/// Gets the transform that can be applied to
/// the SpriteBatch Class.
/// </summary>
/// <see cref="SpriteBatch"/>
/// <value>The transform.</value>
Matrix Transform { get; }

/// <summary>
/// Gets or sets the focus of the Camera.
/// </summary>
/// <seealso cref="IFocusable"/>
/// <value>The focus.</value>
IFocusable Focus { get; set; }

/// <summary>
/// Determines whether the target is in view given the specified position.
/// This can be used to increase performance by not drawing objects
/// directly in the viewport
/// </summary>
/// <param name="position">The position.</param>
/// <param name="texture">The texture.</param>
 /// <returns>

 ///     <c>true</c> if the target is in view at the specified position; otherwise,    < c  >false</c>.
/// </returns>
bool IsInView(Vector2 position, Texture2D texture);
}

```

This is my main Camera2D Class

```
  public class Camera2D : GameComponent, ICamera2D
 {
private Vector2 _position;
protected float _viewportHeight;
protected float _viewportWidth;

public Camera2D(Game game)
    : base(game)
{}

#region Properties

public Vector2 Position
{
    get { return _position; }
    set { _position = value; }
}
public float Rotation { get; set; }
public Vector2 Origin { get; set; }
public float Scale { get; set; }
public Vector2 ScreenCenter { get; protected set; }
public Matrix Transform { get; set; }
public IFocusable Focus { get; set; }
public float MoveSpeed { get; set; }

#endregion

/// <summary>
/// Called when the GameComponent needs to be initialized.
/// </summary>
public override void Initialize()
{
    _viewportWidth = Game.GraphicsDevice.Viewport.Width;
    _viewportHeight = Game.GraphicsDevice.Viewport.Height;

    ScreenCenter = new Vector2(_viewportWidth/2, _viewportHeight/2);
    Scale = 1;
    MoveSpeed = 1.25f;

    base.Initialize();
}

public override void Update(GameTime gameTime)
{
    // Create the Transform used by any
    // spritebatch process
    Transform = Matrix.Identity*
                Matrix.CreateTranslation(-Position.X, -Position.Y, 0)*
                Matrix.CreateRotationZ(Rotation)*
                Matrix.CreateTranslation(Origin.X, Origin.Y, 0)*
                Matrix.CreateScale(new Vector3(Scale, Scale, Scale));

    Origin = ScreenCenter / Scale;

    // Move the Camera to the position that it needs to go
    var delta = (float) gameTime.ElapsedGameTime.TotalSeconds;

    _position.X += (Focus.Position.X - Position.X) * MoveSpeed * delta;
    _position.Y += (Focus.Position.Y - Position.Y) * MoveSpeed * delta;

    base.Update(gameTime);
}

/// <summary>
/// Determines whether the target is in view given the specified position.
/// This can be used to increase performance by not drawing objects
/// directly in the viewport
/// </summary>
/// <param name="position">The position.</param>
/// <param name="texture">The texture.</param>
/// <returns>
///     <c>true</c> if [is in view] [the specified position]; otherwise, <c>false</c>.
/// </returns>
public bool IsInView(Vector2 position, Texture2D texture)
{
    // If the object is not within the horizontal bounds of the screen

    if ( (position.X + texture.Width) < (Position.X - Origin.X) || (position.X) >      (Position.X + Origin.X) )
        return false;

    // If the object is not within the vertical bounds of the screen
    if ((position.Y + texture.Height) < (Position.Y - Origin.Y) || (position.Y) > (Position.Y + Origin.Y))
        return false;

    // In View
    return true;
}

 Here is my draw method i cannot get camera.transform to work properly

 // cam.Zoom = 2.0f // Example of Zoom in
 // cam.Zoom = 0.5f // Example of Zoom out

  public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
  {

      spriteBatch.Begin(BlendState.AlphaBlend, SpriteSortMode.FrontToBack,
          null,
          null,
          null,
          null,
          Camera.Transform);

    spriteBatch.End();

  }
}

```

# Answer
> 3 votes
The problem with your Camera 2D is how you create the translation. A matrix has to be calculated in the right order and that is or "(Origin), Scale, Rotation, Translation". Otherwise it could rotate around the wrong axis.

```
2D Transformation = Scale * Rotation * Translation

1. Scale the object to the correct size, say the width and height of the window
   If it's scaled 2x it will contain half the size of the objects on screen

2. Now you have the double the radius of the object, you rotate it 90 degrees
   It can now rotate the object according to it's size, so an object half width
   and half height will get another "translation" position than if wasn't scaled or
   rotated. Normally the origin is the 0,0 point but when scaling and rotating
   it will change, what you set as 0,0 after rotating and scaling will be somewhere else.

3. Translation, you translate the position according to it's rotation and scale

```

In your case:

```
1. Translate the position
   It's at say 0,0

2. Rotate the object along it's size without scaling it
   Rotate screen 180 degrees, which means 0, 0 is at Width, Height

3. Scale the object up (to say 2x)
   Then scale it which fails because the rotation will rotate around an invalid size
   Instead it will rotate around the wrong axis because the size is changed after
   The rotation has occured.

```

This is a simple implementation of a 2D Camera with Origin, Scale, Rotation and Translation.

```
public class Camera2D
{
    public Camera2D()
    {
        Origin = Vector2.Zero;
        Position = Vector2.Zero;
        Scale = 1f;
        Rotation = 0;
    }

    public void Move(float x, float y) { Position += new Vector2(x, y); }
    public void Zoom(float value) { Scale = Math.Max(Scale + value, 0.01f); }
    public void Rotate(float value) { Rotation += value; }
    public void SetOrigin(Vector2 originPosition) { Origin = originPosition; }
    public void SetPosition(Vector2 newPosition) { Position = newPosition; }

    private Vector2 position;
    public Vector2 Position
    {
        get { return position; } protected set { position = value; }
    }

    private Vector2 origin;
    public Vector2 Origin
    {
        get { return origin; } protected set { origin = value; }
    }

    public float Rotation { get; protected set; }
    public float Scale { get; protected set; }

    public Matrix Transformation
    {
        get
        {
            return
                Matrix.CreateTranslation(Origin.X, Origin.Y, 0) *
                Matrix.CreateScale(Scale) *
                Matrix.CreateRotationZ(MathHelper.ToRadians(Rotation)) *
                Matrix.CreateTranslation(Position.X, Position.Y, 0);
        }
    }

    public Matrix TransformationNoOrigin
    {
        get
        {
            return
                Matrix.CreateScale(Scale) *
                Matrix.CreateRotationZ(MathHelper.ToRadians(Rotation)) *
                Matrix.CreateTranslation(Position.X, Position.Y, 0);
        }
    }
}

```

A concrete example:

```
ScreenWidth = 1280; ScreenHeight = 720;

Matrix transformation =
Matrix.CreateTranslation(-(ScreenWidth /2), -(ScreenHeight/2), 0) *
Matrix.CreateScale(1) *
Matrix.CreateRotationZ(MathHelper.ToRadians(180f)) *
Matrix.CreateTranslation(ScreenWidth /2, ScreenHeight/2, 0);

```

The origin is at the middle of the screen, which is where it will start to rotate So take a paper and rotate around the middle, after rotating it 180 degrees it will be upside down. It will look as if it hasn't moved at all but it will be upside down.

Set origin to 0, 0 and rotate it. If you rotate the paper at the top left corner, it will now rotate so that it's so to speak at X = -ScreenWidth, Y = -ScreenHeight. It will be flipped so it's to your left and above your hand.

So the matrix transformation above is for a screen that is upside down.

If you rotate it and then later scale it, the paper will be rotating around the wrong axis because it's size is incorrect. So it's important for it to be calculated in the correct order.

---
Tags: xna, c#, graphics, camera, platformer
---


# Question
Title: XNA effect lighting like basic effect lighting
Is it possible to make lighting in a normal effect work like the lighting in the basic effect?

With a basic effect it's really easy:

BasicEffect effect; effect.EnableDefaultLighting();

# Answer
You can make any configuration of `BasicEffect` yourself, such as the so-called "default lighting". But really, XNA's `BasicEffect` is not basic at all. Having so many different options means that the actual shader is constructed of many interchangeable fragments. It's quite complex internally.

However, if you don't want your shader to work in a variety of ways, it's much simpler. You can implement your own so that it combines a specific set of features and always uses them. Directional lighting plus ambient lighting is very easy, and google will surely give you a workable example.

You will have to do the work that the built-in class does for you when it prepares to use the shader. You will need to assign a light direction and color, and define and ambient color and intensity. It's more lines of code than using `BasicEfect`, but the shader will be your own to customize and experiment as you please.
> 2 votes

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


# Question
Title: Why doesn't onSurfaceCreated ever run in this code?
I create my game element this way in my activity:

```
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  mGame = new Game(this);
  mGame.bootstrap();
  setContentView(CommonObject.sCommonParams.touch);
  mGame.loadTextures();
}

```

Then in my bootstrap I create my GLsurfaceView this way: (callingActivity is the this I passed when I created mGame)

```
CommonObject.sCommonParams.openGLView = new GLSurfaceView(callingActivity);
CommonObject.sCommonParams.openGLView.setRenderer(new GameRenderer());
CommonObject.sCommonParams.openGLView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);

```

Is it because I pass GLSurfaceView to a static object that it's not working?

# Answer
Turns out I had to

```
setContentView(CommonObject.sCommonParams.openGLView);

```

for onSurfaceCreated to run. Which is sad since I was trying to avoid doing that.
> 0 votes

---
Tags: android, opengl-es
---


# Question
Title: Integrating Scene Graphs and Physics Engines
For some specific reasons, i will have to use a graphic engine based on Scene Graphics with a Physic Engine without this concept. I was thinking about a clear way to integrate both representation but ... i did not found something that convinces me.

The problem that always appears is that the scene graph is a hierarchical structure and the Physical engine is not. The position of a node in a scene graph depends of its parents, and when the parents changes its location, the son must be updated, but the son can be physically simulated (its position is always in global coordinates) ...

(there are lots of others situations similar to this ... - hard to calculate relative positions/orientations and keep both worlds in sync)

The only way i found is to have all the physically simulated objects as direct sons of the root node of the scene graph (no relative positions at all) In the physically simulated nodes, we dont propagate relative positions/orientations, each of this nodes only store world positions/orientations, not relatives. But this constraint sounds a little to much and probably will kill (a bit =P) some of beneficts of scene graph like cullings. (after all, most of my scene wont follow any hierarchy ... )

how people usually solve this kind of situations ?

# Answer
> 3 votes
I have been in the same situation as you and this is how I solved it.

Before that, some clarification:

* In my SceneGraph each SceneNode keeps track of its own local transform (scale, rotation, translation) and a concatenated transform (world).
* SceneNodes can have multiple components.
* BEPUPhysics is the physics library being used, its entity transforms are in world space

Example)

I have a wrapper component, BoundingVolume, for the Physics entities which can be attached to a SceneNode. When the component is initialized it creates the Physics entity and registers it with the Physics System.

The BoundingVolume component can then calculate transforms in two ways in the update loop:

* Update SceneNode transform (default) - The SceneNode's **local transform** (Physics entity worldtransform - parentNode.worldtransform) is updated to so its world transform match the Physics entity's World transform
* Update Physics entity transform - The Physics entity's transform is modified to match the SceneNode's **world transform**

# Answer
> 2 votes
You are approaching the problem from the wrong side. You don't have a scene graph and need to integrate physic engine. You are using a rendering library that uses a scene graph and want to also use a physics library that does not use a scene graph.

How about you step one step back and stop thinking about the solution domain (scene graph) and start thinking about the problem domain?

I don't know what you are simulation and want to represent. But if you look at the real world, there are no scene graphs, only objects. These objects may be connected to each other or not, but any form of hierarchy is totally artificially added.

How about you build you high level logic in the form of a system independent way. You have a "cloud" of objects and these objects then use graphic library and physics library, to actually do something useful. These objects will also arbitrate the data movement from one library into the other (physics -\> rendering). The mapping does not have to be 1:1 but can be m:n. One high level object may have an entire subtree in the scene graph and multiple bodies and geometries in the physics simulation.

This also works well when adding additional things like a sound library or a networking library.

You probably even don't need any organisational structure (i.e. Octree) for the high level objects, because their interaction and spacial hierarchy are not such a big deal. But you must see for yourself and apply it to your problem.

# Answer
> 0 votes
> after all, most of my scene wont follow any hierarchy ...

Since this is the case, I wouldn't keep using a hierarchical scene graph. I'd break down the world using an octree. The benefits of using an octree are that you get your frustum culling and LOD determination without needing to fit every object into a hierarchy. If you want, of course, you can still have object hierarchies like in a traditional scene graph.

On the flipside, octrees are a little more difficult to maintain, especially considering objects whose bounding volumes may lie inside multiple octants, but they integrate much more easily with physics simulations. Just remember to choose an appropriate maximum subdivision level to avoid having a lot of objects in more than one octant.

---
Tags: physics, graph, scene
---


# Question
Title: How to draw a repeated image, but constrain it to a 2D circle in Java?
How would you go about repeating a texture to fill a circle. To be specific: I am using a 5x5 .PNG as the thing or object that will fill the circle. I want to use that to fill my tetrain. At the moment I am having problems making the terrain where it will fill the circle, but rounded.

My specific problem with the generation is that it fills it, however it is not rounded because it goes all the way to the max y at all points. The x axis however is not a problem at the moment. My code right now for the generation of the terrain is so:

```
for(float x = mapEdge.getMinX() ; x < mapEdge.getMaxX() ;   x += 5 ){
            for(float y = mapEdge.getCenterY() ; y > mapEdge.getMinY(); ){
                y -=5;
                g.drawImage(grass,x, y);

        }

```

# Answer
> 1 votes
You can use Graphics.setClip() to set arbitrary clipping shape. After that all image drawing calls will be clipped inside this shape.

```
Shape oldClip = g.getClip();
g.setClip(new Ellipse2D.Float(x, y, diameter, diameter));
// Draw the images here
g.setClip(oldClip);

```

---
Tags: java
---


# Question
Title: HLSL Multitexturing with more than 4 textures
I've come up with an idea that should work in multitexturing a terrain with more than 4 textures, up to a 64 if a supported ShaderModel is used.

I'm trying to use the RGBA color values as both values for blending and identifying which textures should be used.

I'm currently using 16 per textures. Each color has 256 values (R, G, B, A) so by identifying:

**Texture 1** Red = 0-16, Blend = (Value / (16 - (16 * 0)) **Texture 2** Red = 17-32, Blend = (Value / (16 - (16 * 1))

and by changing from 16 to 32 the blend is better because more rgba values can be included.

...and the closer that value is to 16 the higher blend value it gets with that texture.

All I'm stuck at is this calculation because no matter what I do I can't seem to convert the values correctly or get the values in the right way.

```
// VS_OUTPUT contains Position, TextureCoordinates and Color

float4 MultiTexturing_Pixel(VS_OUTPUT input) : COLOR
{
    float4 color = float4(0,0,0,0);

    int scale = 16;

    float red = input.Color.r * 256;

    // gets an index between 0~16, add +16 for each color after this
    int redIndex = ceil(red / scale);
    int redValue = 0;

    if ( (red % scale) == 0)
    {
        redValue = 1.0;
    }
    else
    {
        redValue = (color % scale) / scale; // should give a value between 0.0 and 1.0
    }

    // function with alot of ifs that checks the index and returns the Texture Sampler
    color += GetColor(index, value, input.TexCoord);

    // and the same for blue, green, alpa
    // but add blueIndex + 16, greenIndex + 32, alphaIndex + 48

    return color;
}

```

The math is there, but converting values back and forth is really the problem and since HLSL is basic C it's weird that it doesn't support basic math calculations.

Since I'm not that good at how the calculations should work I hope someone can provide an answer on how to actually perform the calculations below.

I've tried every possible way, all day and I'm totally out of ideas.

**UPDATE: Problems with the calculations:**

As far as my math knowledge goes, this is how it should go.

A color value is 0~255 (256) In HLSL this translates to a value of 0.0-1.0, which means 32 = (32 / 256) = 0.125

**Step 1** I set the Vertex color to:

```
new Color(32, 0, 0, 0)

```

**Step 2** In the pixel shader this value would translate to the second texture this way:

```
float each = 16.0;
float max = 256.0;

float redIndex = (input.Color.r * max) / each;

```

At this point redIndex should be "2.0" if Color value is (32,0,0,0) But it's not. Why? This is the flow for me in any other programming language:

```
float each = 16.0;
float max = 256.0;

float redIndex = 0.125 * 256; // = 32
      redIndex /= 16.0; // = 2.0

int index = redIndex; // = 2
int index = ceil(redIndex); // = 2

```

If I try to use ceil(redIndex) nothing better happens, it still can't get that "index" value. And this is basic MATH. And ceil (available from SM v1.1) takes the value up to the nearest integer, so if it's 1.9 == 2, 0.1 = 1 and so on. But it cannot do this. Because the values are wrong and the calculation is wrong.

**Step 3** To get a value between 0-1 for texture, the closer you are to 16, 32, 48, 64 the more color from texture 1, 2, 3, 4 you get. So: 16 = 1, 8 = 0.5 4 = 0.25

```
float redValue = 0.0;
float red = input.Color.r * max;

if ( fmod(red, each) == 0.0) // or (16.0 % 16.0), which basically is 0.0
{
    redValue = 1.0;
}
else
{
    redValue = fmod(red, each) / each;
            // or (8.0 % 16.0) / 16.0
            // which is (8 % 16.0) = 8 and 8 / 16 = 0.5
            // which means the texture should be blended 0.5 or 50%.
}

```

**Step 4** And finally by using the function GetColor I collect colors for each texture.

```
color += GetColor(index, value, input.TexCoord);

// and then do the same for green, blue, alpha values only add + 16
// because colors at (0,16,0,0) would be 16 + 1
// and color (0,0,32,0) would be 32 + 2
// and color (0,0,0,64) would be 48 + 4

```

# Answer
> 0 votes
Since this "idea" of mine wasn't working at all I just had an idea that silly enough worked. I've been looking for something like this for some while without finding it.

This works so that you can multitexture a terrain with 16 textures or less.

Here is as close as an answer that this question gets:

**HLSL SHADER**

http://pastebin.com/mbneZxJ6

**C# Code**

```
public struct MultiTextureVertex : IVertexType
{

    public MultiTextureVertex(Vector3 position, Vector3 normal, Vector2 textureCoordinate, uint texture)
    {
        Position = position;
        TextureCoordinate = textureCoordinate;

        A = new Color(0, 0, 0, 0);
        B = new Color(0, 0, 0, 0);
        C = new Color(0, 0, 0, 0);
        D = new Color(0, 0, 0, 0);

        Normal = normal;

        switch (texture)
        {
            case 1:
                A.R = 255;
                break;
            case 2:
                A.G = 255;
                break;
            case 3:
                A.B = 255;
                break;
            case 4:
                A.A = 255;
                break;
            case 5:
                B.R = 255;
                break;
            case 6:
                B.G = 255;
                break;
            case 7:
                B.B = 255;
                break;
            case 8:
                B.A = 255;
                break;
            case 9:
                C.R = 255;
                break;
            case 10:
                C.G = 255;
                break;
            case 11:
                C.B = 255;
                break;
            case 12:
                C.A = 255;
                break;
            case 13:
                D.R = 255;
                break;
            case 14:
                D.G = 255;
                break;
            case 15:
                D.B = 255;
                break;
            case 16:
                D.A = 255;
                break;
        }
    }

    public MultiTextureVertex(Vector3 position, Vector3 normal, Vector2 textureCoordinate, Color a, Color b, Color c, Color d)
    {
        Position = position;
        TextureCoordinate = textureCoordinate;

        A = a;
        B = b;
        C = c;
        D = d;

        Normal = normal;
    }

    public void SetTexture(uint texture)
    {
        A = new Color(0, 0, 0, 0);
        B = new Color(0, 0, 0, 0);
        C = new Color(0, 0, 0, 0);
        D = new Color(0, 0, 0, 0);

        switch (texture)
        {
            case 1:
                A.R = 255;
                break;
            case 2:
                A.G = 255;
                break;
            case 3:
                A.B = 255;
                break;
            case 4:
                A.A = 255;
                break;
            case 5:
                B.R = 255;
                break;
            case 6:
                B.G = 255;
                break;
            case 7:
                B.B = 255;
                break;
            case 8:
                B.A = 255;
                break;
            case 9:
                C.R = 255;
                break;
            case 10:
                C.G = 255;
                break;
            case 11:
                C.B = 255;
                break;
            case 12:
                C.A = 255;
                break;
            case 13:
                D.R = 255;
                break;
            case 14:
                D.G = 255;
                break;
            case 15:
                D.B = 255;
                break;
            case 16:
                D.A = 255;
                break;
        }
    }

    public Vector3 Position;
    public Vector3 Normal;
    public Vector2 TextureCoordinate;
    public Color A, B, C, D;

    public static readonly VertexDeclaration VertexDeclaration = new VertexDeclaration
    (
        new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
        new VertexElement((sizeof(float) * 3), VertexElementFormat.Vector3, VertexElementUsage.Normal, 0),
        new VertexElement((sizeof(float) * 6), VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0),
        new VertexElement((sizeof(float) * 8), VertexElementFormat.Color, VertexElementUsage.Color, 0),
        new VertexElement((sizeof(float) * 8) + (sizeof(byte) * 4), VertexElementFormat.Color, VertexElementUsage.Color, 1),
        new VertexElement((sizeof(float) * 8) + (sizeof(byte) * 8), VertexElementFormat.Color, VertexElementUsage.Color, 2),
        new VertexElement((sizeof(float) * 8) + (sizeof(byte) * 12), VertexElementFormat.Color, VertexElementUsage.Color, 3)

    );

    VertexDeclaration IVertexType.VertexDeclaration
    {
        get { return MultiTextureVertex.VertexDeclaration; }
    }
}

```

Then simply create a vertex with this Vertex type, say a plane or anything and it can use 16 textures as long as they're set.

# Answer
> 1 votes
It's really difficult to understand what you're trying to do and what's going wrong with it. It's not the amount of information, but the way in which you wrote it that makes it difficult to understand. I'll give it a try though.

As far as I understood, you want to blend multiple textures. The blending factors are encoded inside the RGBA values of a different texture, and you want a way to extract these values from your pixel shader.

If that is right, supposing you encode 8 blending factors in RGBA8, 2 in each component using 4 bits each, you can do:

```
float blendFactor0 = ((input.Color.r * 256) % 16) / 16;
float blendFactor1 = ((input.Color.r *  16) % 16) / 16;
float blendFactor2 = ((input.Color.g * 256) % 16) / 16;
float blendFactor3 = ((input.Color.g *  16) % 16) / 16;
float blendFactor4 = ((input.Color.b * 256) % 16) / 16;
float blendFactor5 = ((input.Color.b *  16) % 16) / 16;
float blendFactor6 = ((input.Color.a * 256) % 16) / 16;
float blendFactor7 = ((input.Color.a *  16) % 16) / 16;

```

You can also do this in integer math using bitwise operations (probably unnecessary since you're on the GPU)

```
int encodedBlendR = input.Color.r * 256;
int encodedBlendG = input.Color.g * 256;
int encodedBlendB = input.Color.b * 256;
int encodedBlendA = input.Color.a * 256;

float blendFactor0 = ((encodedBlendR >> 0) & 0xF) / 16;
float blendFactor1 = ((encodedBlendR >> 4) & 0xF) / 16;
float blendFactor2 = ((encodedBlendG >> 0) & 0xF) / 16;
float blendFactor3 = ((encodedBlendG >> 4) & 0xF) / 16;
float blendFactor4 = ((encodedBlendB >> 0) & 0xF) / 16;
float blendFactor5 = ((encodedBlendB >> 4) & 0xF) / 16;
float blendFactor6 = ((encodedBlendA >> 0) & 0xF) / 16;
float blendFactor7 = ((encodedBlendA >> 4) & 0xF) / 16;

```

**edit:** I just reread the first part of your question:

> Texture 1 Red = 0-16, Blend = (Value / (16 - (16 * 0)) Texture 2 Red = 17-32, Blend = (Value / (16 - (16 * 1)) and by changing from 16 to 32 the blend is better because more rgba values can be included.

You can't do this. If you want 16 values, you will need 4 bits, so you can store two values per 8-bit element. One value will be the first hex digit, and the other one the second. If you want 32 values, you will need 5 bits, so you can only store one value per 8-bit element.

---
Tags: xna, textures, shaders, hlsl
---


# Question
Title: Incorrect rotations using openGL GLM and shaders
The goal of my program is to display a simple colored triangle rotating on the Y axis without any translation. I'm using the GLM library. The problem is that the transformations of my triangle are not correct : it has a strange and not logical behaviour. Here's my c++ code plus the vertex shader and fragment shader code :

C++ code :

```
float angle = 0.0f;

struct Vertex
{
    float x, y, z;
};

static Vertex vertices[9] =
{
    -1.000000f, 0.000000f, 0.000000f,
    0.000000f, 1.000000f, 0.000000f,
    1.000000f, 0.000000f, 0.000000f
};

static Vertex colors[9] =
{
    1.000000f, 0.000000f, 0.000000f,
    0.000000f, 1.000000f, 0.000000f,
    0.000000f, 0.000000f, 1.000000f
};

[...]

int
main(int ac, char **av)
{
    bool            continuer = true;
    SDL_Event       event;
    GLuint          vboID[2];
    GLuint          programID = 0;

    //SDL window initialization

    SDL_Init(SDL_INIT_VIDEO);
    SDL_WM_SetCaption("VBO tests",NULL);
    SDL_SetVideoMode(WIDTH, HEIGHT, 32, SDL_OPENGL);

    //Viewport initialization

    glViewport(0, 0, WIDTH, HEIGHT);

    //Projection initialization

    glm::mat4 projection = glm::mat4(1.0f);
    projection = glm::perspective<GLfloat>(60.0f, (float)(WIDTH/HEIGHT), 1.0f, 1000.0f);

    //View initialization

    glm::mat4 view = glm::lookAt<GLfloat>(glm::vec3(0.0f, 0.0f, 8.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));

    glewInit();

    //Shaders initialization

    programID = initShaders("triangle.vert", "triangle.frag");

    //Main loop

    while (continuer)
    {
        eventListener(&event, &continuer);

        glClearDepth(1.0f);
        glClearColor(0.13f, 0.12f, 0.13f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glUseProgram(programID);

        //Model transformations

        glm::mat4 model = glm::mat4(1.0f);
        model *= glm::translate(model, glm::vec3(0.0f, 0.0f, 0.0f));
        model *= glm::rotate(model, angle, glm::vec3(0.0f, 1.0f, 0.0f));

        glm::mat4 ModelViewMatrix = model * view;
        glm::mat4 ModelViewProjectionMatrix = projection * ModelViewMatrix;

        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vertices);
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, colors);

        glEnableVertexAttribArray(0);
        glEnableVertexAttribArray(1);

        glUniformMatrix4fv(glGetUniformLocation(programID, "ModelView"), 1, GL_TRUE, glm::value_ptr(ModelViewMatrix));
        glUniformMatrix4fv(glGetUniformLocation(programID, "MVP"), 1, GL_TRUE, glm::value_ptr(ModelViewProjectionMatrix));

        glDrawArrays(GL_TRIANGLES, 0, 3);

        glDisableVertexAttribArray(1);
        glDisableVertexAttribArray(0);

        glUseProgram(0);

        angle += 0.020f;

        glFlush();
        SDL_GL_SwapBuffers();
    }

    SDL_Quit();
    return (0);
}

```

Vertex shader code :

```
#version 330

in vec3 VertexPosition;
in vec3 VertexColor;

uniform mat4 ModelViewMatrix;
uniform mat4 MVP;

out vec3 Color;

void main()
{
    Color = VertexColor;

    gl_Position = MVP * vec4(VertexPosition, 1.0f);
}

Fragment shader code :

#version 330

in vec3 Color;
out vec4 FragColor;

void main() {
    FragColor = vec4(Color, 1.0);
}

```

When I declare just a simple matrix rotation for the model, I send it to the vertex shader and I use it as MVP and it works. But when I add the projection matrix + the view matrix it does not work correctly. Normally, the triangle should be rotating at the center of the screen.The current animation shows the triangle appearing on the right of the screen and disappearing on the left side.

Does anyone can help me, please ?

Thanks in advance for your help.

# Answer
Just set 'the view matrix' to identity and then translate to like -6.0 on the z axis.

You are not using lookAt() correctly. The first paramater is the position you are at (the camera) and the second is where you look at.
> 2 votes

---
Tags: opengl, shaders, glm
---