# Question
Title: Getting the Ray position from View and Projection Matrix
I'm having some trouble calculating the direction and position of the ray from my matrices. I have tried some things such as:

```
private Vec3 getPick(Mat4 projection, Mat4 view) {
     Mat4 inverseProject = projection.copy().inverse();
     Mat4 pick = inverseProject.mul(view.copy());
     Vec3 pos = new Vec3(pick.m10, pick.m11, pick.m12);
     return pos;
}

```

I am using custom math classes and I'm pretty sure they work. Also, would it be better to perform this math in my shader? For better performance etc..?

I contacted Notch (creator of Minecraft) on this issue and he told me to inverse the view Matrix and multiply by the projection, then multiply by the mouse coordinates. I tried that, it didn't do much.

EDIT: Tried normalising the screen space. It seems to do the job except in negative directions. Plus its a little off.

```
Vec3 getPick(double w, double h, double ar) {
    double sx = ((Mouse.getX() / w / 2.0) - 1.0) * ar;
    double sw = 1.0 - (2 * ((h - Mouse.getY()) / h));

    Mat4 viewProjInv = view.copy().mul(projection).inverse();
    Vec3 mouseNormal = new Vec3(sx, sw, 1.0);
    Vec3 dir = viewProjInv.mul(mouseNormal);
    return dir.mul(1);
}

```

# Answer
> 1 votes
There are several steps you need to follow that will allow you to pick in a 3D application.

To transform screen coordinates to world space coordinates, you need to denormalize the scree-space coordinates.

Then, you need to multiply the the point of the cursor (assumed object doing the picking) in normalized device space with this matrix.

Then we would need to solve for the device point in regards to normalized space by solving it from the equation that gives us the screen point and viewport dimensions. This would be the origin of the raycast.

See, the thing is, you are half way there, but you are at the last half with the code supplied.

And then, after all of this, you construct your ray and need to do an intersection test with a bounding volume or mesh triangle.

In regards to doing the math in your shader, most likely not, but for something like that you could try making tests to see which is faster. However, rule #1 is don't worry about optimization until you need to. Rule #2 is never optimize.

I have not much experience with lwjgl, but is there a function that you can call that will transform mouse coordinates for you at all and return the vector? Also, you should show how you are calculating the direction as well as the mouse position.

I usually like to answer with source code, but I found this lwjgl java example on how to pick with OpenGL in 3D

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


# Question
Title: How to use mocaps in your game if they don't loop smoothly?
Following suggestions on IRC, I've downloaded, parsed and incorporated the Free Release of 2500 mocaps to my game. I've noticed, though, that none of those loop perfectly. It does not connect and thus won't form proper walking/jumping/etc cycles. So how I'm supposed to use them in my game? Is there a tool or some trick to solve that problem I'm not aware of?

# Answer
> 1 votes
I can suggest the artist’s approach and the engine programmer’s approach.

What an animator would do is rework the animation sequences in an application such as MotionBuilder, Maya, or even the free Blender. The animating features of these tools are quite tricky to use at first, but there are plenty of tutorial videos on the web to get started.

Another method would be to use software blending: dynamically compute a pose that is a blend of the first and last frames of the animation sequence, then add a blend-out from that frame at the beginning of the animation, and a blend-in to that frame at the end. That way, the sequences will always loop properly, though the result won’t probably be as good as if tweaked by a skilled human.

---
Tags: 3d, graphics, animation
---


# Question
Title: Z-order for cocos2d top-down game with sprite batching
I'm trying to understand how to create z-order system like you can see in http://www.realmofthemadgod.com/

Character is above the tree when he is in front of it and vice versa.

Also, I'm planning to use sprite batching and all the sprites will not fit in one texture (2048\*2048 for cocos2d-iphone). So I need to use several batches (like one for background and one for characters).

Additional "top-background" layer with above the character layer will not solve the problem: what if two characters are staying in front and behind a tree at the same time?

So, I'm thinking about some sort of masking but I don't know how to properly implement it.

Example from the RotMG: https://i.stack.imgur.com/d8dAe.png

# Answer
You need to implement a "2.5D" system. Taking the picture as reference, the ground is drawn first, then all the sprites, using Y as the order. Start from the top (y=0), bush, bush, tree, plant, tree, character, tree, stick, and so on. Please note the character has been drawn *before* the tree near him, that's it. TL;DR: Draw sprites according to their Y offset.
> 1 votes

# Answer
It's simple

```
z_order = position_y

```

Where axis origin is top left corner of screen(in cocos2d, it's bottom left). Player has origin at right between his foot. tree has origin at it's root.....

If the map has size of 100x100, and player are at map's limit, his z\_order must be 100.

If 2 character are at the same y position, their z\_order are equal too.
> 1 votes

---
Tags: 2d, cocos2d-iphone, cocos2d
---


# Question
Title: Can I accept unicoins for micro-payments in my game?
I'm developing a free-to-play game on Android and iOS and Facebook. I see that Unicoins can be purchased in many ways, a lot more that I'll ever be able to implement myself (Paypal, Bitcoins, Gold, Reddit karma! I mean: wow!).

Is there a way I can accept them as micro-payments and then turn them back into real money?

# Answer
# Yes

However, there are some restrictions. As stated in the terms:

> Not legal tender **except in localities with citizenship rights for unicorns**

And, a little known fact is that Scotland's national animal, is the **Unicorn**. Also, I'm pretty sure Internetland allows them, 'cause they, like, for sure allow Unicorns.

The majesty of these animals is unparalleled, so I'm not sure why they're not allowed citizenship rights everywhere, but there you have it.

tl;dr

As long as you're operating in Scotland or Internetland you can accept Unicoins.

I apologize, but for technical reasons I cannot currently accept payments with Unicoins for this answer.
> 4 votes

---
Tags: free-to-play, payment
---


# Question
Title: How to translate swipe gestures into rotations?
I am making a snake game. I want to rotate my snake in the direction specified by swiping on the screen, the directions are limited to orthogonals (90 degree increments). It's an android game.

Can someone provide me with an algorithm to rotate a snake given its current rotation, and a swipe direction? As it rotates at 90 degrees correctly but not always in the direction specified by swipe.

# Answer
> 0 votes
You cannot use transform.Rotate because that will always rotate relative to whichever direction is currently facing. What you want to use instead is Transform.eulerAngles which will explicitly set a rotation despite whatever the current rotation is:

transform.eulerAngles = new Vector3(0f, yAngleRotation, 0f); Each swipe direction would have a different yAngleRotation value (I'm not sure exactly which as it depends on what axis and direction your game is on / displayed at). These values would probably each be 0f, 90f, 180f, 270f.

One key thing to note is to make sure you don't just set one axis rotation by itself or you will get bad results... as in don't do this:

// this is very very bad, don't do this!!! transform.eulerAngles.y = yAngleRotation;

Thanks to Leuthil from unity3d forum Who solve my problem. Thanks allot :) all of the others who sincerly tried for me.

---
Tags: unity, rotation, transformation
---


# Question
Title: How do I separate testable game logic from my UI in Cocos2d-x?
I read some articles on why I should separate game logic and UI code: That makes it possible to test game logic code can be independently of the rest. However, I am having trouble implementing this in cocos2d-x.

For example, the model usually depends on a `Point` coordinate and `Sprite` classes of the engine, which belong to the UI part. How can I separate them?

```
class Projectile : public Sprite{
public:
    CC_SYNTHESIZE(cocos2d::Point, _nextPosition, NextPosition);
    static Projectile initWithFile(const char* filename);

    Projectile(void);
    ~Projectile(void);
    virtual void setPosition(const cocos2d::Point & pos);
};

```

I'm really confused how to test this object when I need to set its position in the unit test. How should I structure game code to be testable?

# Answer
ngoaho91 is basically hinting in the right direction but is not spelling it out explicitly, so I will try to make it more explicit.

So you took the framework and started implementing the logic within the separate framework classes. The problem why you can't simply test the game logic in isolation, is because it is not isolated.

You write that you `Projectile` **is a** `Sprite`, but that is simply not true. You use a sprite to visualize your projectile. The first thing is you need to separate your logic from your presentation, so like ngoaho91 said, **without any presentation logic**. You get bonus points if you wrap the logic into a separate library without any links to the presentation framework.

Then you build your presentation either by writing an observer called `ProjectileView` for each projectile or an observer that contains an array of Sprite objects, one for each projectile. For input you would write one object, say called PlayerController. This would then translate the raw inputs into calls on the game logic.

Now with this setup, you can take the game logic and put it through any amount of unit tests.

You may have noticed, I just decried MVC (model-view-controller). There is a valid reason why this pattern has persisted for such a long time, it separates the concerns in the system.

---

Before I finish, I want to give some real world advice. In general and especially the larger the code base becomes, it makes sense to factor your code into well defined chunks of responsibility. But with smaller project this just does not make that much sense, you can overdo it and thus the extra effort is not worth the cost. For example one common pattern is to clump the input handling into the Screen class instead of factoring it out into a separate object. My basic rule of thumb is, refactor when it starts hurting.
> 5 votes

# Answer
Implement your own Point class. That's good design if UI Point is seperate from logic Point.

```
//Point.h
class Point
{
public:
    int x,y;
};

```

Point different to cocos2d::Point. In Projectile class, you include and use it.

```
//Projectile.h
#include "Point.h"
class Projectile
{
public:
    char* image;
    Point* position;
};

```

Then render class, include the logic file.

```
//ProjectileRender.h
#include "Projectile.h"
class ProjectileRender: public cocos2d::Sprite
{
private:
    Projectile* logicMember;
public:
    void Render()
    {
        cocos2d::render(logicMember->image,logicMember->position->x, logicMember->position->y);
    }
}

```

So Projectile is independence to any graphics component. If you need to render or something, call ProjectileRender, and send Projectile\* to it to handle the logic section.
> 5 votes

---
Tags: c++, design-patterns, cocos2d-x, unit-testing
---


title: How to design reward and points system?

text:
# Question
Title: How to design reward and points system?
There are few events in my game, like complete levels , complete puzzles , kill enemies and so on. Each such event will reward the player points and bonus powers. Now each "master" task (for example puzzles) can reward the player different points so the hierarchy can be big. How do I design such module ?

# Answer
> 2 votes
Take a look at this tutorial. You can implement acheivement easily and start there to change acheivement to a reward system pretty easily.

http://gamedevelopment.tutsplus.com/tutorials/how-to-code-unlockable-achievements-for-your-game-a-simple-approach--gamedev-6012

# Answer
> 1 votes
Well, points I imagine would be just a counter really?

If there is only one score, a total "Points" count, then just KISS and use an int, add points to it. If you want to show maybe the amount of points received at the end of the level, add up the different sub type of points and then add them to the total score at the end of the level in some fancy animation to make it more "fun(tm)".

As for knowing how much an enemy or puzzle is worth depends on how you represent those things in your game. If they are classes or loadable files, then just store inside of them how many points they're worth and again, add the values when those events occur such as "completed puzzle" or "enemy dead", grab the point value, add it.

As for powerups, you could define your player to have certain attributes, such as "speed 5" "jump height 10" "can fly? no", then each powerup could just have modifier values which increases or decreases those values. Like:

```
class Powerup {
    float speedMultiplier = 1f; // What value to multiply against speed
    float jumpMultiplier = 1f; // What value to multiply against jump
}

Powerup superJump = new Powerup();
superJump.jumpMultiplier = 4f;

Powerup superSpeed = new Powerup();
superSpeed.speedMultiplier = 4f;

Powerup activePowerup = null;
float baseSpeed = 5;
float baseJump = 10;

if(jump) {
    float height = baseJump;
    if(activePowerup!=null) height *= activePowerup.jumpMultiplier;
}

// etc

```

Then maybe you have a base player stat, then reference to the currently active powerup, and then a "working stat", which is the base stats multiplied by the powerup multipiers, which is what's used in the game.

Or something like that?

I suppose there's an infinite number of ways of doing it, but I think the important thing is to keep whatever you make simple, over engineering a solution for this would be probably the worse thing to do.

---
Tags: game-design, events
---


# Question
Title: How can I support both multiple resolutions and multiple orientations in a game?
I am writing a mobile Android and iOS game. This game is similar to Doodle Jump, but without scrolling. In my game I display a background image that should cover the entire screen. On top of that I draw some 32x32 tile images that make up the platforms. I have three control buttons that are displayed at the bottom of the screen. The score is displayed at the top of the screen.

I am trying to ensure that this game will work on any resolution and can be rotated from landscape to portrait mode and vice versa. The player should be able to change orientations without losing sight of any platforms.

I have found several methods for doing this, however they only seem to work if you lock the orientation or skew the images.

* Scaling the content
Won't work because it will skew images too much and look unprofessional.
* Scaling the content and keeping the aspect ratio via letterboxing
The black bars that this introduces can become overwhelming. For example, if I rotate a 960x640 resolution device to portrait, the new resolution will be 640x960. When I tried implementing this, it gave me horrible results.

Portrait:

Landscape:

* Scaling the x,y axis with separate values

```
scaling factor (on x-axis) = screen width in pixels / target width in pixels
scaling factor (on y-axis) = screen height in pixels / target height in pixels

```

This method changes the bounds of the coordinate system, which I am trying to avoid.
* Using a virtual viewport
I like this idea, however it still doesn't seem to work with orientation changes. The variation of aspect ratios seems to be to large when you try this approach for landscape and portrait.

Some good links I found on the topic can be found here
http://blog.gemserk.com/2013/01/22/our-solution-to-handle-multiple-screen-sizes-in-android-part-one/
http://v-play.net/doc/vplay-different-screen-sizes/#approaches-for-content-scaling

I have also thought about only stretching the background image and recalculating the new positions for everything else (player and platforms) when the orientation changes. However, I'm not sure how this would affect collision detection and jumping in real-time. I would rather solve this with a different technique if possible.

It seems like most people just lock their game in one orientation. I am trying to avoid this, if possible.

The bottom line is that all of the methods I listed look to only solve the resolution issue if you lock the orientation. *Is there a way I can support both orientations?*

# Answer
I think that your constraints of "don't letterbox" and "support the same viewable area in both orientations" are irreconcilable. I think you need to relax one of those constraints somewhat, and then your question devolves into the already-asked-and-answered question of handling multiple resolutions (see the "Related Questions" sidebar for a collection of links).

That said, I think how you relax those constraints is an interesting topic on its own. Obviously you can't relax "support both orientations" much. That's a binary issue: you either support them or you don't.

But the letterboxing and viewable area issues are more flexible. Since your game will be relatively unique in supporting both orientations (most games require one or the other), you should further emphasis this point by incorporating some unique gameplay aspects that leverage the decision of which orientation to use. Some things to consider:

* Fill the black letterbox UI with additional, useful UI in portrait mode. Add score multipliers for finishing the level without this "assistant" UI.
* Show less of the playfield horizontally and more vertically when in portrait, and make some levels taller than they are wide. Add score multipliers for finishing levels in the "awkward" orientation.
* If "taller" levels don't make much sense, zoom in a little during portrait mode (still clipping horizontally a bit) but slow down time to compensate for the shorter visual range.
* Further, perhaps portrait mode "pauses" the action entirely, showing controls for selecting different brushes or whatever for painting on the level. So you switch to portrait, paint your platforms, and switch back to landscape.

And so on. By combining some of the above (or coming up with better tweaks more suited to the overall vision of your game), you can leverage what appeared to initially be a disadvantage into something that highlights the *uniqueness* of your game.
> 1 votes

---
Tags: mobile, resolution, aspect-ratio, scale, orientation
---


# Question
Title: How can I assist players navigating narrow grid junctions?
I'm looking for a technique to help the player navigate a narrow path while the character is in constant motion. When changing direction in junctions, it's pretty hard to time the direction change for a successful turn. With bad timing, the character just gets stuck as pictured.

How can I make this easier for the player? (This is for a university assignment.)

# Answer
> 1 votes
You could "hot spot"-check areas adjacent to the character

and immediately begin moving in a free direction if the appropriate movement key is held.

For example, if the player is moving right and holds the downward arrow key, they would continue moving right until the *below hot spot* becomes free. They would then begin moving down.

On platforms that allow multiple directional controls to be triggered simultaneously (such as the arrow keys on a PC), you may want to include an input queue in your control state to ensure the inputs process in order.

The original Pacman used a similar scheme, but even allowed the player to cut corners if they held the controls in the appropriate direction ahead of time like this!

---
Tags: game-mechanics, grid, control, user-experience
---


# Question
Title: XNA 4: GetData from Texture2D and Set it into Texture3D with specific order
I am trying to convert my color grading 2d lookup texture into 3d LUT. When I simply use:

```
ColorAtlas.GetData(data);
ColorAtlas3D.SetData(data);

```

I get this:

I tried building my 2d atlass horizontally but it did not helped - the data was messed up in a different way.

So my question is how can I influence the order of the data I get from the 2d atlas and how can I properly pass it into my 3d atlas?

Update: I know that I can GetData from a specific Rectangular area and put it into several arrays, but the result is still the same. This is what I tried:

```
        Color[] data2D = new Color[0];

        for (int i = 0; i < 32; i++)
        {
            Color[] data = new Color[32 * 32];
            GraphicsDevice.SetRenderTarget(null);

            ColorAtlas.GetData(0, new Rectangle(0, i*32, 32, 32), data, 0, data.Length);

            int oldLength = data2D.Length;

            Array.Resize<Color>(ref data2D, oldLength + data.Length);
            Array.Copy(data, 0, data2D, oldLength, data.Length);
        }
        ColorAtlas3D.SetData(data2D);

```

# Answer
> 1 votes
You were right, Martin. The SurfaceFormat settings were off in the 2d texture. But for anyone wondering, here is a quick map how GetData/SetData works for the default GetData(data)/SetData(data):

So basically your layers should be located BELOW your first picture in the 2d atlass to put them into the 3d texture seamlessly.

---
Tags: xna, color, texture-atlas
---


# Question
Title: Having trouble setting color in fragment shader
For some reason, the color isn't applying to the object. Here's my fragment shader code. There's probably something obvious wrong with it that i'm not seeing.

```
#version 330 core
out vec3 Color;

uniform int InColor;

void main()
{
        Color = vec3(float(127 / 255), 0, 0);
}

```

# Answer
The value `127 / 255` is an integer division and always has the value zero.

You want `vec3(127.0 / 255.0, 0.0, 0.0)` instead.
> 3 votes

---
Tags: opengl, glsl, fragment-shader
---


# Question
Title: Who should handle animations when game logic is separated from rendering?
Suppose I have a tile-based game and I want the step to be 1 tile but also want the movement to be smooth while the player is getting there. If I understand correctly, the only way to achieve this would be making a series of small movements where the increment is a percentage of a tile.

My question is: should the game logic thread send the animations to the rendering thread? What is the best way to go about it?

# Answer
To keep rendering perfectly separate from the game logic, animations - at least the ones that have no game logic impact - are solely done from the "rendering" side. A common pattern is to record the transition using three bits of data:

* Start value
* End value
* Time (between 0 and 1)

The advantage of this approach is that it can be easily fed into an easing function so you can choose a style that suits.

To use this pattern, you detect whenever the player has moved from one tile to another. The **start value** will be the position of **the previous tile**, the **end value** will be that of **the current tile**, but to figure out **time** you need to record **when the player began moving**, and compare that against the **current game time**.

That's not the only method though; a simpler method would be to track the **player's position** in the "rendering" side, and **constantly move** this position **towards the "game logic"'s position**.

But finally, don't be so concerned about having the perfect design, especially when making games; if it's easier to hold some "rendering" data in the "game logic", just do it - you can clean it up later if it's hampering things.
> 2 votes

---
Tags: animation, rendering, scrolling
---


# Question
Title: Optimize state changes within a render queue
I am refactoring some parts of the game engine I am working on. This engine is made in C# with XNA.

The part I have trouble with is shader/material and the render queue. In the new version I will give ability to indicate differents render states per pass within a technique (blend state, rasterizer state, ...). In my engine, all renderables have a material and each material is associated to one technique (thus to one or more passes).

Later, when the game will be running, I will add renderable objects to the render queue and then sort it based on the pass used by each material. What I want to achieve is to reduce states changes between draw calls by first grouping same passes together and then passes with nearly identical states to be as closed as possible to minimize changes. But this solution seems to be problematic when it comes to use technique with more than one pass with completely different states. Passes within a same technique can be completely separated in the render queue and not rendered one after the other. If I say that it's because I have always see multi-passes technique render in a loop and all passes rendered immediately like that :

```
foreach(EffectPass pass in technique.Passes)
{
    /* Update parameters */

    pass.apply();
    graphicsDevice.Draw(...);
}

```

But I don't know if I can deferred pass rendering from a same technique instead of using them one after the other as in the previous example.

Here is an example of what will probably happen with the solution I try to build:

* Shader1
    + TechniqueA
        - Pass1 (State A)
        - Pass2 (State C)
* Shader2
    + TechniqueB
        - Pass1 (State A)
* Shader3
    + TechniqueC
        - Pass1 (State A)

Now I have three models to draw, Model1, Model2 and Model3, each one use a different technique from the previous list. If I add those three models in the render queue I will end up with the following render queue :

-\> Set state A -\> Draw Model1(Pass1) -\> Draw Model2(Pass1) -\> Draw Model3(Pass1) -\> Set state C -\> Draw Model1(Pass2)

We can see that the Model1 will be drawn two times (two passes for the Technique A) but the draw call are separated by others draw call.

I don't know how to resolve this. What will be a good solution to this problem? How can I design my render queue to reduce state changes as much as possible between draw calls.

EDIT:

After searching a little more, I have found this helpful article : http://realtimecollisiondetection.net/blog/?p=86. It seems to be an elegant way to sort object by depth and materials. And in the material id, I can had a pass id to sort same pass together that will allow to reduce state changes.

Currently my renderer draw objects directly in the backbuffer without lights nor shadows, everything is flat. So I will just loop over my render queue and call draw methods. But in a future I will probably implement deferred rendering.

I don't know a lot about it but I know that I have to render my objects in different render target to gather differents informations (Z-buffer, Normal buffer, G-Buffer, ...). I assume that for z-buffer and normal buffer I will use the same shader on every objects no matter which material they use. But for the G-buffer I will use the materials of each object so that means different shaders with different number of pass. If I use the solution in the previous link, if I have an object with a material that needs to do two or more passes, my render queue will have at least two times the object (one for each pass). But for Z-buffer or normal buffer isn't it useless to have the same object multiple times?

What I see is that I will need to have at least two different render queue : one for G-buffer in which an object can be multiple times depending on the number of pass the material require and another render queue for Z-buffer or other buffer in which each objects are only one time. Am I right?

# Answer
> 4 votes
The draw order often implied by tutorials, where you do something like this:

```
for each object:
    for each pass:
        apply pass state
        draw object

```

is actually backwards from how it makes sense to do it in a "real game" context. Rather, you'd be more likely to do something like:

```
for each pass:
    apply pass state
    for each object (grouped by shader/material/mesh/etc):
        draw object

```

Multiple *per-object* passes is almost never what you actually want. Instead, you want to accumulate all the objects that use a certain pass, and then draw all those objects together.

For example, some common passes you'd encounter are:

* Depth pre-pass
* Shadow map pass
* Deferred shading pass
* Decal pass
* Lighting pass
* Forward shading pass
* Translucency pass
* Postprocessing pass
* UI pass

Not every shader will include every one of these passes - for instance, in a deferred renderer, a typical "opaque object" shader might only use the first three passes, a lighting shader would only use the lighting pass, etc.

In cases like this, naturally you want to draw all the objects in the depth pre-pass together, so you'd make a render list that includes all those objects, then apply the pass state once and draw them together. Then you apply the shadow map pass state and draw all the objects that go in the shadow map, and so on.

There are only rare special cases where you actually want per-object passes - for example, subsurface scattering using texture-space diffusion, where you draw the object's lighting into an offscreen render target, blur it, then draw the object on screen using the blurred lighting (3 passes per object). This sort of thing doesn't scale well - it gets very expensive as you add objects - so engine programmers try to avoid it as much as possible.

---
Tags: xna, c#, architecture, rendering, deferred-rendering
---


title: How can I scroll my tile maps?

text:
# Question
Title: How can I scroll my tile maps?
I've been trying to understand how I can use matrix to implement a smooth tile scrolling system but I fail miserably.

So I have a pretty big world stored in a multi-dimensional array which is drawn like this :

```
 for (int i = 0; i < screenHeight / 32; i++)
            for (int j = 0; j < screenWidth  / 32; j++)
               spriteBatch.Draw( texture[i + offsetY][j + offsetX] , screenRectangle[i + offsetY][j + offsetX] , Color.White );

```

Can somebody give me some tips on what to do or at least explain the logic behind the matrix translation?
Thank you.

# Answer
> 1 votes
You really just need a 2D camera and I'm sure you will want it locked onto a sprite on your screen, which is what you mean by smooth scrolling. If you just want a working implementation, you can find one over here working at StackOverflow.

With that out of the way, I'm going to explain a bit how it works on a deeper level.

A matrix is used to perform transformations of some sort, there are a few types. The SpriterBatch has an internal projection matrix that will implictly do a lot of work behind the scenes, so that leaves the two you actually need to implement:

* **World Matrix**. This matrix is actually abstracted away from you in many sorts. When you pass in your coordinates (screen rectangle, or X/Y) and dimensions, you have generated a sort of world matrix. In terms of 2D in MonoGame, you will never need to concern yourself with more than this. You can find more information on the web about this if you want, but it is out of scope for this.
* **View Matrix.** This is what you wanted to create and what the above link will help you create. A view matrix will essentially take all your world objects and transform the screen to "see" these things. That is, it used to move the camera around. This includes your scaling, translations, and the like.

**How is the view matrix composed?**

First of all, it is important to note that transformation order is important.

> In a composite transformation, the order of individual transformations is important. For example, if you first rotate, then scale, then translate, you get a different result than if you first translate, then rotate, then scale. In GDI+, composite transformations are built from left to right. If S, R, and T are scale, rotation, and translation matrices respectively, then the product SRT (in that order) is the matrix of the composite transformation that first scales, then rotates, then translates. The matrix produced by the product SRT is different from the matrix produced by the product TRS.

This article is referring to GDI+, but the concept is similar here in XNA/MonoGame. Order is important.

The above implementation does the transformations like:

* Translate
* Rotate
* Translate
* Scale

Great! Now, let us take a look at why these are done in the particular order.

So, we have something like:

```
         // Create the Transform used by any
         // spritebatch process
         Transform = Matrix.Identity*
                     Matrix.CreateTranslation(-Position.X, -Position.Y, 0)*
                     Matrix.CreateRotationZ(Rotation)*
                     Matrix.CreateTranslation(Origin.X, Origin.Y, 0)*
                     Matrix.CreateScale(new Vector3(Scale, Scale, Scale));

         Origin = ScreenCenter / Scale;

```

The **Position** is typically where you want the center of your camera to be pointing at. This is usually your sprite / main player object. This is usually updated in an Update method of the camera that will take the player position and update this value accordingly. However, you can definitely change the target to other objects or use fancy interpolation to make the camera snap less. This gives a chase effect.

The identity matrix is simply our starting point, you can read more about it on the web, but you can just think of it as your **unit matrix**. Next, we translate to the negative position of where our sprite is. By doing this, we end up offsetting. Rotation is then applied, as we want to rotate around this point. Then, a translation to the center is made. Then, we simply apply our zoom.

If you do these steps in single step, you can see how they directly affect each other.

**A caveat about the mouse...**

It should be noted by doing this, you will transform your game view. However, what about **input?** For the mouse, this is always returned in **screen/view coordinates**. You want this in world space (where your objects are being defined) so we fix this by doing something similar to:

```
Vector2 mouseWorldPosition = Vector2.Transform(mousePosition, Matrix.Invert(viewMatrix));

```

Where viewMatrix is your matrix you passed into your SpriteBatch begin, to begin with.

**Other information**

For extra reading, consider these questions on the StackExchange network:

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


# Question
Title: Correcting Lighting in Stencil Reflections
I'm just playing around with OpenGL seeing how different methods of making shadows and reflections work.

I've been following this tutorial which describes using `GLUT_STENCIL`'s and `MASK`'s to create a reasonable interpretation of a reflection.

Following that and a bit of tweaking to get things to work, I've come up with the code below.

Unfortunately, the lighting isn't correct when the reflection is created.

```
glPushMatrix();
plane();                                                //draw plane that reflection appears on

    glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
    glDepthMask(GL_FALSE);
    glEnable(GL_STENCIL_TEST);
    glStencilFunc(GL_ALWAYS, 1, 0xFFFFFFFF);
    glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);

plane();                                                //draw plane that acts as clipping area for reflection

    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
    glDepthMask(GL_TRUE);
    glStencilFunc(GL_EQUAL, 1, 0xFFFFFFFF);
    glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

    glDisable(GL_DEPTH_TEST);
    glPushMatrix();
    glScalef(1.0f, -1.0f, 1.0f);
    glTranslatef(0,2,0);
    glRotatef(180,0,1,0);

sphere(radius, spherePos);                              //draw object that you want to have a reflection

    glPopMatrix();
    glEnable(GL_DEPTH_TEST);
    glDisable(GL_STENCIL_TEST);

sphere(radius, spherePos);                              //draw object that creates reflection
glPopMatrix();

```

It looked really cool to start with, then I noticed that the light in the reflection isn't correct.

I'm not sure that it's even a simple fix because effectively the reflection is also a sphere but I thought I'd ask here none-the-less.

I've tried various rotations (seen above the first time the sphere is drawn) but it doesn't seem to work. I figure it needs to rotate around the Y and Z axis but that's not correct.

Have I implemented the rotation wrong or is there a way to correct the lighting?

# Answer
> 1 votes
You also need to reflect the lighting environment (i.e. light positions and directions) for the lighting on the reflection to be correct.

It's useful to think about the reflection as being applied to the *camera*, i.e. as part of the view transformation, rather than as part of the model transformation. That way, the logic you already have to ensure lights remain fixed in world space as you move the camera around will also make them do the right thing when the camera gets reflected.

---
Tags: opengl, c++, lighting, reflection-rendering, stencil
---


# Question
Title: Why doesn't my animation stop when I press a key?
I wrote a program that animates two squares diagonally across the screen, from opposite sides. Used Timer object to do so. The squares collide with each other and also with the frame boundary to change directions. The problem is that I added a key listener to stop the animation when you press a particular key, and again restart the animation when you press the same key, but that does not seem to work. The animation is not stopping.

problematic part:-

```
 public Drawing(){

    t=new Timer(10,this);
    t.start();
    addKeyListener(this);
    setFocusable(true);
    if(flag==-1){
        t.stop();
    }
    if(flag==1){
        t.start();
    }
}

```

and this is the keyListener part that changes flag to 1 / -1 :-

```
public void keyPressed(KeyEvent arg0) {
    if(arg0.getKeyCode()==KeyEvent.VK_ENTER || arg0.getKeyCode()==KeyEvent.VK_ESCAPE){
        flag=-(flag);
    }
}

```

i also found out that the value of flag variable is changing perfectly with each keyPressed, but it is not stopping the timer.

# Answer
Your `Drawing` constructor checks `flag` and starts or stops the timer. However, the only code (that you've shown) that could ever set `flag` is in the `keyPressed` callback.

`keyPressed` is called when a key is pressed, and will modify `flag` appropriately, but no code will ever check `flag` again. The `Drawing` constructor already ran to completion, so unless there is code you haven't shown here, nothing will ever stop the timer. Presumably the animation only starts because you initialize `flag` to `-1`.

Why don't you just start and stop the timer inside `keyPressed`?

```
public void keyPressed(KeyEvent arg0) {
  if(arg0.getKeyCode()==KeyEvent.VK_ENTER || arg0.getKeyCode()==KeyEvent.VK_ESCAPE){
    if(t.isRunning()) { // presumably this method or a similar one exists
      t.stop();
    }
    else {
      t.start();
    }
  }
}

```
> 1 votes

---
Tags: java, animation
---


# Question
Title: How can I full-screen a Facebook canvas game?
Is there any way to allow the user to click a button on a Facebook canvas app and allow the app to go full-screen?

If it's possible, is it permitted by Facebook?

# Answer
Sure!

The web has a "request fullscreen" API that you can use (be sure to read up on in the reference section below). Facebook seems to indicate this is allowed to be use, just take a look at this transcript:

> Now that Facebook is crippling Facebook Connect powered games as of December 5, 2012 it is imperative that the allowFullScreen attribute is added to Canvas apps' iframes so that we can utilize HTML5's fullscreen mode in our games.

Then, some time later...

> This should now be resolved. Thanks for your patience.

**Requesting Fullscreen**

Simply retrieve your canvas element and call *requestFullScreen*:

```
(document.getElementById('canvas')).requestFullscreen();

```
> 2 votes

---
Tags: html-canvas, viewport, facebook
---


# Question
Title: Understanding and editing HDR light environments in Photoshop
I'm working with an in-development system that uses `.hdr` environments (equirectangular projection) to provide image-based lighting (IBL) to a 3D rendering. I'm trying to understand what range of values can be stored in an `.hdr` image, and how to edit them in Photoshop.

In Photoshop, I can open (or create) `.hdr` images with 32-bits per channel. In this mode, 'normal' colors have RGB values in the range `0.0` \- `1.0`. However, I can pick colors that go as high as `20.0` in each channel. I thus assumed that a value of `20.0` was the maximum that could be stored in a `.hdr` file.

However, if I fill a region with brightest white (`20.0`,`20.0`,`20.0`), and then fill again with (`4.0`,`4.0`,`4.0`) on Multiply mode, I end up with colors that have a value of ~80 (as reported by the Info palette in 32-bit mode). Do it again and I get ~320. I can keep repeating the multiplication and the values shown in the Info palette get successively larger, until the Info palette display maxes out at -231 (`-2,147,483,648`).

Some of the free `.hdr` panoramas that I have found online max out with the sun at around `20` brightness. Some of them, however, max out at `16000` or so. The result is that there are massive tone mapping differences needed between different environments that should be equivalent, e.g. both are a sunny day outdoors. I want to normalize the maps we use and generate, but I first need to figure out what "good" values are for the sun, sky, and ground.

* **What is the largest channel value represented in a `.hdr` image?**
* **What is the significance of Photoshop's `20.0` maximum for a color?**

---

**Edit**: Manually entering RGB channel values of `1`, `4`, `10`, and `20` and painting one pixel using them shows the following results. The fifth square was painted with RGB of `(20,20,20)` on `Normal` mode, and then painted again with RGB of `(4,4,4)` using `Multiply` mode. The color of this pixel is shown at the top of the Info palette. (The first RGB entry is set to `Actual Color`, while the second is set to `RGB`; both readouts are set to 32-bit, as shown.)

Note that these colors are obtained by typing values in the RGB channels of the Color Picker (section "D" in the picture below from Adobe's help), NOT by using the "Intensity: \[\______\] stops" entry. Typing in RGB values of `20.0` sets the Intensity to `4.73` stops. Entering larger intensity values—up to a maximum of 20.0—still results in the RGB values showing `20.0` each in the color picker, but the resulting paint showing larger RGB values of up to 786432 in the Info palette.

Photoshop CS3 HDR Color Picker http://livedocs.adobe.com/en\_US/Photoshop//10.0/images/im\_hdr\_picker.png

As described above, however, even this "largest" value can be made even larger by multiplying the color.

# Answer
The .hdr format represents colors using a variant of floating-point format, so its maximum value is similar to that of float, i.e. about 10^38.

In practice, you will likely not see values this large, but as you've found, different .hdr files may have very different value ranges. There is no standard for what the values in an .hdr image "mean". They could be measured in some physical unit such as nits or foot-lamberts, or they could be measured relative to some arbitrary reference value. There is no way to normalize .hdrs from different sources to the same range without either knowing how they were captured and processed, using some independently calibrated data for expected values of the sky etc. (for instance, measured with a spot meter), or simply eyeballing it.

As for Photoshop and the 20.0 limit, that's actually not an HDR value directly but a value on a log2 scale. When you work with exposure or see references to "stops" (as in the HDR color picker) in Photoshop, that means a log2 scale, i.e. each "stop" is 2x as bright as the previous stop. So 20.0 here actually means 2^20. Indeed if you pick white with intensity 20 stops and fill an image with it, then look in the info palette set to 32-bit mode, you'll see the value is 1048576, which equals 2^20.

At the opposite end of the spectrum you can set the intensity to -20.0 stops, which is 2^-20 or about 0.00000095. (Unfortunately, such small values will simply read as zero in the info palette.)

There is no significance to this \[-20, +20\] range other than that some programmer at Adobe decided this would probably be a big enough range for most purposes.

Screenshot of the color picker and info palette, illustrating the log scale:
> 2 votes

---
Tags: 3d, rendering, lighting, hdr
---


title: Incorrect sprite rotation with atan2()

text:
# Question
Title: Incorrect sprite rotation with atan2()
I want to rotate a sprite so that it faces the mouse cursor/screen touch location. Currently I'm using the following method to compute the angle of rotation. The input position is the target point the sprite must face:

```
- (void) moveToPosition: (CGPoint)pos
{
    moveTarget = pos;
    const float targetX = (moveTarget.x - self.position.x);
    const float targetY = (moveTarget.y - self.position.y);
    const float angle   = atan2(targetX, targetY);
    targetAngle = ClampF(CC_RADIANS_TO_DEGREES(angle), -180.0f, 180.0f);
}

```

Then in the *update* method, which is called every frame, I do a linear interpolation between the target angle and the current, to ensure a smooth rotation:

```
- (void) update
{
    const float currentAngle = self.rotation;
    if (currentAngle != targetAngle)
    {
        const float newAngle = LerpF(currentAngle, targetAngle, [self getTurnSpeed] * Time.deltaTime);
        self.rotation = newAngle;
    }
}

```

This setup works OK, except when the target angle gets close to 180/-180 degrees. When it gets there the sprite just spins the whole way around in a very wacky manner. I've recorded a short video to illustrate.

Which would be the best way to handle these cases, when the angle wraps, and fix this weird spin effect caused by it?

# Answer
> 2 votes
Let's speak radians. Your angle is clamped to a real range and from what I can see from your video I would say between `−π/2` and `3π/2`. Now you can also view angles in different ways, for example as points on a circle. This is clearly the intuitive way to see your problem : in your case the tip of your ship is the considered “angle point” on the circle. The advantage of viewing angles on a circle is that you have no discontinuities, i.e. that `-π/2` and `π/2` are actually the same point. This way your problem is obvious :

You're trying to interpolate from an angle a little on the right of the south angle—it therefore has a value somewhat larger than `-π/2`— and an angle a little on the left—it has a value a little less than `3π/2`. Look at the circle on the right.

But you're using angle value on the real line (see the right line on the figure), which means that when you interpolate two angles (you current ship rotation and the target ship rotation), you go all way through `0` to connect a value close to `-π/2` to a value close to `3π/2` (the gray part of the line in the image). You need to take into consideration the “jump” at `3π/2 = −π/2` of the angle representation to move along the correct path. The correct path is in the black arrow on the line in the image. It corresponds to the path made of the black arrow in the circle. The easiest way is to compute the distance between your start angle and your target angle on the real line (i.e. the absolute value of the difference between the two angles), and check if that distance is larger than `π` (i.e. larger than a half-circle). If it is, add  to the smallest angle. Then you can interpolate the angles and possibly remap the interpolated value to the correct range if required.

---
Tags: 2d, sprites, cocos2d-iphone, objective-c
---


title: How to poll input for a gui in libgdx?

text:
# Question
Title: How to poll input for a gui in libgdx?
Ok, so my question is simple. How do you poll input with a GUI class without it affecting what's underneath the GUI? So suppose you have an RPG game with a gui for the d-pad and other controls:

```
gui.getInput(); //User taps button in the gui
world.getInput(); //The tap should have only affected the gui, but instead goes through and also affects the world

```

How can you deal with this problem? I thought of some ways but I don't like them.

# Answer
Trust me look into Scene2D. It handles everything input related for you. You can even do timed based actions on it, which are very nice. **Its also built into libGDX.** Truuuuust me its super easy once you get the hang of it. Honestly, I now write everything in Scene2D.

If your having issues getting started with it, Heres a little sample code for you

```
 Stage stage;
    ImageButton title; //(there are several types of these, even just simply Image)
    InputListener titleListen; //(also several variants)

 ///----------------------------------------
    //init phase
            stage = new Stage();
            stage.setViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
            Gdx.input.setInputProcessor(stage); //important

            titleListen = new InputListener(){
    //many different types of inputs to override
                @Override
                public boolean touchDown(InputEvent event, float x, float y,
                        int pointer, int button) {
                    //something
                    return super.touchDown(event, x, y, pointer, button);
                }

            };

    ImageButtonStyle style = new ImageButtonStyle();
            style.up = new TextureRegionDrawable(assets.title); //has to be a textureregion
            style.down = new TextureRegionDrawable(assets.title);
            title = new ImageButton(style);
            title.setSize(title.getWidth()*assets.scaleX, title.getHeight()*assets.scaleY);
            title.setPosition(whereever);
            stage.addActor(title);//adds it to the Scene
            play.addListener(titleListen); //adds the listener

  ///----------------------------------------
    //game loop
//
//
//
    stage.act(delta); //updates Scene and grabs inputs

    stage.draw(); //draws Scene

```
> 1 votes

---
Tags: java, android, libgdx
---


# Question
Title: What is the actual formula to find the vertices of an animation frame in using a BVH file?
I've read this tutorial and tried many formulas to build the skeleton. I am able to build it without the rotations, but those break everything. This, for example, is a simplified code for one of my attempts:

```
/* Pseudocode using overloaded operators for illustration purposes */
var build_skeleton = function(motion,frame_number){
    positions = [];
    deg_to_rad = Math.PI/180;

    (function travel_tree(node,old_pos){
        pos = [node.offsetX, node.offsetY, node.offsetZ];

        frame = node.frames[frame_number];

        x_rotation = quat_from_axis_angle([1,0,0],frame[2] * deg_ro_rad);
        y_rotation = quat_from_axis_angle([0,1,0],frame[1] * deg_ro_rad);
        z_rotation = quat_from_axis_angle([0,0,1],frame[0] * deg_ro_rad);
        rotation = x_rotation * y_rotation * z_rotation;

        pos = old_pos + apply_quaternion(rotation, pos);

        positions.push(pos);

        node.children.map(function(a){ return travel_tree(a,pos); })
    })(motion.root,[0,0,0]);

    return positions;
};

```

I've tried many variations of this, switching axes, signals etc. Nothing seems to work. So what is the formula to find the positions of the vertexes of an animation on the BVH format?

# Answer
I think that tutorial actually contains all you need. It mentions that the order of rotations is Z, then X, then Y. I don't know Unity's quaternions, but you are either doing Z then Y then X, or the reverse.

Try swapping x\_rotation and y\_rotation when you calculate your final rotation.
> 1 votes

---
Tags: unity, 3d, mathematics, javascript, algorithm
---


title: explosion spritesheet is not working

text:
# Question
Title: explosion spritesheet is not working
I want to do a simple explosion on a collision.Here is my code...

```
public explosion(Texture2D newTexture, Vector2 newPosition)
    {
        texture = newTexture;
        position = newPosition;
        timer = 0f;
        interval = 40f;
        currentFrame = 1;
        spriteWidth = 60;
        spritHeight = 60;
        isVisible = true;
    }

public void Update(GameTime gameTime)
    {
        timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
        if (timer > interval)
        {
            currentFrame++;
            timer = 0f;
        }
        if (currentFrame == 32)
        {
            isVisible = false;
            currentFrame = 0;
        }
        sourceRect = new Rectangle(currentFrame * spriteWidth, 0, spriteWidth, spritHeight);
        origin = new Vector2(sourceRect.Width/2, sourceRect.Height / 2);
    }
    public void Draw(SpriteBatch spriteBatch)
    {
        if (isVisible == true)
        {

            spriteBatch.Draw(texture, position, sourceRect, Color.White, 0f, origin,1.0f, SpriteEffects.None,0);

        }
    }

```

during collision I am loading like this--

```
foreach (Enemy e in this.em.Enemies)
                {
                    if (i.BoundingRectangle.Intersects(e.BoundingRectangle))
                    {
                        explList.Add(new explosion(cm.Load<Texture2D>("Exp"), new Vector2(e.position.X, e.position.Y)));
                        e.OnHit();
                    }
                }

```

problem is instead of appearing one by one frames,frames are moving to the right side one by one in the rectangle.I am totally new to XNA .Pls help...........

# Answer
> 1 votes
Can't comment so I have to do this as an answer. Tried your code and it worked perfectly for me.

Is the sprite you want to draw really 60x60? If not then that is the problem. Your program is taking rectangles of 60x60. If your sprite is smaller than that then your rectangle will also draw a piece of the next sprite. If your sprites are bigger than 60x60 then your sprite will not fit into the rectangle and the part that didn't fit into the rectangle will be in the next currentFrame.

If you don't know how to check your sprite size, then upload your spritesheet somewhere so someone can check for you.

If the above is not the case then I'm wondering if you are using XNA or MonoGame. Or how show how you call the draw (including the spriteBatch.Begin() function).

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


# Question
Title: How do I convert a .dds texture to .png bitmap in C#?
This question is from someone who has not written a line of code for games, but several Game Save editors and other game tools.

I'm working on a Save Editor and would like to display icons of some of the game assets in C# WPF .NET 4.0, or at least convert them to PNG in memory, so I can display them without having to make copies of them. The assets are stored as `.dds` texture files in `BC3_UNorm`.

I've trawled Google results that either use SharpDX or XNA, but all the ones I've found either do not work (as the sample code is for an old version of the library), or I just plain don't understand (in the case of XNA).

How can I load a `BC3_UNorm` Texture file, either in SharpDX, or XNA for conversion? Sample code would be very welcome.

Here's a sample input file.

---

This is the only code I could get running, but it's missing some of the RGBA channels and the output looks nothing like the original:

```
public static System.Windows.Media.Imaging.BitmapSource ConvertTK(string filename)
{
    try
    {
        // Create the graphics device
        using (var graphicsDevice = SharpDX.Toolkit.Graphics.GraphicsDevice.New(SharpDX.Toolkit.Graphics.GraphicsAdapter.Default, SharpDX.Direct3D11.DeviceCreationFlags.SingleThreaded))
        {
            // Load the texture
            using (var texture = SharpDX.Toolkit.Graphics.Texture2D.Load(graphicsDevice, filename))
            {
                // Copy the pixel colors into a byte array
                var bytesPerPixel = 3;
                var pixelChannel = texture.GetData<byte>();
                var pixelData = new byte[pixelChannel.Length * bytesPerPixel];

                // Where are the RGBA channels? It only has 1 byte per pixel!
                for (var i = 0; i < pixelChannel.Length; i++)
                {
                    pixelData[i * bytesPerPixel + 0] = pixelChannel[i];
                    pixelData[i * bytesPerPixel + 1] = pixelChannel[i];
                    pixelData[i * bytesPerPixel + 2] = pixelChannel[i];
                }

                // Result Image is garbage, looks nothing like original .DDS BC3_UNorm file.

                // Create a bitmap source
                var stride = texture.Width * bytesPerPixel;
                return BitmapSource.Create(texture.Width, texture.Height, 96, 96, PixelFormats.Rgb24, null, pixelData, stride);
            }
        }
    }
    catch (Exception ex)
    {

    }

    return null;
}

```

# Answer
> 6 votes
Loading up DirectX (via SharpDX or XNA) to do the conversion is probably overkill.

Why not simply decode the format on the CPU? It's simple enough. There is a DXT decoder in MonoGame you might be able to borrow. (In case the file changes, the latest revision at time of writing is here.)

`BC3_UNORM` is equivalent to `DXT5`, which that will happily decode.

You'll have to read the `.dds` file yourself. The format is pretty simple. Here are the file format details. (Given that you're making save file editors, I'm going to assume that this is not a problem.)

---
Tags: xna, c#, textures, sharpdx, file-format
---


# Question
Title: MMORPG game server data storage performance
When writing a MMORPG game server...

Which storage design is better:

* Should I only save character data from specific times?

+ On character log-out.
    + User disconnect.
    + From time to time. (every few minutes)
* Should I save it immediately? Which would make writing be more extensive.

Other things:

* What is the best practice when dealing with data on a real time MMORPG game?
* Which database is best with being multi-platformed in mind?

# Answer
This is sort of a vague question, but I will take a stab at it.

One thing for certain **you do not want** any of the user disconnects, character logs off or any other long interval saving. This is because if your server crashes you do not want to lose the players last 5h of gameplay. You want to relaunch the server process and be back without as little loss as possible. So basically the only really feasible process is storing almost immediately.

But you could actually take it a step further, use the database as the actual game world representation. Here is a nice article outlining the approach. (Ignore that it claims to be about entity-component system.) The gist of the article series is that the all the game state is in the database and each individual system only communicates with the database.
> 1 votes

---
Tags: databases
---


title: lwjgl slick textures and glTexParameter

text:
# Question
Title: lwjgl slick textures and glTexParameter
How to make textures fill all area as it is specified? I'm getting small gaps if the texture is smaller than area example: gl\_quads setup like these:

```
-1f, 1f, 0,
-0.98f, 1f, 0,
-0.98f, -1f, 0,
-1f, -1f, 0

```

> I get this: https://i.stack.imgur.com/kWJnh.png

Red one's a texture, black is background, ignore it. Texture is imported by slick loader.

> Texture itself: https://i.stack.imgur.com/8x7ZH.png (in case someone will think it has gaps)

Do I need to use a glTexParameter somehow on it? Added a rendering code down below:

```
//VertexArray initialization, vertexSize is 3, amountOfVertices is 8
private void initVertexArrays() {
    borderVertex = BufferUtils.createFloatBuffer(vertexSize
            * amountOfVertices);
    borderVertex.put(new float[] { -1f, 1f, 0, -0.98f, 1f, 0, -0.98f, -1f,
            0, -1f, -1f, 0 });
    borderVertex.flip();

    borderTextureVertex = BufferUtils.createFloatBuffer(vertexSize
            * amountOfVertices);
    borderTextureVertex.put(new float[] { -1f, 1f, 0, -0.98f, 1f, 0,
            -0.98f, -1f, 0, -1f, -1f, 0 });
    borderTextureVertex.flip();

    amountOfArrays = 2;
}
//VertexBufferObject initialization
private void initVBO() {
    borderVertexHandle = glGenBuffers();
    glBindBuffer(GL_ARRAY_BUFFER, borderVertexHandle);
    glBufferData(GL_ARRAY_BUFFER, borderVertex, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    borderTextureHandle = glGenBuffers();
    glBindBuffer(GL_ARRAY_BUFFER, borderTextureHandle);
    glBufferData(GL_ARRAY_BUFFER, borderTextureVertex, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}
//Texture loading with slick
private void setupTextures(){
    borderTexture = TextureDecoder.getTextureAt(borderTextureLocation,
            "PNG");
}
//Rendering part
public void draw() {
    borderTexture.bind();
    glBindBuffer(GL_ARRAY_BUFFER, borderVertexHandle);
    glVertexPointer(vertexSize, GL_FLOAT, 0, 0L);

    glBindBuffer(GL_ARRAY_BUFFER, borderTextureHandle);
    glTexCoordPointer(vertexSize, GL_FLOAT, 0, 0);

    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glDrawArrays(GL_QUADS, 0, amountOfVertices * amountOfArrays);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);
}

```

# Answer
> 0 votes
Firs things first, The texture coordinates are probably not that what you want. You probably want `0, 0, 0, 1, 1, 0, 1, 1` with a size of 2.

Further you are using `glVertexPointer` and `glTexCoordPointer` with the value vertexSize, it is unclear what that is. It is probably 3 or the code would not render. Ensure that this is the number of values per vertex.

The remainder of the code looks sort of ok.

---
Tags: textures, lwjgl, slick
---


# Question
Title: Surface shader ignores lighting in vertexLit path
I want to use a surface shader in VertexLit(not Forward) rendering path. I caused a problem that the compiled shader completely ingnores lighting from the light sources on the scene. Here's the code:

```
Shader "Custom" {
    Properties {
        _MainTex ("Base (RGB)", 2D) = "white" {}
    }
    SubShader {
        Tags { "LightMode" = "Vertex" }
        LOD 200

        Lighting On

        CGPROGRAM
        #pragma surface surf Lambert
        #pragma target 3.0

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
        };

        void surf (Input IN, inout SurfaceOutput o) {
            half4 c = tex2D (_MainTex, IN.uv_MainTex);
            o.Albedo = c.rgb;
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

I really need this shader to work. Please help me.

# Answer
Try delete Tags { "LightMode" = "Vertex" }
> -1 votes

---
Tags: unity, shaders, lighting
---


title: OpenGL ES 2.0 and atlas

text:
# Question
Title: OpenGL ES 2.0 and atlas
I'm trying to draw elements from a texture atlas with OpenGL ES 2.0

Currently, I'm drawing my elements using something like this in the shader:

```
uniform mat4 uCamera;

uniform mat4 uModel;
attribute vec4  aPosition;
attribute vec4  aColor;
attribute vec2  aTextCoord;

uniform vec2 offset;
uniform vec2 scale;

varying lowp vec4 vColor;
varying lowp vec2 vUV;

void main()
{
    vUV = offset + aTextCoord * scale;
    gl_Position = (uCamera * uModel) * aPosition;
    vColor  = aColor;
}

```

For each element to draw I send it's offset and scale to the shader. The problem with this method is: I can't rotate the element but it's not a problem for now.

I would like to know, which is better for performance:

* Send uniforms like that for each element on every frame
* Update quad geometry (uvs) for each element

Thanks!

# Answer
> -1 votes
The only way to go about this is to use Uniforms. You ALWAYS want to keep the Vertexs uv´s in the local space. for the reason that you don't want to have multiple vertex data containing almost the same information.

Offseting and scaling will only happen on a per mesh basis so it wont be that bad for it either. Sometimes it will be on a special case basis and thats fine to since a float4 to the gpu is not that bad of a bandwidth eater.

Compared to pulling all the data in a vertex buffer from the gpu to the cpu to just redefine a few values, and then pipe it down.

---
Tags: shaders, opengl-es2, texture-atlas
---


# Question
Title: What is a reasonable terminal size across Linux distributions?
I'm working on a Curses-based roguelike; it should (and does) work in both Linux and Windows (various flavours of each).

Currently, I'm enforcing a hard requirement of "your terminal size must be `80x25` to play. Please fix it and come back" to ensure I have a consistent UI.

This works on Windows. But not on Linux; it seems that Ubuntu, at least, uses a terminal size of `80x24` instead.

Since Google is not useful, what can I reasonably expect as far as terminal size support across various Linux distros?

(If it is `80x24` or even as low as `80x20`, I can probably work with that.)

# Answer
> 3 votes
Go with classic VT100 dimensions. It's the kind of terminal that such things would be run on when it was actually a game you played on a terminal.

From http://www.columbia.edu/cu/computinghistory/vt100.html I see that the display is 80x24 or 132x14 character cells, optional 132x24.

I don't recall playing it at the 132 resolutions, but 80x24 is "classic"

---
Tags: linux, text-based
---


title: SVG—Adding fire to the roket

text:
# Question
Title: SVG—Adding fire to the roket
as you might expect, I have got a game in development, including a main character—fortunately…

This character is on the one hand represented by a bunch of Box2D bodies and on the other hand, graphically, by a bunch of SVG-Elements. The character is a floating one, a kind of Hovercraft, basically based on this tutorial, but more sophisticated all in all.

The character can jump, too. To visualize the impulse, which gives the »jump-power« some fire blow out of its very ass straight ahead, what should be animated, during its short visible time.

Question: How to animate that bespoken fire? I could use plain css, or JavaScript, or even SVG-Animation Tags themself, **BUT** I would like to ask for the preferred weapon of choice, faced to the fact that time is running out (less than 3 days) **AND** flexibility needed for the customer?

Intentionally I am not posting any code, since I can imagine a solution based on each one of the methods mentioned above, this question is meant to issue the pros and cons, due to time and flexibility.

In this case, all graphics (world, fire, ass, character) are given in SVG and are meant to be displayed as that, whereby the connection between physics and graphics is established by the use of R.U.B.E. I am searching for the most painless way of realization for the ass on fire.

Thanks for reading **and** kind regards to the community!

# Answer
This sounds like a good use for a particle effect.

When the fire is on, spawn multiple, small dots each frame. Assign a slightly different angle (generally facing downward) and slightly different velocity to each particle. Gradually change the color of each particle from yellow to dark-red over the course of its lifetime and remove it when it has reached the final color.
> 2 votes

---
Tags: javascript, box2d, browser-based-games, character, svg
---


# Question
Title: Swing for game development - regarding threads
For those of you who use Swing to develop their real-time Java games. (Meanign a game that constantly updates game state and redraws the screen using a constant loop).

As I see it, there are three main possible approaches to designing games in Swing, in relation to threads:

**1-** Have the entire game (except for especially long-running tasks) **run on the EDT.**

**2-** Have the entire game **run on a non-EDT thread.**

**3-** Have clear seperation between **a thread to constantly run game logic** (a non EDT thread), and **a thread to constantly update the screen** (the EDT).

By your experience and knowledge, which approach is the most common, and/or the most efficient, and/or the most reasonable programming-wise (aka isn't relativley very complex to design)? **Which approach should I use?**

Help would be appreciated :) (I really want to pick up good habits).

**EDIT: Clarification** \- Even if you don't recommend Swing for game development, please answer my question as it is. Thank you

# Answer
> 1 votes
I think you should forget the EDT for graphics because Java's `repaint` mechanism is quite convoluted and unreliable (in terms of fixed refresh rates). For instance, `repaint` request do not have to be executed immediately by the JVM: multiple `repaint` calls may get collapsed into a single `paint` operation. Plus, you have AWT/Swing's entire event mechanism tied to your leg that will slow things down.

Instead, I would suggest to either use a `BufferStrategy` (e.g. through `Canvas`) which uses hardware acceleration.

```
public class Game extends Canvas {
    public void render() {
        BufferStrategy bs = getBufferStrategy();
        if (bs == null) {
            createBufferStrategy(2);
        } else {
            Graphics g = bs.getDrawGraphics();

            // render game

            g.dispose();
            bs.show(); // flip screen
        }
    }
}

```

This is certainly fine for smaller projects. Or for bigger games, consider using an OpenGL wrapper library, such as, e.g., LWJGL.

# Answer
> 1 votes
If you want to use swing, you have to run it on the EDT, so option wouldn't work. As you mentioned any long-running stuff should'nt be on the EDT and any minecraft-like game would be pretty intensive so that makes option 3 the best one. Just make sure that everything in the logic thread is threadsafe and that you use invokeLater() to do anything on the render thread from the logic thread.

---
Tags: java, multithreading, swing
---


# Question
Title: How to know when all 2d rigid bodies have stopped in unity3d?
Is there anyway to know if all 2d rigid bodies in untiy 3d phisics world have stopped?

# Answer
> 0 votes
Here's a brute force way to do it...

```
bool allSleeping = true;
Rigidbody2D[] allBodies = FindObjectsOfType<Rigidbody2D>();

foreach(Rigidbody2D body in allBodies)
{
    if(body.isAwake)
    {
       allSleeping = false;
       break;
    }
}
return allSleeping;

```

Note that FindObjectsOfType is slow - you don't want to do this every frame. If possible, it's better to cache a list of all Rigidbody2D objects and update it as needed, rather than re-fetching it every time you want to check for awake bodies.

# Answer
> 1 votes
You can create a manager script that keeps count of how many rigidbodies are currently not sleeping as so (VERY simple example):

```
using System;
using UnityEngine;
using System.Collections;

public class SleepTracker : MonoBehaviour
{
    public static SleepTracker Instance { get; private set; }

    public event Action onAllObjectsSleeping;

    private int awakeObjects;

    void Awake()
    {
        Instance = this;
    }

    public void IncAwake()
    {
        this.awakeObjects++;
    }

    public void DecrAwake()
    {
        this.awakeObjects--;
        if (this.awakeObjects == 0)
            StartCoroutine(AllObjectsAreSleepingCoroutine());
    }

    private IEnumerator AllObjectsAreSleepingCoroutine()
    {
        yield return new WaitForSeconds(1.0f);
        Debug.Log("All objects are sleeping!");
        if (this.onAllObjectsSleeping != null)
            this.onAllObjectsSleeping();
    }
}

```

And then, in every object you want to keep track, you just put this component:

```
using UnityEngine;
using System.Collections;

public class TrackSleep : MonoBehaviour
{
    private bool eventFired;

    void Start ()
    {
        this.eventFired = false;
        this.rigidbody2D.AddForce(new Vector2(4.0f, 0.0f));
        StartTracking();
    }

    private void StartTracking()
    {
        SleepTracker.Instance.IncAwake();
    }

    void Update ()
    {
        if (this.rigidbody2D.IsSleeping() && !this.eventFired)
        {
            SleepTracker.Instance.DecrAwake();
            this.eventFired = true;
        }
    }
}

```

This way, instead of querying every frame, you simply register/unregister at the correct times. When every rigibody is asleep, the manager will fire the onAllObjectsSleeping event that you can listen to like so:

```
void Awake()
{
    SleepTracker.Instance.onAllObjectsSleeping += DoSomething;
}

private void DoSomething()
{
    // OMG, everybody's asleep!
}

```

This is a every simplified implementation, but you should be able to follow the idea.

---
Tags: unity, physics
---


# Question
Title: How to create a sun billboard with Ogre3d
I've been working with a few different engines alongside trying to code my own project. Rather than rewrite an entire renderer, etc I am using Ogre3d. To begin with I am trying to implement a very basic scene with day/night cycle.

I've created a plane, added a simple model over the plane to simulate ground and an object. I've also created a directional light which I rotate to simulate a moving sun.

```
// Add a sunlight
sunNode = OgreFramework::getSingletonPtr()->m_pSceneMgr->getRootSceneNode()->createChildSceneNode("sunNode");
sunNode->setPosition(0,0,0);

sun = OgreFramework::getSingletonPtr()->m_pSceneMgr->createLight("Sun");
sun->setPosition(0,0,0);
sun->setType(Ogre::Light::LT_DIRECTIONAL);
sun->setDiffuseColour(Ogre::ColourValue(0.7f,0.7f,0.7f));
sun->setSpecularColour(Ogre::ColourValue(0.7f,0.7f,0.7f));
sun->setDirection(Ogre::Vector3(0,0,1));
sunNode->attachObject(sun);

```

In the main loop, prior to rendering I rotate the sunNode with :

```
 // Rotate the sun
 sunNode->pitch(Ogre::Degree(0.05), Ogre::Node::TS_LOCAL);

```

This all works pretty much like a expected. However, I then moved onto adding a billboard to the sunNode in order to render the sun moving through the sky. Creating the billboardset, setting the texture, adding a billboard and attaching it to the sunNode, was pretty straight forward, however, when I compiled and ran the application, the billboard just sat at the lights position (0,0,0) and didn't move.

What would be involved in getting a billboard to track through the sky to render a simple sun?

# Answer
> 1 votes
So, the answer it turns out is to create a child scene node of the sunNode positioning it some distance away.

```
Ogre::SceneNode* sunBBNode = sunNode->createChildSceneNode("sunFlare", Ogre::Vector3(0,0,-1000));

```

Creating the billboard is easy. In this case, I am just using the Examples/Flare material from the default Ogre media.

```
Ogre::BillboardSet* sunBillboardSet = OgreFramework::getSingletonPtr()->m_pSceneMgr->createBillboardSet();
Ogre::Billboard* sunBillboard = sunBillboardSet->createBillboard(Ogre::Vector3(0,0,0));
sunBillboardSet->setMaterialName("Examples/Flare");

```

Then attach the billboardSet to the sunBBNode

```
sunBBNode->attachObject(sunBillboardSet);

```

Since sunBBNode is a child of the sunNode, its position is updated when its parent node is rotated, thus moving the billboard through the sky as expected.

---
Tags: c++, lighting, graphics-programming, ogre, billboarding
---


title: Java: Irrelative Simplex Noise

text:
# Question
Title: Java: Irrelative Simplex Noise
I am stuck in another problem with Noise(I´ve never did this before). Now Terrain is generating and its quite well but its Irrelative to each other. Here is a screenshot

As you might notice Each column of terrain it isn´t smooth, It makes bruscal Height jumps Example: Instead of doing 2 4 6 7, etc It makes 2 14 16 18 28 46, etc

NOTE: This only happens at high amplitude values but in lower amplitudes its not genration any mountains its almost everything smooth

Here is my Terrain Generation Code:

```
  public void GenerateChunk(float offsetX, float amplitude)//I am using a value of 73 for amplitude.
{
    for (int y = 200; y < 400; y += 16)
    {
        for(float x = 0; x < CHUNK_SIZE; x += 1)
        {
                try
                {
                    float height = (float) PerlinNoise.noise(x+offsetX, 0);
                    height *= amplitude;

                    Block B = new Block(Material.DIRT,(int) (offsetX+(x*16)),(int) height + y, new Image("res/Dirt.png"));
                    Blocks.add(B);
                    B.setVisible(true);
                }
                catch (SlickException e)
                {
                    e.printStackTrace();
                }
            }
     }

}

```

And Here is my Simplex Noise Class:

private static int grad3\[\]\[\] = { {1,1,0},{-1,1,0},{1,-1,0},{-1,-1,0}, {1,0,1},{-1,0,1},{1,0,-1},{-1,0,-1}, {0,1,1},{0,-1,1},{0,1,-1},{0,-1,-1}};

```
private static int p[] = { 151,160,137,91,90,15,
                                                131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
                                                190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
                                                88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
                                                77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
                                                102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
                                                135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
                                                5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
                                                223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
                                                129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
                                                251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
                                                49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
                                                138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180};

// To remove the need for index wrapping, double the permutation table length
private static int perm[] = new int[512];
static {
        for(int i = 0; i < 512; i++)
                perm[i] = p[i & 255];
}

// This method is a *lot* faster than using (int)Math.floor(x)
private static int fastfloor(double x) {
        return x > 0 ? (int)x : (int)x - 1;
}

private static double dot(int g[], double x, double y) {
        return g[0] * x + g[1] * y;
}

// 2D simplex noise
public static double noise(double xin, double yin) {
        double n0, n1, n2;

        final double F2 = 0.5 * (Math.sqrt(3.0) - 1.0);
        double s = (xin + yin) * F2;
        int i = fastfloor(xin + s);
        int j = fastfloor(yin + s);

        final double G2 = (3.0 - Math.sqrt(3.0)) / 6.0;
        double t = (i + j) * G2;
        double X0 = i - t;
        double Y0 = j - t;
        double x0 = xin - X0;
        double y0 = yin - Y0;

        int i1, j1;
        if (x0 > y0) {
                i1=1;
                j1=0;
        } else {
                i1 = 0;
                j1 = 1;
        }

        double x1 = x0 - i1 + G2;
        double y1 = y0 - j1 + G2;
        double x2 = x0 - 1.0 + 2.0 * G2;
        double y2 = y0 - 1.0 + 2.0 * G2;

        int ii = i & 255;
        int jj = j & 255;
        int gi0 = perm[ii + perm[jj]] % 12;
        int gi1 = perm[ii + i1 + perm[jj + j1]] % 12;
        int gi2 = perm[ii + 1 + perm[jj + 1]] % 12;

        double t0 = 0.5 - x0 * x0 - y0 * y0;
        if(t0 < 0)
                n0 = 0.0;
        else {
                t0 *= t0;
                n0 = t0 * t0 * dot(grad3[gi0], x0, y0);
        }

        double t1 = 0.5 - x1 * x1 - y1 * y1;
        if(t1 < 0)
                n1 = 0.0;
        else {
                t1 *= t1;
                n1 = t1 * t1 * dot(grad3[gi1], x1, y1);
        }

        double t2 = 0.5 - x2 * x2 - y2 * y2;
        if(t2 < 0)
                n2 = 0.0;
        else {
                t2 *= t2;
                n2 = t2 * t2 * dot(grad3[gi2], x2, y2);
        }

        return 70.0 * (n0 + n1 + n2);
}

public static void genGrad(long seed) {
    Random rnd = new Random(seed);
    for(int i = 0; i < 255; i++)
      p[i] = i;
    for(int i = 0; i < 255; i++) {
      int j = rnd.nextInt(255);
      int nSwap = p[i];
      p[i]  = p[j];
      p[j]  = nSwap;
    }

for(int i = 0; i < 512; i++)
        perm[i] = p[i & 255];
}

```

# Answer
Probably the frequency of the noise is too high. You can control the frequency by scaling the input to the noise function:

```
float height = (float) PerlinNoise.noise(frequency * (x+offsetX), 0);

```

You can then tweak the value as desired. Lower frequencies will produce smoother terrain, with a larger horizontal scale for the bumps. You can then adjust the amplitude to set the desired vertical scale for the bumps.
> 1 votes

---
Tags: java, simplex-noise
---


# Question
Title: Strange quaternion camera streching in WebGL
So after a lot of researching about quaternions I almost got the quaternion camera working. Almost, cause it rotates in a proper way only in a vertical axis. Other rotations stretches and deforms the view (like on a picture below).

##

* Wobbling horizontal moves makes only Z axis stretched

I don't like to post topics like "Please, debug my brain", but I'm in a dead end right now, and I don't know how to fix it.

My implementation looks like this:

1. I Convert an axis-angle rotation to a quaternion and normalize it.
2. Then multiply it with a camera identity quaternion.
3. And then multiply a position of a camera (which is a 4x4 model-view matrix) by a product of above multiplication converted to matrix.

My free quaternion camera class looks like this (for now):

```
function QuaternionCamera() {
    // Fake 4x4 Matrix
    this.position = new Matrix4x3();
    this.rotation = new Quaternion();
}

QuaternionCamera.prototype = {
    verticalRotation: function(angle) {
        this.rotation.multiply(new Quaternion().axisToQuaternion(angle, 0, 1, 0));
        this.position.multiply(this.rotation.quaternionToMatrix());
        this.rotation.makeIdentity();
    },

    horizontalRotation: function(angle) {
        this.rotation.multiply(new Quaternion().axisToQuaternion(angle, 1, 0, 0));
        this.position.multiply(this.rotation.quaternionToMatrix());
        this.rotation.makeIdentity();
    }
};

```

And on mouse movement, it runs this:

```
    camera.verticalRotation(degToRad(deltaX / 6));
    camera.horizontalRotation(degToRad(deltaY / 6));

```

I believe that this is a proper way to do it, so I'll just dump my math library, maybe you could find a typo in there (cause I have checked it a hunderd of times and found nothing): http://pastebin.com/0zYLaR1V

PS How to get rid off an additional little roll when rotating camera around, so it will move in a game fashion way?

PS2 And where did the imaginery numbers gone when implementing quaternion math to programming language?? ^^ This is a true mystery for me.

# Answer
Ahahaha, problem solved, I'm such a math genius ^^: my math library had a typo in function that converts quaternion to a matrix : `1 - 2 * (this.y * this.y - this.z * this.z);` \- minus times minus makes plus, not minus, as in here: http://www.gameprogrammer.net/delphi3dArchive/quaternions\_bestanden/quat1.gif
> 1 votes

---
Tags: javascript, camera, quaternion, webgl
---


# Question
Title: Best logic to create and drop new gems in a Match-3 game
In a simple match-3 game, with a square gems matrix creating and dropping new gems is fairly simple: when needed I generate those gems above the matrix and then I make them fall into the main matrix simulating that common fall-from-the-ceiling behavior.

Let's now imagine I have a matrix with some rock-type gems, the ones that will never move from their position, and I have cleared an entire column via a "powerful" gem. I have something like this:

```
OOO OOO
OOO OOO
OOO OOO
OOO OOO
OOX XOO
OO   OO
O     O
OOOOOOO

```

Here `O` is a normal gem, and `X` is a rock gem, that is fixed in the matrix and will not move from its original position.

When the new gems flow into this matrix, they will eventually move to the left or to the right to fill that big empty space, but each one will be dropped into the same column.

I'm wondering what the best way to drop those new gems is. I clearly cannot simply make them move from the top of the screen directly to their final position (as in the previous case), since the would move diagonally across the other gems (too bad).

I'd like to know what's the easiest and most flexible way to compute and the configure the path that each gem will have to follow.

# Answer
Without ever having implemented this...

First you will have to control every step of the new gems on their way to their final place. Or in other words, move your sprites only on field on your grid and then calculate their next field.

Now generate new gems and drop them into that column. On each step you check if the gem can fall further down. If not check if there is a free space left or right of the gem the new one landed on. Move the gem to one of that free spaces alternating between left and right.

That should fill up the entire field.
> 4 votes

# Answer
There is an algorithm called **BFS** (Breadth-first\_search).

You can apply this algorithm on each empty cell that has a fixed gem above it, to find the nearest top where you can drop a gem and you can also modify the algorithm to build the shortest path to use it in the animation.

The algorithm will try to move in zigzag if it is the shortest path, but you can solve that by making all gems above a fixed are also fixed while searching.

Or you can search for the nearest normal gem, that doesn't has a fixed gem above it and move it to the empty place that has a fixed gem above it.
> 0 votes

---
Tags: c++, cocos2d-x
---


# Question
Title: How are vertices determined complex geometries in an ever changing game state
For example say you wanted to draw a 3D cube you can define an array of hard coded vertices using float3, here is an example. http://msdn.microsoft.com/en-us/library/windows/desktop/jj552949.aspx

But you obviously can't define by hand large and complex changing geometry vertices such as you would have in a game. So I am trying to understand the mechanics behind how these vertices are loaded/interpreted into the Engine.

Another example, you could create a model in say Maya and export this vertex data to say an XML file, then load up the model using GL/DX. So Maya is doing all the work determining the vertex data. You could do this for terrain also, any vertex geometry.

However a game state is constantly updating, it is not static, the camera is constantly moving with user input. So what is the mechanics behind constantly re-evaluating new vertex data depending on user input.

# Answer
It's not very clever—basically you update the data in memory and then call direct3d/openGL/whatever to do a new render at each update. A single rendered image is called a *frame*. So in a video game, you render like 50 frames in a second (written 50 FPS).

As Raxvan, I suggest you to read a book about computer graphics as the subject is vast and cannot be satisfactorily covered in one stackexchange answer.
> 1 votes

---
Tags: c++, architecture, loading, game-state
---


# Question
Title: How do I write a game server with single-threaded networking?
I want to write a game server with one thread for clients message handling and use something like `epoll` to accept network messages. All I/O and database access will be processed in a thread pool and they are asynchronous and non-blocking.

Given such a scheme, how should I handle other events/messages (physics, game logic, etc)? Can I implement methods to handle these messages as a blocking interface in the main thread?

What simple, popular servers exist (using Cocos\*d/Unity as client) that I could look at for an example of this?

# Answer
> 3 votes
A general game loop should suffice, regardless of how many "games" you're handling. I would suggest considering having a threadpool for your "games" and a separate thread pool for your I/O and DB stuff. Say a 16-core server would use 8 threads per pool would be a good start.

The concept is that your main thread runs through the current number of active games and runs a frame on them. The frame does everything from collecting current network messages, handling physics, updating objects, etc.... Then once that frame is done, the main thread runs a frame on the next game instance, and just constantly loops this.

This is how a little card game server concept of mine behaves, and it seems to work just fine with ~10 active sessions, 2-8 people per session, on a 4-core 2.66ghz system that I tested it on. One thing to look out for is that if one "frame" takes an abnormal amount of time, it will severely affect the performance of the rest.

Therefore if you're going with this solution I highly recommend that everything you update is able to take variable delta time steps with potentially large steps without breaking. It means making sure that your physics updates are done correctly, and placing certain limiters so as to avoid those possible slow downs.

As far as open-source solutions, not really the best place to ask for one. Who knows if someone might have something like that, but you're probably better off researching that bit on your own.

# Answer
> 1 votes
In a single-threaded environment, there is usually nothing wrong with processing events right away when they happen.

But in a multi-threaded environment this can lead to race conditions and syncronization issues. For that reason I would recommend you to give each thread an event queue to which other threads can push events. Each thread would lock its event queue in a suitable phase of their loop, process the events in the order they were received, and unlock the queue again.

Make sure you use the appropriate synchronization features of your programming language to ensure that pushing on and processing of the event queues is thread-safe.

# Answer
> 0 votes
Although this is nothing game specific, libuv may be interesting way to implement a server. libuv is the underlying core that is powering node.js, but instead of JavaScript you program in C. (No big deal to integrate into C++.)

The key point behind libuv (and node.js for that matter) is that all the high level logic is executed in the main thread and all lowlevel logic and I/O is offloaded asynchronously.

The classical example is a database, you formulate the request to the database in the main loop, fire off the request and while you wait on the result something else is done. Once the results are back, you process the result **in the main thread**. Buy using the function `uv_queue_work`, you can offload anything on a pool of threads. The awesome thing is, if you factor your code properly you can work with no or almost no synchronization.

In the case of a game server I can imagine something along the lines of the following:

You open a UDP socket and wait for input (not blocking the main thread). When something comes in you handle the request (parsing the UDP packet into a message could be offloaded). And formulate a request against the game world, once that is done you build the answer asynchronously.

While all this is happening every 10ms you trigger a physics update which is executed async. You would sync the game state with the physics kernel in the main loop, but the actual physics computation would be done in a different thread. (All without locking.)

---
Tags: server, multithreading, polling
---


# Question
Title: How to save am image of a screen using JOGL
Hope this is a better place to ask things like this. I have a 2D scene with some sprites drawn in Swing frame. I need them to be saved as an image. The problem is every tutorial I found seem to be obsolete.

I found using glReadPixels and putting result to a BufferedImage should help but all those snippets look stale, API has changed. I'm using JOGL 2.1.5 that is current at the moment.

I have a feeling this should be a widely known use-case for professionals. Any help would be appreciated!

Updated: I adopted some stale snippets (please, don't tell me API hasn't changed significantly, there're dozens of movings and renamings) No the problem is I'm getting black screen in png file. It comes from byte buffer being read to with zeros only.

```
   public static void main(String[] args) {
        TestPNGSaver saver = new TestPNGSaver();
        saver.run();
    }

    private void writeBufferToFile(GLAutoDrawable drawable, File outputFile) {
        int width = drawable.getWidth();
        int height = drawable.getHeight();

        ByteBuffer pixelsRGB = Buffers.newDirectByteBuffer(width * height * 3);

        GL2 gl = drawable.getGL().getGL2();

        gl.glReadBuffer(GL.GL_BACK);
        gl.glPixelStorei(GL.GL_PACK_ALIGNMENT, 1);

        gl.glReadPixels(0, 0, width, height, GL.GL_RGB, GL.GL_UNSIGNED_BYTE, pixelsRGB);

        int[] pixels = new int[width * height];

        int firstByte = width * height * 3;
        int sourceIndex;
        int targetIndex = 0;
        int rowBytesNumber = width * 3;

        for (int row = 0; row < height; row++) {
            firstByte -= rowBytesNumber;
            sourceIndex = firstByte;
            for (int col = 0; col < width; col++) {
                if (pixelsRGB.get(sourceIndex) != 0) {
                    System.out.println(sourceIndex);
                }

                int iR = pixelsRGB.get(sourceIndex++);
                int iG = pixelsRGB.get(sourceIndex++);
                int iB = pixelsRGB.get(sourceIndex++);

                pixels[targetIndex++] = 0xFF000000
                        | ((iR & 0x000000FF) << 16)
                        | ((iG & 0x000000FF) << 8)
                        | (iB & 0x000000FF);
            }

        }

        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        bufferedImage.setRGB(0, 0, width, height, pixels, 0, width);

        try {
            ImageIO.write(bufferedImage, "PNG", outputFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void display(GLAutoDrawable drawable) {
        GL2 gl = drawable.getGL().getGL2();
        gl.glClear(GL.GL_COLOR_BUFFER_BIT);
        gl.glBegin(GL.GL_TRIANGLES);
        gl.glColor3f(1, 0, 0);
        gl.glVertex2f(-1, -1);
        gl.glColor3f(0, 1, 0);
        gl.glVertex2f(0, 1);
        gl.glColor3f(0, 0, 1);
        gl.glVertex2f(1, -1);
        gl.glEnd();
    }

    private void run() {
        GLProfile.initSingleton();
        GLProfile glp = GLProfile.getDefault();
        GLCapabilities caps = new GLCapabilities(glp);
        final GLCanvas canvas = new GLCanvas(caps);
        canvas.addGLEventListener(this);

        Frame frame = new Frame();
        frame.setSize(400, 400);
        frame.add(canvas);
        frame.setVisible(true);

        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                writeBufferToFile(canvas, new File("/whatever/text.png"));
                System.exit(0);
            }
        });
    }

```

# Answer
> 2 votes
OK, you seem to be pretty confused so here is some code I used with LWJGL which is very similar to JOGL. Probably you will have to swap the buffers with arrays, but the code will be almost identicall.

Here is the method that takes screenshot by writing the screen data to a BufferedImage (the width and height are the dimensions of the screen, the buffer get gets the next element in the buffer - next byte in this case):

```
public BufferedImage makeScreenshot() {
    BufferedImage screenshot = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics graphics = screenshot.getGraphics();

    ByteBuffer buffer = BufferUtils.createByteBuffer(width * height * 3);

    glReadPixels(0, 0, width, height, GL_RGB, GL_BYTE, buffer);

    for (int h = 0; h < height; h++) {
        for (int w = 0; w < width; w++) {
            // The color are the three consecutive bytes, it's like referencing
            // to the next consecutive array elements, so we got red, green, blue..
            // red, green, blue, and so on..
            graphics.setColor(new Color( buffer.get()*2, buffer.get()*2, buffer.get()*2 ));
            graphics.drawRect(w,height - h, 1, 1); // height - h is for flipping the image
        }
    }
    return screenshot;
}

```

And here how to write that data to a file:

```
      try {

            BufferedImage screenshot = makeScreenshot();

            ImageIO.write(screenshot, "png", new File("D:/screen.png"));
        } catch (IOException ex) {
             // You know ... what to do here :P
        }

```

Hope I've helped :)

---
Tags: opengl, jogl
---


# Question
Title: How to find the right direction to plug a sword into a rig's hand after projecting it?
I've downloaded BVH animations and projected it following a book. I can now see a 3D moving rig and it looks alright. The problem is, now I want to plug a sword on the hand of the rig, but I don't know which direction it should face. That is because each vertex has a rotation and an offset, so I can calculate their positions, but there is no information available about their normals. How is this done?

Pseudocode of the position finding procedure for illustration

```
calculate_position(bone)
     local = bone.rotation_x * bone.rotation_y * bone.rotation_z # matrices
     local[3] = bone.offset_x
     local[7] = bone.offset_y
     local[11] = bone.offset_z
     global = local * bone.parent.global
     return [global[3], global[7], global[11]]

```

# Answer
I believe it is pretty common to use a bone just to represent the weapon, and pull the rotation from that. Alternative you would keep an extra vertex so you can determine the direction. Depending on what they are holding you might be able to use a fixed rotation from the hand's bone rotation.
> 1 votes

---
Tags: 3d, mathematics, animation, rigging
---