# Question
Title: How to syncronize two animations without delays
I have one character idle animation running inside a game in a loop, over and over again. A a certain time I trigger another animation to be played, for the same character.

The second animation won't play immediately, as will be a discontinuity in my character animation. First I wait for the idle animation to finish and then I play my second animation. Now I have a smooth, continuous animation, BUT I have introduced a delay between my action and character animation.

If I play the second animation right away as it is triggered, the character animation won't be continuous and smooth.

I was thinking on breaking the idle animation in small pieces and also to have the same number of second action animations to match the last frame of the idle pieces. This won't solve the delay completely, only will minimize it a bit.

So it's a magic formula of how can I get rid of this delay?

Thanks.

# Answer
If you're looking for responsiveness then you'll have to blend the animation, their lot's of tricks in making your blends looks clean. Foot placement is the biggest culprit for weird blends (if two feet slide it looks really off).

One trick is that at least one foot needs to be planted in the same spot as the first frame of your next animation. If it's the back foot then you have you more time for a smooth blend. You can also transition to left foot or right foot forward first. You can have a intermediate animation that is synced with your idle animation the basically has a planted foot, then you blend to that one then blend to your walk.

It's always easier to figure out some clever animations then it is to create some crazy rules for your animation system.
> 0 votes

# Answer
Depending on what the idle animation is, you could mark some frames as "close enough" to the ending position so you can cut it short at these points, instead of waiting until the very end. At anything above 10 FPS you probably won't notice anything anyway.

If you want to get very fancy, you could have "transition points" for every pair of animations you're interested in... say, you could go from frame 7 of Idle to frame 3 of Kicking Ball, instead of playing them one after the other.

Source: I spent countless hours trying to get smooth transitions for Wild West Wendy. We made bigger and better games after that one, but this one may be the one I'm the most proud of - in no small part because of the amount of detail, including the animations, we put into it (sorry, nostalgic moment!)
> 0 votes

---
Tags: animation
---


# Question
Title: How do I keep user input and rendering independent of the implementation environment?
I'm writing a Tetris clone in JavaScript. I have a fair amount of experience in programming in general, but am rather new to game development.

I want to separate the core game code from the code that would tie it to one environment, such as the browser.

My quick thoughts led me to having the rendering and input functions external to my main game object. I could pass the current game state to the rendering method, which could render using `canvas`, elements, text, etc. I could also map input to certain game input events, such as *move piece left*, *rotate piece clockwise*, etc.

I am having trouble designing how this should be implemented in my object.

Should I pass references to functions that the main object will use to render and process user input? For example...

```
var TetrisClone = function(renderer, inputUpdate) {
    this.renderer = renderer || function() {};
    this.inputUpdate = input || function() {};
    this.state = {};
};

TetrisClone.prototype = {
    update: function() {

       // Get user input via function passed to constructor.
       var inputEvents = this.inputUpdate();

       // Update game state.

       // Render the current game state via function passed to constructor.
       this.renderer(this.state);

    }
};

var renderer = function(state) {
    // Render blocks to browser page.
}

var inputEvents = {};

var charCodesToEvents = {
    37: "move-piece-left"
    /* ... */
};

document.addEventListener("keypress", function(event) {
    inputEvents[event.which] = true;
});

var inputUpdate = function() {
   var translatedEvents = [],
       event,
       translatedEvent;

   for (event in inputEvents) {
       if (inputEvents.hasOwnProperty(event)) {
           translatedEvent = charCodesToEvents[event];
           translatedEvents.push(translatedEvent);
       }
   }

   inputEvents = {};

   return translatedEvents;

}

var game = new TetrisClone(renderer, inputUpdate);

```

Is this a good game design? How would you modify this to suit best practice in regard to making a game as platform/input independent as possible?

# Answer
> 1 votes
In my current engine, I have a few globals (all inside the main closure, of course):

```
// variables
var game;
var input;
var screen;
var sound;

```

Which are pointers to the main controller on independent subsystems, one of which is the game subsystem. They're all singletons, instantiated from their respective pseudoclasses:

```
function Game() {}
function Input() {}
function Screen() {}
function Sound() {}

```

They work independently, calling each other through their global pointers when necessary, through a high-level set of public methods, such as `game.reset()`, `sound.play()`, `input.hasCandidate()`, etc.

Let me know if you need more information about this design.

---
Tags: architecture, javascript
---


title: HTML5/JS - Choppy Game Loop

text:
# Question
Title: HTML5/JS - Choppy Game Loop
I have been experimenting with HTML5/JS, trying to create a simple game when I hit a wall. My choice of game loop is too choppy to be actually of any use in a game.

I'm trying for a fixed time step loop, rendering only when required. I simply use a `requestAnimationFrame` to run `Game.update` which finds the elapsed time since the last update, and calls `State.update` to update and render the current state.

```
State.prototype.update = function(ms) {
    this.ticks += ms;

    var updates = 0;
    while(this.ticks >= State.DELTA_TIME && updates < State.MAX_UPDATES) {
          this.updateState();

          this.updateFrameTicks += State.DELTA_TIME;
          this.updateFrames++;

          if(this.updateFrameTicks >= 1000) {
              this.ups = this.updateFrames;
              this.updateFrames = 0;
              this.updateFrameTicks -= 1000;
          }

          this.ticks -= State.DELTA_TIME;
          updates++;
    }

    if(updates > 0) {
          this.renderFrameTicks += updates*State.DELTA_TIME;
          this.renderFrames++;

          if(this.renderFrameTicks >= 1000) {
              this.rps = this.renderFrames;
              this.renderFrames = 0;
              this.renderFrameTicks -= 1000;
          }

          this.renderState(updates*State.DELTA_TIME);
    }

};

```

But this strategy does not work very well. This is the result: http://jsbin.com/ukosuc/25 (Edit).

As it is apparent, the 'game' has fits of lag, and when you tab out for a long period and come back, the 'game' behaves unexpectedly - updates faster than intended. (**EDIT**) Thanks to `dreta` and `Vincent Piel`, I was able to fix the issue with tabbing out and finding the game to be updating very fast. The problem with the whole thing constantly stuttering and being choppy still persists.

This is either a problem due to something about game loops that I don't quite understand yet, or a problem due to implementation which I can't pinpoint. I haven't been able to solve this problem despite attempting several variations using `setTimeout` and `requestAnimationFrame`. (One such example is http://jsbin.com/eyarod/1/edit).

Some help and insight would really be appreciated!

# Answer
> 1 votes
You should use window.RequestAnimationFrame to manage your game rendering when making games in HTML5.

Here are some good blogs that explain the issue.

http://creativejs.com/resources/requestanimationframe/ http://www.playmycode.com/blog/2011/08/building-a-game-mainloop-in-javascript/

# Answer
> 0 votes
You really don't need the delta time pattern while developing 2D games. It's just a waste of CPU and floating points. You don't have such thing as a half pixel, right?

So you can just set any fixed frame rate that works for you and forget about delta time on your animations.

---
Tags: javascript, html5, html-canvas, game-loop
---


# Question
Title: How can I get a property of an entity without having to call getEntityByType every time?
I'm trying to get an entity (a bullet, a grenade, and an explosive) from my player. Specifically, I want the `shootingRate` of my bullet (how frequently it can be fired).

How can I do this without having to call `getEntityByType` each time I fire this projectile? There has got to be a cleaner way from what I'm doing right now, which is:

```
// Shooting
var isShooting = ig.input.state('shoot');

if (isShooting && this.lastShootTimer.delta() > 0) {

switch (this.activeWeapon)
{
    case("EntityBullet"):
        ig.game.spawnEntity(this.activeWeapon, this.pos.x, this.pos.y - 10);
        var equipedWeap =  ig.game.getEntitiesByType(EntityBullet);
        this.lastShootTimer.set(equippedWeap.shootingRate);
        console.log(equipedWeap.shootingRate);
        break;
    case("EntityGrenade"):
        ig.game.spawnEntity(this.activeWeapon, this.pos.x, this.pos.y +5);
      var  equipedWeap =  ig.game.getEntitiesByType(EntityGrenade);
        this.lastShootTimer.set(equipedWeap.shootingRate);
        console.log(EquipedWeap.shootingRate);
        break;
    case("EntityExplosiveBomb"):
        ig.game.spawnEntity(this.activeWeapon, this.pos.x, this.pos.y +5 );
     var   equipedWeap =  ig.game.getEntitiesByType(EntityExplosiveBomb)[0];
        this.lastShootTimer.set(equipedWeap.shootingRate);
        console.log(equipedWeap.shootingRate);
        break;
   }
}

```

# Answer
Just have a look at the documentation on spawnEntity : it returns the newly created entity.

```
// Shooting
var isShooting = ig.input.state('shoot');

if (isShooting && this.lastShootTimer.delta() > 0) {
   var spawnWeap = ig.game.spawnEntity(this.activeWeapon,
                                         this.pos.x, this.pos.y ,
                                             { gunnerflip : this.currentAnim.flip,
                                                gunnerSize : this.size });
   this.lastShootTimer.set(spawnWeap.shootingRate);
 }

```

Rq 1 : You'll notice i didn't handle here the (x,y) shift linked to each weapon : i think you should handle it in the init() of each weapon, that's why i sent the flip and the size of the weapon user in the settings.

Rq 2 : you need to make a distinction between a weapon and its 'bullets'.

Rq 3 : Things might be simpler if you have, for each weapon, a canShoot function, that handles both the fire rate and the bullets remaining, and maybe some other conditions (overheat, ...). If you also implement a shoot() function that takes the shooting entity as an argument, your code becomes :

```
// Shooting
var isShooting = ig.input.state('shoot');

if (isShooting && this.activeWeapon.canShoot()) {
    this.activeWeapon.shoot(this);
 }

```
> 3 votes

# Answer
Just create a constant at the top level of your scope:

```
// constants
var PLAYER_SHOOTING_RATE = 2;

```
> 0 votes

---
Tags: javascript, impactjs
---


title: Best way to do "cutscenes"

text:
# Question
Title: Best way to do "cutscenes"
I'm curious about the best way to display cutscenes in canvas. When I say cutscene I mean something like a static image fading from one to the other. Would it be best to use a timeout for a certain amount of seconds then go to the next image? Alternatively, would it be better to somehow use the main loop and increment a counter? If anyone has a method they use, post an answer! :D

# Answer
Don't use `setInterval()` or so on for animating canvas. There is a `requestAnimationFrame()` (MDN) function for this. It has better performance and more usefull in general.

Here is a good article about it: http://html5hub.com/request-animation-frame-for-better-performance
> 0 votes

# Answer
Use `setTimeout()` instead of `setInterval()`, because `setTimeout()` will only run after a successful call, while `setInterval()` would just stack many unhandled calls in case one of the calls takes more time to complete before another call is made. Combine it with `requestAnimationFrame()` for even better performance plus not trying to render while the browser window is not even being shown.

This is what a standard JavaScript game loop usually looks like:

```
function getTime() {
    return new Date().getTime();
}

function loop() {
    var startTime = getTime();
    screen.update();
    var elapsedTime = getTime() - startTime;
    var interval = FRAME_DURATION - elapsedTime;
    setTimeout(onTimeout, interval);

    function onTimeout() {
        requestAnimationFrame(loop);
    }
}

function main() {
    loop();
}

main();

```

You have to issue the first call to `loop()` from `main()` (or whatever your main function is called) and then it will keep calling itself indefinitely. In the snippet above, `screen.update()` is the method for your animation. And yes, you can have a `++tick` there to increment whatever property of your animation is required to make the transition.
> 0 votes

---
Tags: javascript, html-canvas, cutscene
---


# Question
Title: Input prediction and server re-simultaion
I have read plenty of articles about multiplayer principles and I have basic client-server system set up. There is however one thing I am not clear on.

When player enters input, it is sent to the server and steps back in time to check if what should have happened at the time of that input and it resimulates the world again. So far everything's clear.

All articles took shooting as an example, because it is easy to explain and it is pretty straightforward, but I believe movement is more complicated. Imagine following situation: 2 players move towards each other.

A------\>\<------B

Player A stops halfway towards the collision point, but there is lag spike so the command does not arrive on the server for a second or so. Current state of the world on the server (and on the other clients as well) at the time when input arrives is this:

\[1\]:

-------AB-------

The command arrives and we go back in time and re-simulate the world, the result is this:

\[2\]:

---AB-----------

Player A sees situation \[2\] which is correct, but the player is suddenly teleported from the position in \[1\] (center) to the position in \[2\].

Is this how this is supposed to work? Point of the client prediction is to give lagged player feeling that everything is smooth, not to ruin experience for other players.

Alternative is to discard timestamp on the player's input and handle it when it arrives on the server without going back in time. This, however, creates even more severe problems for lagged player (even if he is lagging just a bit)

*EDIT:*

To give you more info about my situation, I am making a game where exact position is quite important and the action is quite fast-paced. Imagine air-hockey with some perks on top. Another thing worth considering is that this is flash game and I have to use TCP. From my previous experience, ping times of 200ms are the norm (unlike 50ms on pc games) in situations I will be facing.

# Answer
> 1 votes
You seem to have explained everything yourself. But, in case you need someone agree / disagree with that: Yes, your thoughts all seam reasonable.

As you do not wait for all players inputs before start simulating the world, you will run into those problems. You can not solve this, as you don't have the information (what each player does) before the network has transferred it.

So you only can "guess" what will happens and show this to your players, which is like predicting future (you might have luck or not). Or, you show only what is already for sure which will cause the maximum lag of all users to effect all users experience.

The only thing you can do about this is to improve your prediction algorithm for a user. E.g. detect movement patterns in acceleration, deceleration. But you'll never get it to perfection...

Note, that if a user only pretends to be lagging (network lag) he might see his "simulated" future. So the user might cheat. To balance the chances, you should delay the information (what other players did) sent from the server to each user by the detected lag (minus the minimum lag of all players).

## EDIT #1

To answer your question in the comment below:

> Well, the question might be hidden in there, but I wanted to ask is which approach is better, to re-simulate world on the server when user's input arrives or discard the timestamp info. Both have their pros and cons, I guess it depends on the situation. I was just wondering if there is another solution that I might be missing –

**In the environment of a 3D-Shooer game:**

1. Dropping the Timestamps: This is *bad for the player with longer lags*, as something different happens than he actually commanded. His commands will be executed in the future. You stop pressing "forward" and your actor stops some time later. You maybe shoot while seeing the object in the cross hair, but its executed when it already moved further. The players with longer lags know this *and can adapt to this*. They can release the forward key earlier or shoot a bit earlier than they would normally need. This is like driving a car, where you need to turn the wheel some meters in advance if you drive very slow... This is in a way acceptable to the lagging player, as he knows that he causes the problem himself. He also cant cheat by even increasing his lag.
2. Simple Re-Simulation when releasing information immediately: This is *bad for all players with fast connections*, as the lagging players just "beam" from one position to the other and they don't have a chance to know where he really is, while the lagging players can more easily aim their targets (they immediately see their correct opponents positions).
3. Delayed information releasing: You can also wait until all clients have send their current "actions" to the server and then distribute the whole information to all clients and simulate it. This gives a consistent state of the game at all clients, without the need for re-simulation. The client programs may of course "predict" the future and display it. This causes all players to suffer from the largest lag, but equalizes the chances of the players a bit. The lagging players still have some more problems, as their update-interval is longer. This means the time needed to send the next update from the server to this client is longer, and the player has a longer time in which he only sees the "prediction". But as long this period is short enough, this shouldn't be a real problem.

You can also do a combination of these methods. You can delay information releasing up to some limit (e.g. 50 ms and then start `to drop "timestamps"`). So you wait until all players have send their next actions -or- some timeout (e.g. 50 ms) is reached and then distribute them to the player together with the timestamp registered at the server. The server just simulates this. If an action is arriving too late at the server it is executed within the next round / simulation tick. The result is, that up to the limit (e.g. 50 ms) the player will have a synchroneous play, the server does not need to resimulate and only players with longer delays will have re-simulations at their client and will actually suffer from the problem. It also enables to have a quicker update period, if all players have a shorter ping that the limit (e.g. 50ms).

## Other Game Types...

In games which are more cooperative in nature and lots of players (as MMORPGs for example) the lag for all other players should be at least be limited to a reasonable amount. You'll always have players with slower connections, so they would at the end define the speed of the whole simulation. Depending on the type of game, the acceptable lag can be up to 400ms without being noticed by the players. This might especially work for real time strategy games... Especially in real-time strategy games repeatedly re-simulating and excessive "beaming" of actors would not be acceptable, if this is happening for all players. "What happens if I delay commands for x milliseconds in this game?" is what matters. For example in a real time strategy game it would even sound logical that it takes some time to tell the acting unit what it shall do, then it maybe needs to plan the route and finally starts walking. So a short delay won't disturb to much.

---
Tags: multiplayer
---


title: Android Swipe In Unity 3D World with AR

text:
# Question
Title: Android Swipe In Unity 3D World with AR
I am working on an AR application using Unity3D and the Vuforia SDK for Android. The way the application works is a when the designated image(a frame marker in our case) is recognized by the camera, a 3D island is rendered at that spot. Currently I am able to detect when/which objects are touched on the model by raycasting. I also am able to successfully detect a swipe using this code:

```
if (Input.touchCount > 0)
{
         Touch touch = Input.touches[0];

         switch (touch.phase)
         {
                case TouchPhase.Began:

                    couldBeSwipe = true;

                    startPos = touch.position;

                    startTime = Time.time;

                break;

                case TouchPhase.Moved:

                    if (Mathf.Abs(touch.position.y - startPos.y) > comfortZoneY)
                    {

                        couldBeSwipe = false;

                    }
                    //track points here for raycast if it is swipe
                break;

                case TouchPhase.Stationary:

                    couldBeSwipe = false;

                break;

                case TouchPhase.Ended:

                    float swipeTime = Time.time - startTime;

                    float swipeDist = (touch.position - startPos).magnitude;

                    if (couldBeSwipe && (swipeTime < maxSwipeTime) && (swipeDist > minSwipeDist))
                    {

                        // It's a swiiiiiiiiiiiipe!

                        float swipeDirection = Mathf.Sign(touch.position.y - startPos.y);

                        // Do something here in reaction to the swipe.
                        swipeCounter.IncrementCounter();
                    }

                break;

            }

         touchInfo.SetTouchInfo
          (Time.time-startTime,(touch.position-startPos).magnitude,Mathf.Abs (touch.position.y-startPos.y));
       }

```

Thanks to andeeeee for the logic. But I want to have some interaction in the 3D world based on the swipe on the screen. I.E. If the user swipes over unoccluded enemies, they die. My first thought was to track all the points in the moved TouchPhase, and then if it is a swipe raycast into all those points and kill any enemy that is hit. Is there a better way to do this? What is the best approach?

Thanks for the help!

# Answer
> 0 votes
Well it depends on how you want to kill enemies. If you want to kill anything you touched during swipe then you should either do a raycast in each frame whci you are swiping and record all hits in a list and then kill them all when swipe is approved or do an sphereCast from start position to end position. something like this 1- At start do a raycast and find the point p1 on ground 2- at end do another raycast and find the point p2 on ground 3- Do a sphere cast from p1 to p2. This is possible if you don't have covers which you want to block enemies between cover and your camera from being killed.

The swipe code is a little unfriendly as well cause a little stantionary should be ok if you don't want only really fast swipes and also you could do it using Input.GetMouseButtonX calls to make it possible to test it easily in editor and make it cross platform.

---
Tags: android, unity, mobile, touch
---


title: Infinite terrain shadows

text:
# Question
Title: Infinite terrain shadows
I'm creating an infinite terrain engine, which generates the terrain either with fractals or noise. How can I make dynamic shadows for the sun on this terrain, if I don't know in advance what will be rendered in front of the sun.

**My terrain:** The sun is the only light, it is directional, my terrain is generated on a plane which is positioned before the camera, frustum culled and fits the size of the viewing frustum. It is height mapped with generated noise texture, and using tessellation shaders on it.

Video:http://www.youtube.com/watch?v=tk6yFwYusOs Dynamic shadows with the infinite terrain.

# Answer
Generate shadows as part of your render, this way you render shadows around the camera and as the camera moves your detailed shadows relocate. Many games operate this way and apply lower detailed shadows (e.g. lower resolution shadow textures) the further from the camera a portion of the scene is.
> 1 votes

---
Tags: opengl, terrain, shadows
---


title: Multithreading 2D gravity calculations

text:
# Question
Title: Multithreading 2D gravity calculations
I'm building a space exploration game and I've currently started working on gravity ( In C# with XNA).

The gravity still needs tweaking, but before I can do that, I need to address some performance issues with my physics calculations.

This is using 100 objects, normally rendering 1000 of them with no physics calculations gets well over 300 FPS (which is my FPS cap), but any more than 10 or so objects brings the game (and the single thread it runs on) to its knees when doing physics calculations.

I checked my thread usage and the first thread was killing itself from all the work, so I figured I just needed to do the physics calculation on another thread. However when I try to run the Gravity.cs class's Update method on another thread, even if Gravity's Update method has nothing in it, the game is still down to 2 FPS.

**Gravity.cs**

```
public void Update()
    {
        foreach (KeyValuePair<string, Entity> e in entityEngine.Entities)
        {
            Vector2 Force = new Vector2();

            foreach (KeyValuePair<string, Entity> e2 in entityEngine.Entities)
            {
                if (e2.Key != e.Key)
                {
                    float distance = Vector2.Distance(entityEngine.Entities[e.Key].Position, entityEngine.Entities[e2.Key].Position);
                    if (distance > (entityEngine.Entities[e.Key].Texture.Width / 2 + entityEngine.Entities[e2.Key].Texture.Width / 2))
                    {
                        double angle = Math.Atan2(entityEngine.Entities[e2.Key].Position.Y - entityEngine.Entities[e.Key].Position.Y, entityEngine.Entities[e2.Key].Position.X - entityEngine.Entities[e.Key].Position.X);

                        float mult = 0.1f *
                            (entityEngine.Entities[e.Key].Mass * entityEngine.Entities[e2.Key].Mass) / distance * distance;

                        Vector2 VecForce = new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));
                        VecForce.Normalize();

                        Force = Vector2.Add(Force, VecForce * mult);
                    }
                }
            }

            entityEngine.Entities[e.Key].Position += Force;
        }

    }

```

Yeah, I know. It's a nested foreach loop, but I don't know how else to do the gravity calculation, and this seems to work, it's just so intensive that it needs its own thread. (Even if someone knows a super efficient way to do these calculations, I'd still like to know how I COULD do it on multiple threads instead)

**EntityEngine.cs (manages an instance of Gravity.cs)**

```
public class EntityEngine
{
    public Dictionary<string, Entity> Entities = new Dictionary<string, Entity>();
    public Gravity gravity;
    private Thread T;

    public EntityEngine()
    {
        gravity = new Gravity(this);
    }

    public void Update()
    {
        foreach (KeyValuePair<string, Entity> e in Entities)
        {
            Entities[e.Key].Update();
        }

        T = new Thread(new ThreadStart(gravity.Update));
        T.IsBackground = true;
        T.Start();
    }

}

```

EntityEngine is created in Game1.cs, and its Update() method is called within Game1.cs.

I need my physics calculation in Gravity.cs to run every time the game updates, in a separate thread so that the calculation doesn't slow the game down to horribly low (0-2) FPS.

How would I go about making this threading work? (any suggestions for an improved Planetary Gravity system are welcome if anyone has them)

I'm also not looking for a lesson in why I shouldn't use threading or the dangers of using it incorrectly, I'm looking for a straight answer on how to do it. I've already spent an hour googling this very question with little results that I understood or were helpful. I don't mean to come off rude, but it always seems hard as a programming noob to get a straight meaningful answer, I usually rather get an answer so complex I'd easily be able to solve my issue if I understood it, or someone saying why I shouldn't do what I want to do and offering no alternatives (that are helpful).

Thank you for the help!

**EDIT**: After reading the answers I've gotten, I see that you guys actually care and aren't just trying to spew out an answer that might work. I wanted to kill two birds with one stone (improving performance and learning some basics of multlthreading), but it appears most of the issue lies in my calculations and that threading is more hassle than it's worth for performance increases. Thank you all, I will read through your answers again and try out your solutions when I'm done with school, Thanks again!

# Answer
What you have here is a classic **O(n²)** algorithm. The root cause of your problem has nothing to do with threading and everything to do with the fact that your algorithm has a high complexity.

If you haven't come across "Big O" notation before, it basically means the number of operations required to work on ***n*** elements (this is the super-simplified explanation). Your 100 elements are executing the inner part of your loop *10000 times*.

In game development you generally want to avoid **O(n²)** algorithms, unless you have a small (and preferably fixed or capped) amount of data and a very fast algorithm.

If every entity were affecting every other entity, you would by necessity require an O(n²) algorithm. But it looks like only a few entities are actually interacting (due to `if (distance < ...)`) - so you could significantly reduce your number of operations by using something called "**Spatial Partitioning**".

Because this is a fairly detailed topic and somewhat game-specific, I recommend you ask a fresh question for more details. Let's move on...

---

One of the major performance problems with your code is fairly simple. **This is freaking slow**:

```
foreach (KeyValuePair<string, Entity> e in Entities)
{
    Entities[e.Key].Update();
}

```

You're doing a dictionary lookup by string, every iteration (multiple times in your other loops), *for an object you already have!*

You could do this:

```
foreach (KeyValuePair<string, Entity> e in Entities)
{
    e.Value.Update();
}

```

Or you could do this: (I personally like this better, both should be about the same speed)

```
foreach (Entity e in Entities.Values)
{
    e.Update();
}

```

A dictionary lookup by string is pretty slow. Iterating directly will be *significantly* faster.

Although, how often do you *actually* need to look up items by name? Compared to how often you must iterate through them all? If you only do name lookups rarely, consider storing your entities in a `List` (give them a `Name` member).

The code you actually have there is relatively trivial. I haven't profiled it, but **I bet most of your execution time is going to the repeated dictionary lookups**. Your code may well be "fast enough" just by fixing this problem.

EDIT: The next biggest problem is probably calling `Atan2` and then immediately converting it back into a vector with `Sin` and `Cos`! Just use the vector directly.

---

Finally, let's address threading, and the major issues in your code:

First and most obviously: **Don't create a new thread every frame!** Thread objects are quite "heavy". The simplest solution to this would be to simply use `ThreadPool` instead.

Of course, it's not that simple. Let's move on to problem number two: **Don't touch data on two threads at once!** (Without adding the appropriate thread-safety infrastructure.)

You're basically stomping memory here in the most *horrible* way. There's no thread-safety here. Any one of the multiple "`gravity.Update`" threads you are starting can be overwriting data being used in another thread at unexpected times. Your main thread, meanwhile, will no doubt be touching all these data structures as well. I would not be surprised if this code produced hard-to-reproduce memory access violations.

**Making something like this thread safe is *difficult* and can add *significant performance overhead* such that it is often not be worth the effort.**

---

But, seeing as you asked (not so) nicely about how to do it anyway, let's talk about that...

Normally I'd recommend starting out by practising something simple, where your thread is basically "fire and forget". Playing audio, writing something to disk, etc. Things get complicated when you have to feed the result back into the main thread.

There are basically three approaches to your problem:

**1)** Put locks around *all* the data that you use across threads. In C# this is made fairly simple with the `lock` statement.

Generally you create (and retain!) a `new object` specifically for locking to protect some set of data (it is for safety reasons that generally only come up when writing public APIs - but good style all the same). You must then lock your lock object *everywhere* you access the data it protects!

Of course, if something is "locked" by one thread because it is in use, and another thread tries to access it - that second thread will then be forced to wait until the first thread is finished. So unless you carefully select tasks that can be done in parallel, you'll basically be getting single-threaded performance (or worse).

So in your case, there's no point in doing this unless you can architect your game such that some other code runs in parallel that won't be touching your entity collection.

**2)** Copy the data into the thread, let it process, and then take the result out again when it's finished.

Exactly how you implement this will depend on what you are doing. But obviously this will involve a potentially expensive copy operation (or two) that in many cases will be slower than just doing things single-threaded.

And, of course, you still have to have some other work to do in the background, otherwise your main thread will just be sitting around waiting for your other thread to finish so it can copy the data back!

**3)** Use thread-safe data structures.

These are a fair bit slower than their single-threaded counterparts and often harder to use than than simple locking. They can still exhibit the problems of locking (reducing performance down to a single thread) unless you use them carefully.

---

Finally, because this is a frame-based simulation, you'll need to have the main thread wait for other threads to provide their results, so that frame can be rendered and simulation can continue. A full explanation is really too long to put in here, but basically you'll want to learn how to use `Monitor.Wait` and `Monitor.Pulse`. Here is an article to start you off.

---

I know I haven't given specific implementation details (except that last bit) or code for any of these approaches. First of all, there would be a *lot* to cover. And, secondly, none of them are applicable to your code on its own - you need to approach your entire architecture with a look towards adding threading.

**Threading won't magically the code you have there any faster - it just lets you do something else at the same time!**
> 36 votes

# Answer
Ok at first glance there are some things you should try out. At first you should try to reduce your collision checks, you can do this by using some kind of spatial structure like a **quadtree**. This will allow you to reduce the second foreach count, as you will only query entities close the first one.

Regarding your threading: Try not to create a thread every Update turn. This overhead is maybe slowing your down more than its speeding things up. Instead try creating a single collision thread and let it do the work for you. I have no concrete *copy-paste-this-code* approach, but there are articles about thread syncronising and background worker for C#.

Another point is that in the foreach loop you don´t need to do `entityEngine.Entities[e.Key].Texture` because you already accessed the dict in your foreach header. Instead you can just write `e.Texture`. I don´t really know about the impact of this, just wanted to let you know ;)

One last thing: At the moment you are double checking every entity, because it gets queried in the first AND the second foreach loop.

Example with 2 entities A and B:

```
pick A in first foreach loop
   pick A in second foreach loop
      skip A because keys are the same
   pick B in second foreach loop
      collision stuff
pick B in first foreach loop
   pick A in second foreach loop
      collision stuff
   pick B in second foreach loop
      skip B because keys are the same

```

While this is a possible approach, maybe you can handle A and B in one turn, skipping half of your collision checks

Hope this gets you started =)

PS: Even if you said you dont want to hear it: Try to keep the collision detection in the same thread and just speed it up enough. Threading it seems like an good idea but with this comes the need to synchronise like hell. If you collision check is slower than your update (reason for threading it) you WILL get glitches and errors, because collision will trigger after ships moved already and vice versa. I don´t want to discourage you, this is just a personal experiene.

EDIT1: Links with QuadTree tutorial (Java): http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space/
> 22 votes

# Answer
Honestly, the *first* thing you should do is switch to a better algorithm.

Parallelizing your simulation can, even in the best possible case, speed it up only by a factor equal to the number of CPUs × cores per CPU × threads per core available on your system — i.e. somewhere between 4 to 16 for a modern PC. (Moving your code to the GPU can yield *much* more impressive parallelization factors, at the cost of extra development complexity and a lower per-thread baseline computation speed.) With an O(n²) algorithm, like your example code, this would let you use from 2 to 4 times as many particles as you currently have.

Conversely, switching to a more efficient algorithm could easily speed up your simulation by, say, a factor of 100 to 10000 (numbers purely guesstimated). The time complexity of good n-body simulation algorithms using spatial subdivision scales roughly as O(n log n), which is "almost linear", so that you could expect almost the same factor of increase in the number of particles you can handle. Also, that would still be using only one thread, so there would still be room for parallelization *on top of that*.

Anyway, as the other answers have noted, the general trick to efficiently simulating large numbers of interacting particles is to organize them in a quadtree (in 2D) or an octree (in 3D). In particular, for simulating gravity, the basic algorithm you want to use is the **Barnes–Hut simulation algorithm**, in which you store the total mass (and the center of mass) of all the particles contained in each cell of your quad/octree and use that to approximate the average gravitational effect of the particles in that cell on other, distant particles.

You can find plenty of descriptions and tutorials on the Barnes–Hut algorithm by Googling for it, but here's a nice and simple one to get you started, while here's a description of an advanced implementation used for GPU simulation of galaxy collisions.
> 10 votes

# Answer
Another optimization answer that has nothing to do with threads. Sorry about that.

You're calculating the Distance() of every pair. This involves taking a square root, which is slow. It also involves several object lookups to get the actual sizes.

You can optimize this using the DistanceSquared() function instead. Precalculate the maximum distance at which any two objects can interact, square it, and then compare this with the DistanceSquared(). If and only if the distance squared is within the maximum, then take the square root and compare it with the real object sizes.

**EDIT**: This optimization is mostly for when you're testing for collisions, which I now noticed is not actually what you're doing (though you surely will at some point). It may still be applicable to your situation though, if all the particles are of similar size/mass.
> 6 votes

# Answer
I don't know much about threading, but it seems like your loops are time consuming, so maybe changing from this

```
i = 0; i < count; i++
  j = 0; j < count; j++

  object_i += force(object_j);

```

to this

```
i = 0; i < count-1; i++
  j = i+1; j < count; j++

  object_i += force(object_j);
  object_j += force(object_i);

```

could help
> 3 votes

# Answer
If you already have such huge problems with 10 simulated objects, you'll need to optimize the code! Your nested loop would cause only 10\*10 iterations of which 10 iterations are skipped (same object), resulting in 90 iterations of the inner loop. If you only achieve 2 FPS, this would mean that your performance is so bad, that you only achieve 180 iterations of the inner loop per second.

I suggest you to do the following:

1. PREPARATION/BENCHMARKING: To surely know that this routine is the problem, write a small benchmark routine. It shall execute the `Update()` method of the Gravity multiple times for e.g. 1000 times and measure it's time. If you want to achieve 30 FPS with 100 objects, you should simulate 100 objects and measure the time for 30 executions. It should be less than 1 second. Using such a benchmark is needed to do reasonable optimizations. Else you will probably achieve the opposite and make the code run slower because you just think it must be faster... So I really encourage you to do this!
2. OPTIMIZATIONS: While you cannot do much about the O(N²) effort problem (meaning: calculation time increases quadratically with number of simulated objects N), you can improve the code itself.

a) You use a lot of "associative array" (Dictionary) lookups within your code. These are slow! For example `entityEngine.Entities[e.Key].Position`. Can't you just use `e.Value.Position`? This saves one lookup. You do this everywhere in the whole inner loop to access properties of the objects referenced by e and e2... Change this! b) You create a new Vector inside the loop `new Vector2( .... )`. All "new" calls implicate some memory allocation (and later: deallocation). These are even much slower than lookups of Dictionaries. If you only need this Vector temporarily, so allocate it outside of the loops AND -reuse- it by reinitializing its values to the new values instead of creating a new object. c) You use a lot of trigonometric functions (e.g. `atan2` and `cos`) within the loop. If your accuracy doesn't need to really really exact, you might try to use an lookup table instead. To do this you scale your value to a define range, round it to an integer value and look it up in a table of pre-calculated results. If you need help with that, just ask. d) You often use `.Texture.Width / 2`. You can pre-calculate this and store the result as `.Texture.HalfWidth` or -if this is always an even positive integer value - you can use bit the shift operation `>> 1` to devide by two.

Do only one of the changes at a time and measure the change by the benchmark to see how it effected your runtime! Maybe one thing is good while the other idea was bad (even I did propose them above!)...

I think these optimizations will be much better than trying to achieve better performance by using multiple threads! You'll have much trouble to coordinate the threads, so they will not overwrite the others values. Also they will conflict when accessing similar memory regions too. If you use 4 CPUs/Threads for this job, you could expect only a speed up of 2 to 3 for the frame rate.
> 1 votes

# Answer
Are you able to rework it without the object creation lines?

Vector2 Force = new Vector2();

Vector2 VecForce = new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));

if perhaps you could place the force value into the entity instead of creating two new objects each time, it may help to improve performance.
> 0 votes

---
Tags: xna, c#, physics, multithreading
---


# Question
Title: General visual effects to meshes/entities
I am trying to add some visual effects to some entities, meshes, or whatever you want to call them as they are looking pretty dull in my game right now.

What I want to achieve is this: http://youtu.be/zox8935PLw0?t=36s (the "texture" gets disintegrated and then goes back to normal, covering the whole mesh.)

Also I would like to know what is the best way to add effects like the one in the video to my game (for example, thunder effects, shattering, etc.) I know that I can do some things with shaders, but I haven't learned them too well and I am still in a beginner level.

I am using Ogre3D, and GLSL for shaders.

Thanks!

Note: this is a screen-shot of my game, I want to apply the effect in the video to my main character):

# Answer
Seeing the video I think the approach used is just to move the triangles of the mesh independently, instead of treating the whole mesh as a rigid body. Follow these passes:

1) To achieve that spinning tornado movement just rotate all triangles around the up vector of the mesh. In addition, move each triangle in the direction of its normal to achieve this "explosion" movement. This pass doesn't need to be in a shader.

2) To disintegrate the triangles, just go subtracting a delta to their alpha channel while the animation goes. Your delta should be an interpolation between (1.0, 0.0) based on the length of the animation. This way you will have a smooth disintegration. This pass can be done in a pixel shader with an uniform delta.

3) To let the texture fly with the triangles, just don't change the UV coordinates. You can do this in the same pixel shader of pass 2.

4) To reintegrate the mesh, just do the passes 1) through 3) with operations reversed.

Now about the best way to add effects to a game. Usually you can do this with shaders and/or particles. Shaders are better suited for effects that takes the mesh into consideration (e.g. outline, cartoon and environment mapping effects) or full screen effects and filters (for example blur, night-vision googles, noise and old film effects). Particles usually model effects that are best viewed as a group of independent bodies (usually tiny particles): magical auras, fire, smoke, etc.
> 2 votes

# Answer
A great way to easily make good looking effects is to use particles. Take a look at the particle scripts that come with the Ogre SDk (Located at OgreSDK\_vc10\_v1-8-1\media\particle), may be different depending on your version of Ogre.

Particle scripts are saved a a .particle file and are loaded and parsed in a similar way to materials.

There is a wiki page on particles that helped me a lot by just looking through all the pages under manual.
> 0 votes

---
Tags: 3d, ogre, graphic-effects
---


# Question
Title: How to deal with characters picking up and dropping objects in a 2D game
I'm quite new to game development, so would like to get a consensus on methods of doing this.

My game features a 2D character that is able to pick up and drop objects, for example, a stick. My question is: is it advisable / possible to manipulate the image of the character and image of the stick to make it look like the character is now carrying a stick; or is it best to have a separate sprite sheet for the character with the stick and the character without?

EDIT:

To be clear - I have a lot of characters, with a few items (4 separate items and over 20 characters)

# Answer
It will depend a lot on the artwork and what effect you want to accomplish and how much time you want to spend on it.

Do you need the to work with every single object? Or just some wieldable ones (like swords and sticks). If its just some then I would probably just have a separate set of sprites.

If you are looking to do rotations on pickup and you are doing pixel art (via a pixmap/bitmap image) then manipulating the original image won't work very well. It will possibly blur (if you have some kind of antialiasing) or it might loose a lot of detail (if there is no antialiasing pixels can disappear or 'tear').

You could try using much higher resolution graphics or even better (but much more complex to program) vector art, so manipulations don't have as many visual issues.

A simple 90° bitmap rotation would work without any distortions. It could allow the stick to be flat on the ground and upright when held, 45° wouldn't be too bad either. But some items won't make sense (a cup of water might look weird when left on the side), so you might need to provide a rotation 'hint' with the sprite/object.

You will need to track the location of the hand, you might also need to have some bits that are drawn under the item or over it. For example fingers. It might also be reversed when the character is facing the other way.

It might be an idea to have some rigging like you would with a 3d mesh. For a simple setup, I would probably make a separate character sprite (or another layer) that just has a couple of pixels in a few color keys. The Red pixel might be the left hand position. Blue for right. You can add other colors for things like the head, torso, legs, knees, feet and so on which would allow things like helmets, armour, pants, shoes and so on. Just scan though the pixels for the 'slots' (there are probably more efficient ways of packing it, but don't make more work for yourself). You might also be able to use different colors to specify if the object should be drawn after to before the character sprite (ie will the hands obscure the object). You could make a fingers a separate 'object' if you need that level of complexity (ie the fingers drawn over the object but the palm of the hand behind it).

Otherwise if you just need a few specific items, swords and such rather than every object in existence I would probably just have a animation for 'guy with sword' 'guy with axe' 'guy with stick' and so on. Maybe just have them overlay the generic 'guy' character sprites. But remember an attack animation with a sword will probably be different to one with an axe so setting up some overly complex setup would just get in the way their.

Maybe you can offer some colour pallet options so you could have a wooden sword or a steel one with the same sprites just with different colours.
> 0 votes

# Answer
The way we do this in our 2D MMORPG is to use the following approach:

* Two base character models
* Weapons go on their own layer
* Animate the weapon for all the same frames as the character model

To accommodate different kinds of weapons, we use different animation states. So we have Idle - Fist Weapon, Idle - Sword, Idle - Staff, etc.

The result of our approach is a high degree of flexibility, but it also means a lot of work. We have to animate every weapon in the game for every (applicable) animation state of our characters. We also have to do this for armor, etc.

We try to minimize this work as much as possible, but it's still there.

In short, if you want a believable result in your game, you're probably going to have to do something along these lines or tailor your art very carefully and think about using some kind of animation system. We just use frame-by-frame animation.

Hope this helps at least a little bit. Good luck!
> 0 votes

# Answer
you can have:

* separate sprite with stick.
* hands with stick, that are attached to body.
* some skeleton, and then draw stick where the hand is.
> -1 votes

---
Tags: 2d, sprites, gameobject
---


title: OpenGL camera moves faster than player

text:
# Question
Title: OpenGL camera moves faster than player
I have a side scroller game made in OpenGL, and I'm trying to center the player in the viewport when he moves. I know how to do it:

```
cameraX = Width / 2 / TileSize - playerPosX
cameraY = Height / 2 / TileSize - playerPosY

```

However, I have a problem. The player and "camera" move, but the player moves faster than the "camera" scrolls. So, the player can actually move out of the screen.

Some code, this is how I translate the camera:

```
public Camera(){
}

public void update(Player p){
    glTranslatef(-p.getPos().x - Main.WIDTH / 64 / 2, -p.getPos().y - Main.HEIGHT / 64 / 2, 1);
}

```

Here's how I move the player:

```
public void update(){
    if(Keyboard.isKeyDown(Keyboard.KEY_D)){
        this.move(MOVESPEED, 0);
    }

    if(Keyboard.isKeyDown(Keyboard.KEY_A)){
        this.move(-MOVESPEED, 0);
    }
}

```

The move method:

```
public void move(float x, float y){
    this.getPos().set(this.getPos().x + x, this.getPos().y + y);
}

```

And then after I move the player, I update the player's geometry, which shouldn't matter.

What am I doing wrong here, this seems like such a simple problem, yet it doesn't work!

# Answer
is your player's coordinates in screen coordinates or does your 'world' use a separate coordinate system? You'll need to convert between world coordinates and screen coordinates to do the calculations for translation.
> 1 votes

# Answer
The solution is simple. You just translate the camera to the position in the center of the player. If the stored player position is in the center of the player sprite then cameraPosition = playerPosition. If it is in the left bottom of the player sprite then cameraPosition = playerPosition + playerSize/2.0.
One important thing is to first update the player position and then the camera position, otherwise your camera will lag one update behind.
> 0 votes

# Answer
As Anastasios said, if your Camera update function is called first and the player Move function after, the camera will follow the previous position of the player, and it will look as the Player go faster than the camera.

And what are Main.Width, 64 and Width? You never use cameraX and cameraY ?

If you want your player to constantly be in the center a easier way is :

```
glTranslate(playerPos.x, playerPos.y) //Camera translate
//draw your level
glPushMatrix(); //save where you where
glLoadIdentity() //Reset the translate to (0,0) (I'm not sure, but I think it'll affect the camera translate, that would be a big problem)
//Draw your Player
glPopMatrix() // return to the camera translation.

```

I did not tested this code, but I think that you'll understand what I plan to do.
> 0 votes

---
Tags: opengl, java, camera
---


# Question
Title: How do multi-platform games usually store save data?
I realize this is a bit of a broad question, but I was wondering if there is a "standard" in the industry when it comes to storing save data for games (and is it different across platforms - Xbox/PS/PC/Mac/Android/iOS?)

For example for a game like Assassin's Creed or The Walking Dead: They are on multiple platforms and they usually have to save enough information about the player and their actions. Do they use something like XML files, databases, or just straight binary dumps? How much does it differ from platform to platform?

I would appreciate it if someone with experience in the game industry would answer this.

# Answer
> 1 votes
I wrote the save game system for Disney's Guilty Party. I can give you a high level overview of how it was done. Although it was shipped as a Wii game, for debugging purposes we needed a save game system that worked both on the Wii and on the PC. Disclaimer: this is the only time I've written such a system, and by no means can I claim that it is The Standard Way(tm) to write a save game system. It is more of a case study.

From a purely design standpoint, binary files are always a hassle. For one thing, they are extremely hard to debug since you have to open the save game files in a hex editor. Second, you cannot download a save game file generated on the console and open it on the PC without making sure that your endianness is correct, which requires you either to A) have duplicate serialization code for big and little endian machines or B) wrap your serialization code in swapBytes() calls that switch things based on the endianness of your machine. Both are clunky.

Hence, we were looking for a save game system that had the ability to

* Be able to be read and written from both the Wii and the PC with the same format.
* Be easy to debug the serialization of our objects
* Have a versioning system that allowed us to read save game files from previous versions of the game in order to track down crash reports during playtesting of old builds.
* Ignore loading time because loading a game from a deserialized save file was on the same order of magnitude as loading a fresh level from scratch.

With these ideas in mind, we used (roughly) the following system. Each save game file was saved as plaintext. The beginning of each save game file always started with a line that looked like:

```
Version: 21

```

Then, we used something akin to the following for serializing and deserializing:

```
const unsigned int kCurrentVersion = 24;
void Serialize(GameState &state, const char *filename) {
  File saveFile = File::Open(filename);
  saveFile.Write("%d\n", kCurrentVersion);
  saveFile.Write("%f %f %f\n", state.playerPosition);
  saveFile.Write("%f %f %f\n", state.playerPantsColor);
  saveFile.Write("%d\n", state.kNumTacosIHadForLunch);
}

// Any save game file before this version is invalid...
const unsigned int kMinimumSupportedVersion = 18;
GameState Deserialize(const char *filename) {
  File saveFile = File::Open(filename);
  unsigned int version = 0;

  GameState savedState;

  if(saveFile.Read("%d\n", &version) != 1 || !version) {
    fprintf(stderr, "No version... no idea what's going on.");
    return kInvalidState;
  }

  if(version < kMinimumSupportedVersion || version > kCurrentVersion) {
    fprintf(stderr, "Unsupported version: %d\n", version);
    return kInvalidState;
  }

  float pos[3];
  if(saveFile.Read("%f %f %f\n", &pos[0], &pos[0], &pos[0]) != 3) {
    fprintf(stderr, "Error reading position.\n");
    return kInvalidState;
  } else {
    savedState.setPlayerPosition(pos);
  }

  if(version > 10) {
    float c[3];
    if(saveFile.Read("%f %f %f\n", &c[0], &c[1], &c[2]) != 3) {
      fprintf(stderr, "Error reading pants color.\n");
      return kInvalidState;
    } else {
      savedState.setPantsColor(c);
    }
  }

  if(version > 17 && version < 22) {
    int nsiwaat;
    if(saveFile.Read("%d\n", &nsiwaat) != 1) {
      fprintf(stderr, "Error reading the number of socks I wear at a time.\n");
      return kInvalidState;
    } else {
      savedState.setNSIWAAT(nsiwaat);
    }
  }

  // ...etc

  return savedState;
}

```

The key takeaways from this are: Your serialization code should always write the most up to date version of your game state, regardless of what that is. However, it must also write what the most up to date version is so that future (and current) versions of the game are able to know how to read the file.

The deserialization code gets a little bit messy with this technique. It takes a very defensive approach to reading save game files. There are security reasons (i.e. buffer overflow) for why this is a good idea. It also reduces the risk of reading a corrupt save game file and loading bad data and crashing (or worse, not crashing). For debugging purposes, however, you should make sure to be as verbose as possible for why a saved game could not be read. This will save you many headaches in future versions where you thought a thing should be a certain way but it isn't. This system proved to not only be very effective, but I had a very easy time maintaining it.

# Answer
> 1 votes
I'd advice on using SQL databases whenever you can. They are robust, well known, easy to interface, scalable and all. The only downside might be performance. But as you are not asking about how to store your live game objects on every update performance of the database itself will very likely not be a problem.

Make sure to learn about serializing you savegame-relavant part of your game state. Pushing those into a database should be fairly easy then.

# Answer
> 1 votes
You could use Google's protocol buffers (https://developers.google.com/protocol-buffers).

---
Tags: game-design
---


# Question
Title: RTS Voxel Engine using LWJGL - Textures glitching
I'm currently working on an **RTS game engine using voxels**.

I have implemented a basic chunk manager using an **Octree of Octrees** which contains my voxels (simple square blocks, as in Minecraft). I'm using a Voronoi-based terrain generation to get a simplistic yet relatively realistic heightmap.

I have no problem showing a 256\*256\*256 grid of voxels with a decent framerate (\>250), because of **frustum culling**, **face culling** and only rendering visible blocks. For example, in a random voxel grid of 256\*256\*256 I generally only render 100k-120k faces, not counting frustum culling. Frustum culling is only called every 100ms, since calling it every frame seemed a bit overkill.

Now I have reached the stage of **texturing** and I'm experiencing some problems:

Some experienced people might already see the problem, but if we zoom in, you can see the glitches more clearly:

All the seams between my blocks are glitching and kind of 'overlapping' or something. It's much more visible when you're moving around. I'm using a single, simple texture map to draw on my cubes, where each texture is 16\*16 pixels big:

I have added black edges around the textures to get a kind of **cellshaded** look, I think it's cool. The texture map has 256 textures of each 16\*16 pixels, meaning the total size of my texture map is 256\*256 pixels.

The code to update the ChunkManager:

```
public void update(ChunkManager chunkManager) {
    for (Octree<Cube> chunk : chunks) {
        if (chunk.getId() < 0) {
            // generate an id for the chunk to be able to call it later
            chunk.setId(glGenLists(1));
        }

        glNewList(chunk.getId(), GL_COMPILE);
        glBegin(GL_QUADS);

        faces += renderChunk(chunk);

        glEnd();
        glEndList();
    }
}

```

Where my *renderChunk* method is:

```
private int renderChunk(Octree<Cube> node) {
    // keep track of the number of visible faces in this chunk
    int faces = 0;

    if (!node.isEmpty()) {
        if (node.isLeaf()) {
            faces += renderItem(node);
    }

    List<Octree<Cube>> children = node.getChildren();

    if (children != null && !children.isEmpty()) {
        for (Octree<Cube> child : children) {
            faces += renderChunk(child);
        }
    }

    return faces;
}

```

Where my *renderItem* method is the following:

```
private int renderItem(Octree<Cube> node) {
    Cube cube = node.getItem(-1, -1, -1);
    int faces = 0;

    float x = node.getPosition().x;
    float y = node.getPosition().y;
    float z = node.getPosition().z;

    float size = cube.getSize();

    Vector3f point1 = new Vector3f(-size + x, -size + y, size + z);
    Vector3f point2 = new Vector3f(-size + x, size + y, size + z);
    Vector3f point3 = new Vector3f(size + x, size + y, size + z);
    Vector3f point4 = new Vector3f(size + x, -size + y, size + z);
    Vector3f point5 = new Vector3f(-size + x, -size + y, -size + z);
    Vector3f point6 = new Vector3f(-size + x, size + y, -size + z);
    Vector3f point7 = new Vector3f(size + x, size + y, -size + z);
    Vector3f point8 = new Vector3f(size + x, -size + y, -size + z);

    TextureCoordinates tc = textureManager.getTextureCoordinates(cube.getCubeType());

    // front face
    if (cube.isVisible(CubeSide.FRONT)) {
        faces++;

        glTexCoord2f(TEXTURE_U_COORDINATES[tc.u], TEXTURE_V_COORDINATES[tc.v]);
        glVertex3f(point1.x, point1.y, point1.z);
        glTexCoord2f(TEXTURE_U_COORDINATES[tc.u + 1], TEXTURE_V_COORDINATES[tc.v]);
        glVertex3f(point4.x, point4.y, point4.z);
        glTexCoord2f(TEXTURE_U_COORDINATES[tc.u + 1], TEXTURE_V_COORDINATES[tc.v + 1]);
        glVertex3f(point3.x, point3.y, point3.z);
        glTexCoord2f(TEXTURE_U_COORDINATES[tc.u], TEXTURE_V_COORDINATES[tc.v + 1]);
        glVertex3f(point2.x, point2.y, point2.z);
    }

    // back face
    if (cube.isVisible(CubeSide.BACK)) {
        faces++;

        glTexCoord2f(TEXTURE_U_COORDINATES[tc.u + 1], TEXTURE_V_COORDINATES[tc.v]);
        glVertex3f(point5.x, point5.y, point5.z);
        glTexCoord2f(TEXTURE_U_COORDINATES[tc.u + 1], TEXTURE_V_COORDINATES[tc.v + 1]);
        glVertex3f(point6.x, point6.y, point6.z);
        glTexCoord2f(TEXTURE_U_COORDINATES[tc.u], TEXTURE_V_COORDINATES[tc.v + 1]);
        glVertex3f(point7.x, point7.y, point7.z);
        glTexCoord2f(TEXTURE_U_COORDINATES[tc.u], TEXTURE_V_COORDINATES[tc.v]);
        glVertex3f(point8.x, point8.y, point8.z);
    }

    // left face
    if (cube.isVisible(CubeSide.SIDE_LEFT)) {
        faces++;

        glTexCoord2f(TEXTURE_U_COORDINATES[tc.u], TEXTURE_V_COORDINATES[tc.v]);
        glVertex3f(point5.x, point5.y, point5.z);
        glTexCoord2f(TEXTURE_U_COORDINATES[tc.u + 1], TEXTURE_V_COORDINATES[tc.v]);
        glVertex3f(point1.x, point1.y, point1.z);
        glTexCoord2f(TEXTURE_U_COORDINATES[tc.u + 1], TEXTURE_V_COORDINATES[tc.v + 1]);
        glVertex3f(point2.x, point2.y, point2.z);
        glTexCoord2f(TEXTURE_U_COORDINATES[tc.u], TEXTURE_V_COORDINATES[tc.v + 1]);
        glVertex3f(point6.x, point6.y, point6.z);
    }

    // ETC ETC

    return faces;
}

```

When all this is done, I simply render my lists every frame, like this:

```
public void render(ChunkManager chunkManager) {
    glBindTexture(GL_TEXTURE_2D, textureManager.getCubeTextureId());

    // load all chunks from the tree
    List<Octree<Cube>> chunks = chunkManager.getTree().getAllItems();
    for (Octree<Cube> chunk : chunks) {
        if (frustum.cubeInFrustum(chunk.getPosition(), chunk.getSize() / 2)) {
            glCallList(chunk.getId());
        }
    }
}

```

I don't know if anyone is willing to go through all of this code or maybe you can spot the problem right away, but that is basically the problem, and I can't find a solution :-)

Thanks for reading and any help is appreciated!

UPDATE: Okay, here's some more code, showing how I determine my texture coordinates. In the **TextureManager** I define the texturecoordinates for each block type:

```
private void setupTextureCoordinatesForCube(CubeType type) throws IOException {
    if (cubeTextureId < 0) {
        cubeTextureId = loadTexture(terrainTextureFileName);
    }

    TextureCoordinates textureCoordinates;

    switch (type) {
        case DIRT:
            textureCoordinates = new TextureCoordinates(2, 0, 2, 0, 2, 0);
            break;
        case GRASS:
            textureCoordinates = new TextureCoordinates(3, 0, 0, 0, 2, 0);
            break;
        default:
            textureCoordinates = new TextureCoordinates(1, 0, 1, 0, 1, 0);
    }

    this.cubeTextureCoordinates.put(type, textureCoordinates);
}

```

And these are the coordinate arrays I'm using to represent each separate texture:

```
private static final float[] TEXTURE_U_COORDINATES = { 0f, 0.0625f, 0.125f, 0.1875f, 0.25f, 0.3125f, 0.375f, 0.4375f, 0.5f, 0.5625f, 0.625f, 0.6875f, 0.75f, 0.8125f, 0.875f, 0.9375f, 1.0f };

private static final float[] TEXTURE_V_COORDINATES = { 0f, 0.0625f, 0.125f, 0.1875f, 0.25f, 0.3125f, 0.375f,    0.4375f, 0.5f, 0.5625f, 0.625f, 0.6875f, 0.75f, 0.8125f, 0.875f, 0.9375f, 1.0f };

```

# Answer
> 1 votes
I have found my problem!

It appears it was a stupid mistake (aren't they always?).

I was adding every block with size of 1 unit and rendering it on coordinates \[-size,+size\] which means the actual size of the blocks were 2 units big... This bug must have slipped back into my code at a certain moment because I already fixed this once before.

My terrain looks like this now:

---
Tags: opengl, java, textures, lwjgl
---


title: How to opitimize Shadows in Unity 3D

text:
# Question
Title: How to opitimize Shadows in Unity 3D
I made the shadow of Solider in my game using Unity pro shadows feature.

http://docs.unity3d.com/Documentation/Manual/Shadows.html

The performance of my game becomes very slow after adding these shadows. I used light map for buildings shadows but I cant use this thing for solider. I want to ask what technique should I use to make both real and optimize shadow of my solider.

# Answer
There are a few things you should do to optimise the shadows in your game:

Use lightmapping heavily to compute the shadows for static meshes. Unity has a builtin lightmapper. See http://docs.unity3d.com/Documentation/Manual/Lightmapping.html and http://docs.unity3d.com/Documentation/Manual/OptimizeForIntegratedCards.html.

The computation of dynamic lights have 3 main aspects and each one must be tweaked for performance: the light itself, the casters and the receivers.

To make a dynamic light, set Hard Shadows or Soft Shadows in it. However, the number of dynamic lights should be minimal since each one issue additional rendering for shadow projection. Also, Soft Shadows require a blur filter to ensure smoothness, which can impact the performance. Finally, the resolution of the shadow texture also affects performance. See http://docs.unity3d.com/Documentation/Manual/Shadows.html and http://docs.unity3d.com/Documentation/Manual/DirectionalShadowDetails.html.

To make a mesh receive or cast shadows, set Receive Shadows or Cast Shadows in the respective Renderer (**BEWARE: by default these settings are on**). However, the number of casters and receivers should also be minimal, since each caster or receiver in the "light frustum" must be rendered additional times. See http://docs.unity3d.com/Documentation/Manual/ShadowTroubleshooting.html.

Another related performance tweek is to use the Deferred Rendering Path instead of the Forward Rendering Path.

In summary:

1. Bake light maps;
2. Keep the number of dynamic lights to a minimum;
3. Tweak the resolution of the shadow texture;
4. Tweak the filter for Soft Shadows;
5. Use Receive Shadows and Cast Shadows judiciously;
6. Use the Deferred Rendering Path.
> 3 votes

---
Tags: 3d, unity, shadows
---


# Question
Title: cocos2dx- set draw() method interval time
What is the default interval of draw method call in cocos2dx engine? Can we set it manually? I couldn't find much information about it online. After researching a bit I found that update() method interval step could be adjusted by setting setAnimationInterval. Can I set a specific interval for draw method too?

# Answer
The default interval is 1/60s. Although you can set it manually using `CCDirector::sharedDirector()->setAnimationInterval(1.0 / 60);`, it's not usually effective for intervals less than 1/60s simply because of vertical sync in case of desktop platforms, or hardware limits in case of mobile ones. For desktop platforms (specially windows that I've already tested) though you can disable vsync using `wglSwapIntervalEXT(0);`
> 1 votes

---
Tags: cocos2d, cocos2d-x
---


title: StringBuffer behavior in LWJGL

text:
# Question
Title: StringBuffer behavior in LWJGL
Okay, I've been programming in Java for about ten years, but am entirely new to LWJGL. I have a specific problem whilst attempting to create a text console. I have built a class meant to abstract input polling to it, which (in theory) captures key presses from the Keyboard object and appends them to a StringBuilder/StringBuffer, then retrieves the completed string after receiving the ENTER key.

The problem is, after I trigger the String return (currently with ESCAPE), and attempt to print it to System.out, I consistently get a blank line. I can get an appropriate string length, and I can even sample a single character out of it and get complete accuracy, but it never prints the actual string.

I could swear that LWJGL slipped some kind of thread-safety trick in while I wasn't looking.

==UPDATE==

I've now determined that a null value was appended at the beginning of my StringBuffer. The problem can (sloppily) be solved with a command.delete(0, 1) line, freeing the actual String data. However, I don't know how that null got in there to begin with. If anyone sees it before I do, please let me know.

Here's my code:

```
static volatile StringBuffer command = new StringBuffer();

@Override
public void chain(InputPoller poller) {
    this.chain = poller;
}

@Override
public synchronized void poll() {
    //basic testing for modifier keys, to be used later on
    boolean shift = false, alt = false, control = false, superkey = false;

    if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT))
        shift = true;
    if(Keyboard.isKeyDown(Keyboard.KEY_LMENU) || Keyboard.isKeyDown(Keyboard.KEY_RMENU))
        alt = true;
    if(Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || Keyboard.isKeyDown(Keyboard.KEY_RCONTROL))
        control = true;
    if(Keyboard.isKeyDown(Keyboard.KEY_LMETA) || Keyboard.isKeyDown(Keyboard.KEY_RMETA))
        superkey = true;

    while(Keyboard.next())
        if(Keyboard.getEventKeyState()) {
            command.append(Keyboard.getEventCharacter());
        }

        if (Framework.isConsoleEnabled() && Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {
            System.out.println("Escape down");
            System.out.println(command.length() + " characters polled"); //works
            System.out.println(command.toString().length()); //works
            System.out.println(command.toString().charAt(4)); //works
            System.out.println(command.toString().toCharArray()); //blank line!
            System.out.println(command.toString()); //blank line!

            Framework.disableConsole();
        }

        //TODO: Add command construction and console management after that
    }
}

```

Maybe the answer's obvious and I'm just feeling tired, but I need to walk away from this for a while. If anyone sees the issue, please let me know. This machine is running the latest release of Java 7 on Ubuntu 12.04, Mate desktop environment.

Many thanks.

# Answer
Solution found. To toggle the console mode, I use the tilde key ("~"). This requires a shift, and the grave character ("\`", next to the numbers). After I release tilde, I generally still have the shift key down, which, incidentally, is a type of key event. Shift itself is not responsible for a proprietary character, yet is fully valid otherwise. Thus, when I request the character, I receive null, and append it to the ArrayList contained in StringBuffer. A little defensive programming will easily solve this.
> 0 votes

# Answer
Judging with the code you provided, your STDOUT Stream likely isn't what you expect it to be due to a control character.

Try using a `System.out.flush()` after your `System.out.print()`

Let me know if this helps.
> 0 votes

---
Tags: java, lwjgl, multithreading, keyboard, text
---


# Question
Title: Are techniques from Warioware: D.I.Y actually useable in creating an actual game?
In a game called **Warioware: D.I.Y,** it teaches you how to create *minigames* with certain forms of AI. Can I use the techniques shown in this game to actually **develop** an advanced game?

# Answer
> 3 votes
Fundamentally, WarioWare DIY provides you with a very high-level *rules* engine - each rule (called an Assembly Instruction, or AI) consists of a trigger and a series of actions that are performed when the trigger is... well, triggered.

Rules are in other words statements of the form "When A occurs, B happens", and they define the *basic gameplay* of a game. Obviously, A and B can be significantly more complex in a "real" game than in WarioWare DIY, but the principle still applies.

There are many different game development tools out there, and different engines provide different layers of abstraction in how you define the gameplay.

Something like Multimedia Fusion 2 works on a similar level to WarioWare DIY by having you define triggers and actions - but of course, there are limitations to that approach, since not everything is easily expressable in the framework provided by the engine. Using a more general engine like Unity, where you write code to express the gameplay, offers more flexibility - but you also have to handle more things on your own, so it's a tradeoff.

By only having these ~5-second microgames, WarioWare DIY is able to apply a very high abstraction level. This makes it very easy to dive in, and this allows you to get some practice in actually *seeing* the rules that make up the game, and *converting* them to something the program can understand. With enough clever thinking, you can even do some very non-obvious things.

In that sense, then *yes*, WarioWare DIY can teach you some skills that will help you to develop more advanced games. *However*, you still need to do a lot of thinking to convert those rules into something meaningful, and there will almost surely be a lot of things in that process that don't make any sense in a microgame - WarioWare DIY isn't going to help you much with those parts - and you also have to remember that some of the tricks you can do in DIY might not be appropriate or even necessary in a "full" game.

---
Tags: software-engineering
---


# Question
Title: Multi Resolution graphic for ios 4 and ios 5
I have used cocos2d-x to develop a game for iPhone 4, iPhone 4s, iPhone 5 with different screen sizes (3.5 inch and 4 inch)

First, my resource are designed for iPhone 4 and iPhone 4s with 3.5 inch screen size.

So if I want to use for iPhone 5 with 4 inch screen size. what should I do?

# Answer
> 0 votes
A simple solution is that using `[[CCDirector sharedDirector] convertToUI]` and not using it. If you want to place align top, using `convertToUI` or else using normal `ccp(x, y)`. Also you need to write a method to resize the area that need to fill up the screen;

Another good option is to use the CocosBuilder to create the user interface; Can know more at the following URL: http://www.raywenderlich.com/23996/introduction-to-cocosbuilder

---
Tags: ios, cocos2d-x, resolution
---


# Question
Title: Testing HTML5 canvas games on low resource computers
I've made a game in HTML5 & JS and want to test it on varying types of user setups as I've heard it doesn't perform too well on older MacBooks.

How can I accomplish this? I'm thinking of something like browserstack.com but for GPU, CPU and memory testing.

# Answer
You could use virtual machines.

With a virtualization software like VirtualBox or VMWare you can simulate a computer inside a computer. You can install any operating system in them and you can artificially restrict the amount of hardware and CPU power the virtual machines have available.

This is of course not nearly as conclusive as testing on real hardware, especially when it comes to performance benchmarking. When you really want to know how fast a software runs on a given hardware, there is no way around actually testing it on that hardware.

But virtualized testing can still save you a lot of time and money.
> 4 votes

# Answer
"Heard it doesn't perform too well on older Macbooks" doesn't really give you much information. You should be collecting cold hard data, and making your own deductions based on numbers.

Consider collecting data that you *can* get from browsers:

* OS (navigator.appVersion containing one of Mac/Win/X11/Linux)
* browser version (window.navigator)
* resolution (window.screen.availWidth and window.screen.availHeight)
* 3d rendering context presence (!!window.WebGLRenderingContext)
* refresh rate (calculate the difference between start- and end-times for each update and render your game performs, and store that in an array from which you can calculate an average FPS)

Once you've got some statistics from which to work, you can decide how to take your investigation to the next step... even if that is borrowing/begging/stealing the problematic platform and running your profiler on it to see what is bogging down.
> 1 votes

---
Tags: javascript, html5, html-canvas, testing
---


title: Get screen bounds of 3D object

text:
# Question
Title: Get screen bounds of 3D object
I'm trying to draw a 2D plane that has minimum dimensions to contain a 3D model (a sphere). How do I calculate the minimum size and position of the rectangle to completely cover a 3D model on screen?

# Answer
> 5 votes
**Loose fitting, fast**

Generate a bounding AABB, which you likely already have (and is super cheap to compute for a sphere). Project the AABB's corners to the screen. Take the maximum and minimum X and Y values of the projected coordinates to form bounds of screen-space rectangle.

This will be at least as large as the object. Depending on camera orientation, the AABB may extend past the visible edges of the object, so the rectangle will be larger than the object (but no smaller).

**Close fitting, slow, generalized**

The above algorithm is mostly the same except we no longer want an AABB. Rather we want a bounding box aligned to the camera. One way to do this is to take the camera's up and right vectors and to find the points on the mesh/object farthest point in those directions and their inverses.

This is quite easy, albeit slow. For a plain mesh or triangulated object take each vertex and project it along the input axis (+X in camera space, -X in camera space, etc., all unit vectors). In this projection you'll compute a dot product between the point (treated as a vector) and the unit direction vector; simply keep the vertex with the largest dot product which is the point furthest along that direction vector. You can avoid needing to iterate over all vertices for both the positive and negative versions of a direction vector by taking both the largest and smallest dot product vertices. Once you have these vertices you project those to the screen to get their screen-space coordinaes and use those as bounds for your screen-space rectangle.

For more mathematical shapes like a perfect sphere, you need to find the function that computes this equivalence. For a sphere it's super easy: the vertex "position" of the farther point on the sphere in any direction is the center point of the sphere plus the radius scaling the target direction. More complex shapes can have very intricate functions, but thankfully you generally always use vertices/meshes in games.

Since the sphere is so special, if that's all you care about you can simplify all of the above for just that case. Center point of sphere plus the camera up/right vectors scaled by the radius.

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


# Question
Title: How can I ensure reasonably spaced out enemies
I have a simple javascript game and I'm initializing their positions on the y axis using random numbers. How can I ensure that they are reasonably spaced apart? My simple algorithm is:

```
 y = (Math.random()*1000%600);

```

However I frequently get enemies almost directly on top of each other. This is a huge problem for the game, since it's a word game and the enemies have text on their center, that if overlapped makes them impossible to kill since you can't see the words. Any advice would be appreciated! I'm pretty new to making games in general so this has all been a learning experience for me!

# Answer
Just add a small constant amount to your random value to ensure separation.

```
y = ((Math.random()*1000)%600) + 10;

```

All in all, this is going to be a play testing issue to find out what a good distance is. You can also experiment with other random distribution methods. For example, you can have each enemy placed 100 units apart, and that position is randomized by +- 40 units.

With basic questions like this is good to just experiment and find something that works for you. Ideally starting with something static and then making it random.
> 1 votes

---
Tags: javascript, random
---


title: Accesing depth buffer from shader

text:
# Question
Title: Accesing depth buffer from shader
I read this presentation and on 6th slide I found that is not need to use multiple render targets and depth can be taken directly from depth buffer.

From which version of DirectX or OpenGL can be the feature used? How to do that?

# Answer
As far as rendering the scene goes, it's just like using the ordinary depth buffer. The difference is that here the depth buffer is a texture which you can later sample in the lighting passes.

Depth textures have been available for a long time - since D3D9, or OpenGL 1.4. You can pretty much assume universal support on desktop GPUs today. For mobile platforms, depth textures are an extension in OpenGL ES 2; I'm not sure how widespread the support is. If you just google for the phrase "depth texture" you should be able to find details of how to do it on your chosen platform/API.
> 1 votes

# Answer
Don't know about OpenGL, but for DirectX it can be done in DX10+. See this article.
> 0 votes

---
Tags: opengl, directx, shaders, depth-buffer
---


title: Rendering oily/polluted water?

text:
# Question
Title: Rendering oily/polluted water?
Any shader wizards out there have an idea of how to achieve an oily/polluted water effect, similar to this:

Ideally, the water would not be uniformly oily, but instead the oil could be generated from some source (such as a polluting drain from a chemical plant) and then diffuse throughout the water body. My thought for this part would be to keep an "oil map" as a 2D texture that determines the density of oil at each point on the water surface. It would diffuse and move naturally with the water vel;ocity at that point (I have a wave-particle simulation for dynamic waves, and am already doing something similar for foam on the water surface). However, I'm not sure how physically correct that would be, since oil might not move at the same velocity as the water.

And I have no idea how to make all those trippy colors :-). Thoughts?

# Answer
The physical basis of the colors of an oil slick is iridescence, and also related to Newton's rings. Specifically, the thickness of the oil layer is on the order of the wavelength of light. Since light reflects from both the top and bottom surface of the oil, at any given wavelength, at some angles the two reflections will be out of phase and cancel each other out; at other angles the reflections will be in phase and add together. This happens at different angles for every wavelength, so illuminating the oil with white light produces all those colors. If you illuminated it with a single frequency (e.g. laser light) you would only see a series of light and dark rings.

If you ignore refraction in the oil layer, just working out the geometry of the situation, you can find that the brightness of the reflected light for any given wavelength should vary like

```
sin(2.0 * pi * oilThickness / (dot(L, H) * wavelength)) * 0.5 + 0.5

```

Theoretically this should be integrated over all wavelengths, but in practice you can probably just do it for red, green, and blue - let's say 700, 550, and 400 nm, respectively. Changing the oil thickness will change the apparent radius of the rings of color. I would probably wrap the `2.0 * pi * oilThickness / wavelength` into a single RGB value provided to the shader as a uniform value. You could multiply it by a texture to simulate varying thickness of oil, if desired - that's probably what gives most of the interesting texture in the image above.

That produces an RGB color value that you can multiply into your BRDF. The `dot(L, H)` factor would be used for point/directional lights, and you can substitute `dot(N, V)` in there for applying this to an environment map reflection as well.

Disclaimer: I haven't tried this out in a shader, just drawn some diagrams and convinced myself it "should work"...so let me know the results if you do try it! :)
> 26 votes

---
Tags: shaders, graphics, hlsl, water, effect
---


# Question
Title: How to fix Monogame WP8 Touch Position bug?
Normally below code will result in X:Infinity, Y:Infinity

```
TouchCollection touchState = TouchPanel.GetState();

foreach (TouchLocation t in touchState)
{
    if (t.State == TouchLocationState.Pressed)
    {
        vb.ButtonTouched((int)t.Position.X, (int)t.Position.Y);
    }
}

```

Then, I followed this https://github.com/mono/MonoGame/issues/1046 and added below code at the first line in update method. (I still don't know how it's worked, but it fixed the problem)

```
if (_firstUpdate)
{
    typeof(Microsoft.Xna.Framework.Input.Touch.TouchPanel).GetField("_touchScale",System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static).SetValue(null, Vector2.One);
    _firstUpdate = false;
}

```

And then, when I randomly testing something, there are several area that won't read the user touch.

The tile with the purple dude is the area which won't receive user input (It don't even detect "Pressed", the TouchCollection.Count = 0)

Any idea how to fix this?

UPDATE 1 : The second attempt in recompiling

The difference is weird. Dunno why the consistent clickable area is just 2/3 area to the left

UPDATE 2 : After trying to rotate to landscape and back to portrait to randomly testing, then the outcome become :

# Answer
There are 3 changes I made to solve this :

1) Make some changes in GamePage.xaml.

2) Using the different way to use TouchPanel.

3) Using the monogame-develop source code as my project reference instead of the installed one (3.0.1).

#

1) Make some changes in GamePage.xaml

Normally, when you are first created a monogame project, there are these codes in the GamePage.xaml.

```
<DrawingSurfaceBackgroundGrid x:Name="XnaSurface" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
        <TextBlock Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
        <TextBlock Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
    </StackPanel>

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

    </Grid>
</DrawingSurfaceBackgroundGrid>

```

....Change it into :

```
<Grid x:Name="LayoutRoot">
    <MediaElement />
    <DrawingSurface x:Name="XnaSurface" />
</Grid>

```

2) Using the different way to use TouchPanel.

First step, is to add enabled gestures you want in your game. Set it in your Game1.cs constructor (TouchPanel.EnabledGestures)

```
Game1()
{
    _graphics = new GraphicsDeviceManager(this);
    Content.RootDirectory = "Content";
    TouchPanel.EnabledGestures = GestureType.FreeDrag | GestureType.Tap;
}

```

You can add in extra enabled gestures by adding | Gesture.DoubleTap (for example), etc.

Second step is to use below code to detect your touch (put it in your update method)

```
public override void Update(GameTime gameTime)
{
    while (TouchPanel.IsGestureAvailable)
    {
        GestureSample gesture = TouchPanel.ReadGesture();
        switch (gesture.GestureType)
        {
            case GestureType.Tap:
            {
                //what to do if a tap is detected??
            }break;
            case GestureType.FreeDrag:
            {
                //what to do if a freedrag is detected??
            }break
            //and so on, depends on your enabledgestures..
        }
   }
}

```

3) Using the monogame-develop source code as my project reference instead of the installed one (3.0.1).

There is some bugs in MonoGame 3.0.1, so after I read & asked several times at the monogame forum, it's said that the "developed" monogame source code, is already corrected some problems (including mine). But since they hasn't released the "install" version, I need to use it directly from the source code. This is how :

https://monogame.codeplex.com/discussions/453170

That's my question thread, and it already answered (and solved) clearly.

#

Hope those helps.
> 0 votes

---
Tags: monogame, touch, windows-phone-8
---


# Question
Title: XNA hlsl tex2D() only reads 3 channels from normal maps and specular maps
Our engine uses deferred rendering and at the main draw phase gathers plenty of data from the objects it draws.

In order to save on tex2D calls, we packed our objects' specular maps with all sorts of data, so three out of four channels are already taken. To make it clear: I am talking about the assets that come with the models and are stored in their material's Specular Level channel, not about the RenderTarget. So now I need another information to be stored in the alpha channel, but I cannot make the shader to read it properly! Nomatter what I write into alpha it ends up being 1 (255)! I tried:

1. saving the textures in PNG/TGA formats.
2. turning off pre-computed alpha in model's properties.

Out of every texture available to me (we use Diffuse map, Normal Map and Specular Map) I was only able to read alpha successfully from the Diffuse Map!

Here is how I add specular and normal maps to my model's material in the content processor:

```
if (geometry.Material.Textures.ContainsKey(normalMapKey))
{
    ExternalReference<TextureContent> texRef = geometry.Material.Textures[normalMapKey];
    geometry.Material.Textures.Remove("NormalMap");
    geometry.Material.Textures.Add("NormalMap", texRef);
}

...

foreach (KeyValuePair<String, ExternalReference<TextureContent>> texture
in material.Textures)
{
    if ((texture.Key == "Texture") ||
        (texture.Key == "NormalMap") ||
        (texture.Key == "SpecularMap"))
        mat.Textures.Add(texture.Key, texture.Value);
}

```

In the shader I obviously use:

```
float4 data = tex2D(specularMapSampler, TexCoords);

```

so `data.a` is always 1 in my case, could you suggest a reason?

# Answer
Ok I returned to this question now as our engine started requiring more channels and finally I solved it. I am using a custom content processor, and in such a case the user should manually specify whether he needs premultiplied alpha in the content processor. Or so I concluded :). Basically I added this code into my ConvertMaterial() method:

```
OpaqueDataDictionary processorParameters = new OpaqueDataDictionary();
            processorParameters["ColorKeyColor"] = this.ColorKeyColor;
            processorParameters["ColorKeyEnabled"] = false;
            processorParameters["TextureFormat"] = this.TextureFormat;
            processorParameters["GenerateMipmaps"] = this.GenerateMipmaps;
            processorParameters["ResizeTexturesToPowerOfTwo"] = this.ResizeTexturesToPowerOfTwo;
            processorParameters["PremultiplyTextureAlpha"] = false;
            processorParameters["ColorKeyEnabled"] = false;

            return context.Convert<MaterialContent, MaterialContent>(deferredShadingMaterial, typeof(MaterialProcessor).Name,
                processorParameters);

```

and I could finally read alpha from normal and specular maps, while not having them messed up by alpha. Just remember to never store alpha == 0 as this WILL ruin the other channes and I don't know how to override this.

P.S. I got this working with .tga, did not try other formats.
> 1 votes

# Answer
It's hard to say without seeing all the code. Just guessing here, but what format are you using for your Specular and Normal maps? Are they 4 component formats?
> 0 votes

---
Tags: xna, textures, hlsl, alpha
---


# Question
Title: Is the "impossible object" possible in computer graphics?
This may be a silly question but I want to know the answer to it. I saw this thing called the "impossible object", while they're many different images of this online, it's suppost to be impossible geometry.

Here is an example:

Now as far as logic goes, I know you don't have to obey it in games, such as a flying cow, or an impossible object. So that's out of the way, but what stands in my way is whether or not there is a way to draw this onto a 3D scene. Like is there a way to represent it as a 3D object? Thanks!

# Answer
3D computer graphics works based on the mathematics of 3D space. Objects like that cube cannot exist in 3D space - that's why they're "impossible objects" - so they cannot be directly modeled in computer graphics either.

Of course it is possible to build objects that, when seen from a certain camera angle, produce an optical illusion that makes them *look like* an impossible object.

Or as Jari Komppa commented, it's possible to render things "incorrectly" (mis-sorted for example) and make things look like impossible geometry that way. And there are games that play with 2D/3D perspective deliberately, such as echochrome, Fez, and Perspective.
> 10 votes

# Answer
Sure you can, just modify the geometry as the player goes through.

There was a game called Antichamber that was built entirely around this idea, where the maze changed as you went through it.

So like you start at this point right, where you choose which dir to go

You go up the stairs,

Turn the corner,

Then end up back at the same point

Physically impossible, done with (apparently portals as Nathan says in this post)
> 2 votes

---
Tags: opengl, 3d, directx
---


# Question
Title: OcclusionQuery: how to ignore some objects?
I'm trying to make a LensFlare effect when the player watch the sun in my XNA 4.0 Game.

To do this, I use OcclusionQuery, here's my code:

http://pastebin.com/meAkdwmD

I also have some models, a terrain and a skybox.

Here's my main Draw code:

```
terrain.Draw();
model1.Draw();
model2.Draw();
skybox.Draw();
lensFlare.UpdateOcclusion();
lensFlare.Draw();

```

The problem is that the occlusion considers the sun to be behind the skybox, and the lensFlare wasn't showing up.

So I moved `lensFlare.UpdateOcclusion()` before the drawing of the Skybox, and now the lensFlare appears, but my skybox is blinking (it's like it disappear and reappear at each frames...)

How do I ignore the skybox in the occlusion?

# Answer
> 0 votes
The easiest way is to change the depth range for your skybox. I'm not familiar with XNA but in D3D terms you would create a new viewport with the same size as the one used for your main scene but with MinZ 1.0f, MaxZ 1.0f, then draw the skybox, then restore the original viewport. You could alternatively achieve the same result by writing a depth of 1.0f from your pixel shader (although that wouldn't play nice with early-Z rejection on your GPU).

This ensures that your skybox will always be behind any other scene objects, and has other advantages too; for example, you no longer need to ensure that your skybox geometry is large enough to enclose your entire scene (you could draw it as a 10x10x10 cube if you wished) and you no longer need to have a large enough zFar in your projection matrix to contain it.

---
Tags: xna, occlusion
---