# Question
Title: How should game objects be aware of each other?
I find it hard to find a way to organize game objects so that they are polymorphic but at the same time not polymorphic.

Here's an example: assuming that we want all our objects to `update()` and `draw()`. In order to do that we need to define a base class `GameObject` which have those two virtual pure methods and let polymorphism kicks in:

```
class World {
private:
    std::vector<GameObject*> objects;
public:
    // ...
    update() {
        for (auto& o : objects) o->update();
        for (auto& o : objects) o->draw(window);
    }
};

```

The update method is supposed to take care of whatever state the specific class object needs to update. The fact is that each objects needs to know about the world around them. For example:

* A mine needs to know if someone is colliding with it
* A soldier should know if another team's soldier is in proximity
* A zombie should know where the closest brain, within a radius, is

For passive interactions (like the first one) I was thinking that the collision detection could delegate what to do in specific cases of collisions to the object itself with a `on_collide(GameObject*)`.

Most of the the other informations (like the other two examples) could just be queried by the game world passed to the `update` method. Now the world does not distinguish objects based on their type (it stores all object in a single polymorphic container), so what in fact it will return with an ideal `world.entities_in(center, radius)` is a container of `GameObject*`. But of course the soldier does not want to attack other soldiers from his team and a zombie doesn't case about other zombies. So we need to distinguish the behavior. A solution could be the following:

```
void TeamASoldier::update(const World& world) {
    auto list = world.entities_in(position, eye_sight);
    for (const auto& e : list)
        if (auto enemy = dynamic_cast<TeamBSoldier*>(e))
            // shoot towards enemy
}

void Zombie::update(const World& world) {
    auto list = world.entities_in(position, eye_sight);
    for (const auto& e : list)
        if (auto enemy = dynamic_cast<Human*>(e))
            // go and eat brain
}

```

but of course the number of `dynamic_cast<>` per frame could be horribly high, and we all know how slow `dynamic_cast` can be. The same problem also applies to the `on_collide(GameObject*)` delegate that we discussed earlier.

So what it the ideal way to organize the code so that objects can be aware of other objects and be able to ignore them or take actions based on their type?

# Answer
> 12 votes
Instead of implementing the decision-making of each entity in itself, you could alternatively go for the controller-pattern. You would have central controller classes which are aware of all objects (which matter to them) and control their behavior.

A MovementController would handle the movement of all objects which can move (do the route finding, update positions based on current movement vectors).

A MineBehaviorController would check all the mines and all the soldiers, and command a mine to explode when a soldier gets too close.

A ZombieBehaviorController would check all zombies and the soldiers in their vicinity, pick the best target for each zombie, and command it to move there and attack it (the move itself is handled by the MovementController).

A SoldierBehaviorController would analyze the whole situation and then come up with tactical instructions for all soldiers (you move there, you shoot this, you heal that guy...). The actual execution of these higher-level commands would also be handled by lower-level controllers. When you put some effort into it, you could make the AI capable of quite smart cooperative decisions.

# Answer
> 2 votes
Personally I recommend keeping the draw function out of the Object class itself. I even recommend keeping the Objects location/coordinates out of the Object itself.

That draw() method is going to be dealing with low level rendering API of either OpenGL, OpenGL ES, Direct3D, your wrapping layer on those APIs or an engines API. It might be that you have to swap between then (If you wanted to support OpenGL + OpenGL ES + Direct3D for example.

That GameObject should just contain the basic information about it's visual appearance such as a Mesh or maybe a bigger bundle including shader inputs, animation state and so on.

Also you are going to want a flexible graphics pipeline. What happens if you want to order objects based on their distance to the camera. Or their material type. What happens if you want to draw a 'selected' object a different color. What about if instead of actually rending as soo as you call a draw function on an object, instead it puts it into a command list of actions for the render to take (might be needed for threading). You can do that kind of thing with the other system but it's a PITA.

What I recommend is instead of drawing directly, you bind all the objects you want to another data structure. That binding only really need to have a reference to the objects location and the rendering information.

Your levels/chunks/areas/maps/hubs/wholeworld/whatever get given a spacial index, this contains the objects and returns them based on coordinate queries and could be a simple list or something like an Octree. It could also be a wrapper to something implemented by a 3rd party physics engine as a physics scene. It allows for you to do things like "Query all objects that are in the view of the camera with some extra area around them", or for simpler games where you can just render everything grab the whole list.

Spacial Indexes don't have to contain the actual positioning information. They work by storing objects in tree structures in relation to the location of other objects. They can be though of as a kind of lossy cache allowing a quick lookup of an object based on its position. There's no real need to duplicate your actual X, Y, Z coordinates. Having said that you could if you wanted to keep

In fact your game objects don't even need to contain their own location information. For example an object that hasn't been put into a level shouldn't have x,y,z coordinates, that makes no sense. You can contain that in the special index. If you need to lookup the coordinates of the object based on its actual reference then you will want to have a binding between the object and the scene graph (scene graphs are for returning objects based on coordinates but are slow at returning coordinates based on objects).

When you add an Object to a Level. It will do the following:

1) Create a Location Structure:

```
 class Location {
     float x, y, z; // Or a special Coordinates class, or a vec3 or whatever.
     SpacialIndex& spacialIndex; // Note this could be the area/level/map/whatever here
 };

```

This could also be a reference to an object in a 3rd party physics engines. Or it could be an offset coordinates with a reference to another location (for a tracking camera or an attached object or example). With polymorphism it could be either depending on if it's a static or dynamic object. By keeping a reference to the spacial index here when the coordinates are updated the spacial index can be too.

If you are worried about dynamic memory allocation, use a memory pool.

2) A binding/linking between your object, its location and the scene graph.

```
typedef std::pair<Object, Location> SpacialBinding.

```

3) The Binding is added to the spacial index inside of the level at the appropriate point.

When you are preparing to render.

1) Get the camera (It will just be another object, except it's location will be tracking the players character and your renderer will have a special reference to it, in fact that's all it really needs).

2) Get the camera's SpacialBinding.

3) Get the spacial index from the binding.

4) Query the objects that are (possibly) visible to the camera.

5A) You need to have the visual information processed. Textures uploaded to the GPU and so on. This would be best done in advance (such as on level load) but perhaps could be done at runtime (for an open world, you could load stuff when you are nearing a chunk but should still be done in advance).

5B) Optionally build a cached render tree, if you want to depth/material sort or keep track of nearby objects the might be visible at a later time. Otherwise you can just query the spacial index everytime it will depend on your game/performance requirements.

Your renderer will likely need a RenderBinding object that will link between the Object, the coordinates

```
class RenderBinding {
    Object& object;
    RenderInformation& renderInfo;
    Location& location // This could just be a coordinates class.
}

```

Then when you render, just run though the list.

I have used references above but they could be smart pointers, raw pointers, object handles and so on.

EDIT:

```
class Game {
    weak_ptr<Camera> camera;
    Level level1;

    void init() {
        Camera camera(75.0_deg, 1.025_ratio, 1000_meters);
        auto template_player = loadObject("Player.json")
        auto player = level1.addObject(move(player), Position(1.0, 2.0, 3.0));
        level1.addObject(move(camera), getRelativePosition(player));

        auto template_bad_guy = loadObject("BadGuy.json")
        level1.addObject(template_bad_guy, {10, 10, 20});
        level1.addObject(template_bad_guy, {10, 30, 20});
        level1.addObject(move(template_bad_guy), {50, 30, 20});
    }

    void render() {
        camera->getFrustrum();
        auto level = camera->getLocation()->getLevel();
        auto object = level.getVisible(camera);
        for(object : objects) {
            render(objects);
        }
    }

    void render(Object& object) {
        auto ri = object.getRenderInfo();
        renderVBO(ri.getVBO());
    }

    Object loadObject(string file) {
        Object object;
        // Load file from disk and set the properties
        // Upload mesh data, textures to GPU. Load shaders whatever.
        object.setHitPoints(// values from file);
        object.setRenderInfo(// data from 3D api);
    }
}

class Level {
    Octree octree;
    vector<ObjectPtr> objects;
    // NOTE: If your level is mesh based there might also be a BSP here. Or a hightmap for an openworld
    // There could also be a physics scene here.
    ObjectPtr addObject(Object&& object, Position& pos) {
        Location location(pos, level, object);
        objects.emplace_back(object);
        object->setLocation(location)
        return octree.addObject(location);
    }
    vector<Object> getVisible(Camera& camera) {
        auto f = camera.getFtrustrum();
        return octree.getObjectsInFrustrum(f);
    }
    void updatePosition(LocationPtr l) {
        octree->updatePosition(l);
    }
}

class Octree {
    OctreeNode root_node;
    ObjectPtr add(Location&& object) {
        return root_node.add(location);
    }
    vector<ObjectPtr> getObjectsInRadius(const vec3& position, const float& radius) { // pass to root_node };
    vector<ObjectPtr> getObjectsinFrustrum(const FrustrumShape frustrum;) {//...}
    void updatePosition(LocationPtr* l) {
        // Walk up from l.octree_node until you reach the new place
        // Check if objects are colliding
        // l.object.CollidedWith(other)
    }
}

class Object {
    Location location;
    RenderInfo render_info;
    Properties object_props;
    Position getPosition() { return getLocation().position; }
    Location getLocation() { return location; }
    void collidedWith(ObjectPtr other) {
        // if other.isPickup() && object.needs(other.pickupType()) pick it up, play sound whatever
    }
}

class Location {
    Position position;
    LevelPtr level;
    ObjectPtr object;
    OctreeNote octree_node;
    setPosition(Position position) {
        position = position;
        level.updatePosition(this);
    }
}

class Position {
    vec3 coordinates;
    vec3 rotation;
}

class RenderInfo {
    AnimationState anim;
}
class RenderInfo_OpenGL : public RenderInfo {
    GLuint vbo_object;
    GLuint texture_object;
    GLuint shader_object;
}

class Camera: public Object {
    Degrees fov;
    Ratio aspect;
    Meters draw_distance;
    Frustrum getFrustrum() {
        // Use above to make a skewed frustum box
    }
}

```

As for making things 'aware' of each other. That's collision detection. It would be implemented in the Octree probably. You would need to provide some callback in your main object. This stuff is best handled by a proper physics engine such as Bullet. In that case just replace Octree with PhysicsScene and Position with a link to something like CollisionMesh.getPosition().

# Answer
> 1 votes
Use a component based system, in which you have a barebones GameObject that contains 1 or more components which define their behavior.

For example say some object is supposed to move left and right all the time ( a platform ), you might create such a component and attach it to a GameObject.

Now say a game object is supposed to slowly rotate all the time, you could create a separate component which does just that and attach it to the GameObject.

What if you wanted to have a moving platform that also rotated, in a traditional class heirarchy that becomes difficult to do without duplicating code.

The beauty of this system, is that instead of having a Rotatable or a MovingPlatform class, you attach both of those components to the GameObject and you now have a MovingPlatform that AutoRotates.

All the components have a property, 'requiresUpdate' which while true, the GameObject will call the 'update' method on said component. For example, say you have a Draggable component, this component on mouse-down (if it was over the GameObject) can set 'requiresUpdate' to true, and then on mouse-up set it to false. Allowing it to follow the mouse only when the mouse is down.

One of the Tony Hawk Pro Skater developers has the defacto write up on it, and it's well worth reading: http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/

# Answer
> 1 votes
First of all, try to implement features so that objects stay independent of each other, whenever possible. Especially you want to do that for multi threading. In your first code example, the set of all objects could be divided in sets matching the number of CPU cores and be updated very efficiently.

But as you said, interaction with other objects is needed for some features. That means that the state of all objects must be synchronized at some points. In other words, your application must wait for all parallel tasks to finish first, and then apply computations that involve interaction. It is good to reduce the number of these synchronization points, since they always imply that some threads must wait for others to finish.

Therefore, I suggest buffering those information about the objects that are needed from inside other objects. Given such a global buffer, you can update all you objects independent of each other but only dependent on themselves and the global buffer, which is both faster and easier to maintain. At a fixed timestep, say after each frame, update the buffer with the current objects´ state.

So what you do once per frame is 1. buffer the current objects´ state globally, 2. update all objects based on themselves and the buffer, 3. draw your objects and then start over with renewing the buffer.

# Answer
> 1 votes
Favour composition over inheritance.

My strongest advice aside from this would be: Don't get drawn into the mindset of "I want this to be supremely flexible". Flexibility is great, but remember that at some level, *in any finite system* such as a game, there are atomic parts which are used to construct the whole. One way or another, your processing relies on those pre-defined, atomic types. In other words, catering for "any" type of data (if that were possible) wouldn't help you in the long run, if you don't have code to process it. Fundamentally, all code must parse / process data based on known specifications... which means a predefined set of types. How large that set? Up to you.

This article offers insight into the principle of Composition over Inheritance in games development via a robust and performant entity-component architecture.

By building up entities out of (differing) subsets of some superset of predefined components, you offer your AIs concrete, piecemeal ways of comprehending the world and actors around them, by reading those actors' components' states.

---
Tags: c++, architecture
---


# Question
Title: Why isn't my other two constant buffers being updated to the shader?
I posted previously before about my two dynamic buffers not being dynamically updating the constant shader. The tessellation buffer isn't working because I have to manually update the tessellation factor inside the hull shader. I believe the camera position isn't updating either because when I perform distance adaptation the far edges are more tessellated then the what's truly in front of the camera. I have all the buffers set to dynamic. Inside the render loop I have them set as:

Here is the updating map and unmap functions.

```
 D3D11_MAPPED_SUBRESOURCE map;
                 CBUFFER_PER_OBJECT *cBufferTessPerObject;
                 ZeroMemory(&map, sizeof(D3D11_MAPPED_SUBRESOURCE));
                 devcon->Map(mesh.m_constantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map);

                // mesh.worldMatrix = XMMatrixIdentity();
                 mesh.worldMatrix = mesh.translationMatrix;
                 XMMATRIX world = XMMatrixTranspose(mesh.worldMatrix);
                 cBufferTessPerObject = (CBUFFER_PER_OBJECT*)map.pData;

                 cBufferTessPerObject->WorldMatrix = mesh.worldMatrix * CameraView * CameraProjection;
                 cBufferTessPerObject->viewMatrix = CameraView;
                 cBufferTessPerObject->projectionMatrix = CameraProjection;
                 cBufferTessPerObject->modelWorldMatrix = mesh.worldMatrix;
                 cBufferTessPerObject->isSelected = mesh.isSelected;

                 // Finally set the matrix constant buffer in the domain shader with the/ updated values.

                 devcon->Unmap(mesh.m_constantBuffer, 0);

                 cameraConstantBuffer *dataPtr1;
                 ZeroMemory(&map, sizeof(D3D11_MAPPED_SUBRESOURCE));
                 devcon->Map(camCbuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map);
                 dataPtr1 = (cameraConstantBuffer*)map.pData;

                 float cx = XMVectorGetX(CameraPosition);
                 float cy = XMVectorGetY(CameraPosition);
                 float cz = XMVectorGetZ(CameraPosition);

                 dataPtr1->cameraPosition = XMFLOAT3(cx, cy, cz);
                 dataPtr1->padding = 0.0f;
                 devcon->Unmap(camCbuffer, 0);

                 TessellationBufferType *dataPtr2;
                 ZeroMemory(&map, sizeof(D3D11_MAPPED_SUBRESOURCE));
                 devcon->Map(mesh.tessellationBuffer, 0 ,D3D11_MAP_WRITE_DISCARD, 0, &map);
                 dataPtr2 = (TessellationBufferType*)map.pData;

                 mesh.tessellationFactor = tessAmount;
                 dataPtr2->tessellationAmount = mesh.tessellationFactor;
                 dataPtr2->padding = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
                 devcon->Unmap(mesh.tessellationBuffer, 0);

                 mesh.multiBuffers[0] = mesh.m_constantBuffer;
                 mesh.multiBuffers[1] = camCbuffer;
                 mesh.multiBuffers[2] = mesh.tessellationBuffer;

                 devcon->VSSetShader(mesh.m_vertexShader, NULL, 0);
                 devcon->HSSetShader(mesh.m_hullShader, NULL, 0);
                 devcon->DSSetShader(mesh.m_domainShader, NULL, 0);
                 devcon->PSSetShader(mesh.m_pixelShader, NULL, 0);

                 devcon->VSSetConstantBuffers(0, 3, mesh.multiBuffers);
                 devcon->HSSetConstantBuffers(0, 3, mesh.multiBuffers);
                 devcon->DSSetConstantBuffers(0, 3, mesh.multiBuffers);
                 devcon->PSSetConstantBuffers(0, 3, mesh.multiBuffers);

```

I only got that from a directX Sample. Inside the shader file I have the three cbuffer structs.

```
cbuffer ConstantBuffer
{
    float4x4 WorldMatrix;
    float4x4 viewMatrix;
    float4x4 projectionMatrix;
    float4x4 modelWorldMatrix;    // the rotation matrix
    float3 lightvec;      // the light's vector
    float4 lightcol;      // the light's color
    float4 ambientcol;    // the ambient light's color
    bool isSelected;
}

cbuffer cameraBuffer
{
float3 cameraDirection;
float padding;
}

cbuffer TessellationBuffer
{
float tessellationAmount;
float3 padding2;

}

```

Am I missing something or would anyone know why wouldn't my buffers update to the shader file?

# Answer
> 4 votes
When you are calling the VSSetConstantBuffer(), it will locate the diffrent buffers on registers. It might do fine without register semantics in some cases, but this is really bad practice.
To start solving your problem you should start biding your constat buffers with register semantics.
In otherwords, like this:

```
cbuffer DataBuffer : register(b0) {};
cbuffer VertexHelperBuffer : register(b1) {};

```

I would refer you to this article, Microsoft clearly explains whats happening.
Buffer description

Next step is to make sure your Map/Updatesubresource function actualy works. In other words, know if itś returning S\_OK or not.

After that, you can take a pix capture to see if the correct values went down the pipe.
this is a good video on how to use pix if you have visual studio 2012 \<. video

---
Tags: directx
---


title: How do I recruit beta testers?

text:
# Question
Title: How do I recruit beta testers?
We're a small company without enough employees to run a large scale beta in house. The app is geo-location based so we're trying to recruits some beta testers from all over that aren't "friends and family". Are there any sites or communities dedicated to something like this?

# Answer
Personally, I find beta testers via my friend network, colleague or working network like Game Developer group on Facebook or LinkedIn or Twitter and on. But the options should not stop there. You can get ones by using game engine's forums to spread the words about your campaign (if you use 3rd party framework). Anyway, at least, you can start recruiting one by one starting from your interested friend then grow it a little by little and see it from there.
> 1 votes

---
Tags: ios, beta
---


# Question
Title: LibGDX - Check if currently on Android/Desktop
I'm using LibGDX and flixel-android to build a Desktop/Android game. It feels like there should be a way of checking to see if you're currently being run on an Android device, the Desktop, and so on, but I can't find it anywhere. Am I supposed to just pass it down from the individual launchers? Surely LibGDX can just tell me?

# Answer
I think you're after Application querying

```
switch(Gdx.app.getType()) {
   case ApplicationType.Android:
       // android specific code
   case ApplicationType.Desktop:
       // desktop specific code
   case ApplicationType.WebGl:
       /// HTML5 specific code
}

```
> 37 votes

# Answer
Magd's code may have worked at one stage, it didn't with my version of GDX, or certainly not my implementation anyway. I had to change it as follows:

```
switch(Gdx.app.getType()) {
       case Android:
           // android specific code
           TouchPadController.createTouchPad();
       case Desktop:
           // desktop specific code
       case WebGL:
           /// HTML5 specific code

```

}
> 8 votes

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


# Question
Title: Input of mouseclick not always registered in XNA Update method
I have a problem that not all inputs of my mouse events seem to be registered. The update logic is checking a 2 dimensional array of 10x10 . It's logic for a jewel matching game. So when i switch my jewel I can't click on another jewel for like half a second. I tested it with a click counter variable and it doesn't hit the debugger when i click the second time after the jewel switch. Only if I do the second click after waiting half a second longer. Could it be that the update logic is too heavy that while he is executing update logic my click is happening and he doesn't register it?

What am I not seeing here :)? Or doing wrong. It is my first game.

**UPDATE :<br>I changed to Variable time step, then i saw after the reindex of my jewels (so after the switch) i see the elapsedgametime was 380ms. So I guess that is why he doesn't catch the short "Press" of my mouseclick because update method is still busy with executing the reindexing code. Anyone knows how I can deal with this .. Or do I have to start using threads because my update of reindex takes too long?**

**SOLVED : The problem was that in my reindexing code I got out of bound exceptions which I catched and then continued. That catching of exceptions caused a massive lag each time a reindex happened. Now everything runs smoothly and I do not have to worry about a slow Update. But I'm still asking the question.. what should you do If you have really heave update logic where the time to process the logic takes almost a 0.5 second? I guess you need to execute your game logic in multiple threads to reduce the update time? I'm also thinking i'll never have to worry about this for a jewels game :p. It's more for a problem for a heavy physics game with alot of game objects ?**

My function of the update methode looks like this.

```
 public void UpdateBoard()
        {
            currentMouseState = Mouse.GetState();
            if (currentMouseState.LeftButton == ButtonState.Pressed &&
                prevMouseState.LeftButton != ButtonState.Pressed)
            {
                debugCount++;
                if (debugCount == 3)
                {
                    int a = 4;
                }

                leftButtonPressed = true;
            }
            if (this.IsBoardActive() == false)
            {
                UpdatingLogic = true;
                if (leftButtonPressed == true)
                {
                    // this.CheckDropJewels(currentMouseState);
                    this.CheckForSwitch(currentMouseState);
                    if (SwitchFound == true)
                    {
                        reIndexSwitchedJewels = true;
                    }
                    this.MarkJewel(currentMouseState);
                }
                if (CheckForMatches == true)
                {
                    if (this.CheckMatches(5) == true)
                    {
                        this.RemoveMatches();
                        reIndexMissingJewels = true;
                    }
                    else
                    {
                        CheckForMatches = false;
                    }
                }

                UpdatingLogic = false;
                if (currentMouseState.RightButton == ButtonState.Pressed &&
                    prevMouseState.RightButton != ButtonState.Pressed)
                {
                    this.CheckMatches(5);
                }

                this.ReIndex();
                leftButtonPressed = false;
            }

            prevMouseState = currentMouseState;
            this.UpdateJewels();

        }

```

# Answer
I believe the code could be changed to avoid this problem using two boolean variables to store the button clicks, one for each button. For the left button, could be something like this:

```
bool isLeftMouseBtnDown = false;

public void UpdateBoard()
{
    // Mouse events processing.
    currentMouseState = Mouse.GetState();
    // If the current state is pressed.
    if (currentMouseState.LeftButton == ButtonState.Pressed)
    {
        // If the left mouse button was already down, then the user is
        // resting or moving the mouse with the button still down, like a drag.
        // Else, then it is a button down event.
        if (isLeftMouseBtnDown)
        {
            mouseDrag();
        }
        else
        {
            mouseDown();
        }
    }
    else
    {
        // If the button is not pressed, but it was before, it means
        // a mouse up event.
        // Else, the user is moving the mouse without pressing any button.
        if (isLeftMouseBtnDown)
        {
            mouseUp();
        }
        else
        {
            mouseMove();
        }
    }

    // Here comes the code that is independent of mouse events.
    if (CheckForMatches == true)
    {
        if (this.CheckMatches(5) == true)
        {
            this.RemoveMatches();
            reIndexMissingJewels = true;
        }
        else
        {
            CheckForMatches = false;
        }
    }

    this.UpdateJewels();
}

public void mouseDown()
{
    // Example code that is dependent on mouse status.
    debugCount++;
    if (debugCount == 3)
    {
        int a = 4;
    }

    if (this.IsBoardActive() == false)
    {
        UpdatingLogic = true;
        // this.CheckDropJewels(currentMouseState);
        this.CheckForSwitch(currentMouseState);
        if (SwitchFound == true)
        {
            reIndexSwitchedJewels = true;
        }
        this.MarkJewel(currentMouseState);
    }

    UpdatingLogic = false;

    this.ReIndex();

    // Sets the mouse button state as down.
    isLeftMouseBtnDown = true;
}

public void mouseUp()
{
    // Sets the mouse button state as up.
     isLeftMouseBtnDown = false;
}

```
> 0 votes

# Answer
not sure when you are running Mouse.GetState() as this is required to update the state of the previous and current mouseState objects

what i would be looking to do is

```
public void Update(GateTime time)
{
   prevMouseState = currMouseState;
   currMouseState = Mouse.GetState();

   //All Other stuff you want to do
}

```

what you code seems to currently be doing is trying to compare two states (that are at the same state) and comparing opposing booleans but you should post more code for us to be sure
> 0 votes

---
Tags: xna, performance, input, game-loop, monogame
---


# Question
Title: HLSL What you get when you subtract world position from InvertViewProjection.Translation?
In one of NVIDIA's Vertex shaders (the metal one) I found the following code:

```
// transform object normals, tangents, & binormals to world-space:
float4x4 WorldITXf : WorldInverseTranspose < string UIWidget="None"; >;

// provide tranform from "view" or "eye" coords back to world-space:
float4x4 ViewIXf : ViewInverse < string UIWidget="None"; >;
...
float4 Po = float4(IN.Position.xyz,1); // homogeneous location coordinates
float4 Pw = mul(Po,WorldXf);    // convert to "world" space
OUT.WorldView = normalize(ViewIXf[3].xyz - Pw.xyz);

```

The term OUT.WorldView is subsequently used in a Pixel Shader to compute lighting:

```
float3 Ln = normalize(IN.LightVec.xyz);
float3 Nn = normalize(IN.WorldNormal);
float3 Vn = normalize(IN.WorldView);
float3 Hn = normalize(Vn + Ln);
float4 litV = lit(dot(Ln,Nn),dot(Hn,Nn),SpecExpon);
DiffuseContrib = litV.y * Kd * LightColor + AmbiColor;
SpecularContrib = litV.z * LightColor;

```

Can anyone tell me what exactly is WorldView here? And why do they add it to the normal?

PS. Error in the last sentence - they add it to the light vector.

# Answer
It is view direction, last row of inverted View matrix is simply camera position.
> 2 votes

---
Tags: matrix, hlsl, lighting, view
---


# Question
Title: What are the semantics of glRotate and glTranslate's parameters?
I have been trying to play with OpenGL after watching some tutorials and I don't understand how the `glTranslatef` and `glRotatef` functions work. I believe a simple picture would help me.

I understand that `glTranslatef` changes the position of the "camera" (but does it change the position in wich the shapes are getting drawn)?

However, I don't understand the rotation concept at all. If I do `glRotatef(1,0,0,1)` it makes my quad spin around. If I just do `glRotatef(1,0,0,0)` it makes the quad smaller (further away) but if I try to rotate around the X or Y axis, I get a black screen. I don't understand the angle either. Help would be appreciated.

# Answer
As mentioned by others, the function families `glRotate` and `glTranslate` are deprecated, so if you have the ability to use a more modern version of OpenGL, you should.

That said, the concepts you are struggling with are not specific to those two functions, although you may be getting hampered by the fact that those functions are operating on a *matrix stack*, which is somewhat GL-specific.

In 3D graphics, when you send some geometry (vertices) to the CPU to be rendered, that geometry is transformed (on the GPU) by the current 4x4 transformation matrix. In OpenGL (and disregarding for the moment shaders, which are part of the modern programmable pipeline you should eventually become aware of), the convention is to represent that matrix as two matrices: the *modelview* and the *projection* matrix. The OpenGL API allows you to manipulate both of those matrices independently on the CPU-side of the API, and they are concatenated on the GPU prior to a rendering operation.

In legacy OpenGL, where you'd use the `glRotate` and `glTranslate` functions, that CPU-side manipulation is presented to you as a stack of individual matrices, which you push onto via the two functions you are having trouble with. When you call `glRotate` (or `glTranslate`), you specify a single transformation matrix. That matrix is then *multiplied* with whatever matrix is currently on top of the stack for the current matrix mode and the result becomes the new top of the stack.

That's why it's usually important to use `glLoadIdentity` to reset the stacks when you start preparing a new frame, and that's why you can sometimes get unexpected results when you make several matrix function calls in a row, especially since (for matrix multiplication), the order of the multiplication changes the result significantly.

So then, to address your specific questions:

* When you call `glTranslate` you can choose to interpret (in your own head) whether the transform is altering the camera or the objects in the scene. Both representations are valid (although switching between them may mathematically involve switching signs or where in the code you call the function).
* When you call `glRotate` you are creating an axis-angle rotation matrix. Again, you are free to interpret whether this affects the "camera" or the "objects" in the world, as to the API there is no difference.
* The actual parameters to the rotation function are (in order): `angle`, `x`, `y`, and `z`. The `angle` parameter specifies the rotation amount, in degrees, and the (`x`, `y`, `z`) triple represent the components of a vector that defines the rotation axis. OpenGL will normalize the input vector if needed, and the function follows the right-hand rule, so if the vector points "towards" the screen, the rotation will be counter-clockwise.

Based on that, I'd venture to say that the unexpected behavior you are seeing appears to be because you have the parameter order confused -- in your second rotation example, you have asked to create a rotation matrix around the axis `(0, 0, 0)` which is invalid and produces a malformed matrix that does the unexpected things.

Also make sure that

* you switch matrix modes between modelview and projection accordingly (you generally will need to call `glMatrixMode` twice during scene setup, once to set up the projection part of the transform, and again to set up the modelview part.
* you reset the stack after the `glMatrixMode` call using `glLoadIdentity`.
* you perform all calls to the matrix functions *outside* the `glBegin` and `glEnd` pair if you are using them (you should work on moving away from them to modern OpenGL equivalents when you can, however).
> 5 votes

# Answer
I didn't see an actual question in your post so I'm assuming it to be: What are glRotatef and glTranslatef in context of OpenGL.

Well the answer is, **deprecated**! Use another math library instead. I would suggest glm but that is C++, maybe jglm is reasonable? (I wouldn't know)

FYI: glRotatef is a 4x4 matrix implementation of Axis Angle rotation. Translation is straightforward read the math library documentation.
> 0 votes

# Answer
Have a look here for the docs: http://www.opengl.org/sdk/docs/man2/xhtml/glRotate.xml

glRotatef( angleInDegrees, x, y, z );

if you draw a line from 0,0,0 to x,y,z this will give you the axis which you will be rotating about. the angle defines how much you want to rotate about this axis.

make sure you are handling your model view matrix with push/pop or resetting to identity in each frame so that you can make sense of how this works, otherwise you'll be compounding the rotation with with frame and you may not be able to understand what you are doing.
> 0 votes

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


title: infer half vector length in BRDF

text:
# Question
Title: infer half vector length in BRDF
it's my first question on stack.
Is it possible to infer length of the half angle vector for specular lighting from N·L and N·V without the whole view and light vectors?
I may be completely off-track, but I have this gut feeling it's possible... Why? I'm working on a skin shader and I'm already doing one texture lookup with N·L+N·E and one texture lookup for specular with N·H+N·V. The latter one can be transformed into N·L+N·E lookup if only I had the half vector length. Doing so could simplify the shader a bit and move some operations into the pre-computed lookup texture. It would make a huge difference since I'm trying to squeeze as much functionality as possible to a single pass mobile version so instruction **count** matters.

Thanks.

Edit, for clarity, I'm doing something like this:

```
float NdotL = dot(s.Normal, lightDir);
float NdotE = dot(s.Normal, viewDir);

fixed3 diffAndTransl = 2.0 * tex3D(_Lookup3d, half3(diffNdotL, NdotE * 0.5 + 0.5, depth)).rgb;

```

now we have diffuse with SSS and backscattering from lookup everything below could be just a lookup if I had length(h) information when calculating the lookup

```
float3 h = lightDir + viewDir;
float hLen = length(h);
//float3 H = normalize(h);
float3 H = h/hLen;
//float NdotH = dot(s.Normal, H);
float NdotH = (NdotL + NdotE)/hLen;
float EdotH = dot(viewDir, H);

fixed ph_by_fresnelReflectance = tex3D(_Lookup3d, half3(NdotH* 0.5 + 0.5, EdotH * 0.5 + 0.5, s.Gloss)).a;
half spec = saturate(NdotL) * max(ph_by_fresnelReflectance / hLensq, 0 ); // this could go into lookup as well

```

I was thinking I could infer length(h) from NdotL and NdotE when generating the specular lookup to reduce above code. In my mind I was imagining something like a triangle on the plane made by lightDir and viewDir vectors could be thought of in 2D space. Don't the two dot products give me the (half?) angle and since both vectors are of length one, wouldn't it be possible to infer the length of the last side? I tried some trigonometric voodoo programming but with no luck (chord of theta inferred from dot products?). Does anybody have any idea if it's at all possible? Maybe I just need to sleep more.

ps.: I know tex3D won't work well on mobile, just testing the grounds...

# Answer
The trouble is that knowing N·L and N·V doesn't tell you anything about the relative orientation of L and V. Imagine holding L fixed and rotating V around the normal (or vice versa) - it doesn't change N·L and N·V, but the relationship between L and V can change greatly, so N·H will change as well.

For skin shading, you may want to look into Preintegrated Skin Rendering by Eric Penner. It's a cheap enough technique that it can certainly run on mobile. It uses a lookup texture based on geometric curvature and N·L, as well as a pre-blurred normal map (which can just be a higher mip level of the regular normal map).
> 1 votes

# Answer
Well, I don't think you can infer the half vector without using the view vector and light vector, or even pre-compute the half vector.

The problem is with the whole specular lighting concept in the blinn-phong model, specular lighting is dependant on the viewer, the specular term will be different for two people looking at the object and standing at different locations.

Unless you have both the light and the viewer at fixed a fixed positions, -the light can be fixed - but fixing the viewer though, is usually not possible, you won't be able to pre-compute it. If you have your camera with minimal movement you can get away with a pre-computed light texture (read:lightmap).

There are other shading algorithms but I doubt you will find any that can model the specular lighting without calculating the Reflection or the Half vector.
> 0 votes

---
Tags: shaders, trigonometry, mathematics
---


# Question
Title: Action Script 3.0 datatype to match C++ iterator? (Code convertion)
I am developing a game with Action Script 3.0 using Starling Framework, converting it from C++

C++ Code :

```
for (std::vector<MyObject*>::iterator i = m_listEnemy->begin();i!= m_listEnemy->end();)
{

    (*i)->update(dt);
    if ( (*i)->m_Hp <=0 )
    {
            (*i)->release();
            i = m_listEnemy->erase(i);
            continue;
    }
    i++;
}

```

MyObject is the class.

What Action Script 3.0 data type matches the C++ iterator? Also , how can I convert this C++ code to Action Script 3.0 code? Thanks in advance!

# Answer
> 1 votes
Different approaches:

```
for each (var value:MyObject in array)
{
   ...
}

for (var index:int in array) /*or (var prop:* in obj)*/
{
   var value:MyObject = array[index]; //or var value = obj[prop]
   ...
}

for (var i:int = 0; i < array.length; i++)
{
   var value:MyObject = array[index];
   ...
}

```

There are no native iterators in AS3. You can however download polygonal's game dev libraries if you want mature, advanced data access capabilities. These libraries are sort of like Boost for AS3 :)

---
Tags: c++, actionscript-3, starling
---


# Question
Title: How to implement lockstep model for RTS game?
In my effort to learn programming I'm trying to make a small RTS style game. I've googled and read a lot of articles and gamedev q&a's on the topic of lockstep synchronization in multiplayer RTS games, but am still having trouble wrapping my head around how to implement it in my own game.

I currently have a simple server/client system. For example if player1 selects a unit and gives the command to move it, the client sends the command \[move, unit, coordinates\] to the server, the server runs the pathfinding function and sends \[move, unit, path\] to all clients which then moves the unit and run animations. So far so good, but not synchronized for clients with latency or lower/higher FPS. How can I turn this into a true lockstep system?

Is the right methodology supposed to be something like the following, using the example from above:

Turn 1 start

1. gather command inputs from player1
2. send to the server turn number and commands
3. end turn, increment turn number

The server receives the commands, runs pathfinding and sends the paths to all clients.

Next turn

1. receive paths from server, as well as confirmation that all clients completed previous turn, otherwise pause and wait for that confirmation
2. move units
3. gather new inputs
4. end turn

Is that the gist of it? Should perhaps pathfinding and other game logic be done client side instead of on the server, if so why? Is there anything else I'm missing? I hope someone can break down the concept, so I understand it better.

# Answer
https://gamedev.stackexchange.com/search?q=client+prediction

You'll want to do client side prediction to deal with latency issues.

In essence, do everything exactly as you have set up, but when the client sends the command to the server, the client assumes the command is valid and performs the pathing algorithms and begins moving. The server can then validate and send the command to all clients to simulate while the server performs the actual pathing.

The only time you want to send unit data is when the units are taking a new action. IE: When a unit starts moving up after it has been moving left. The clients assume the unit will continue to move up until they are told otherwise. The same follows for attacking and performing actions.

This style is used a lot in MMO style games like World of Warcraft.

another link: http://gafferongames.com/networking-for-game-programmers/what-every-programmer-needs-to-know-about-game-networking/
> 3 votes

# Answer
Here is how I understand it:

In a lock step networking model, the entire game simulation is ran on each client. This includes path finding.

You should be sending each player's inputs to each client. Each client will then need to be able to process the inputs and run the simulation locally.

The benefit here is it significantly reduces the amount of information sent over the wire. In an RTS you can have thousands of units. In the client/server model you have you would have to send the path information for each unit every game frame.
> 2 votes

---
Tags: networking, rts
---


# Question
Title: How can I simulate a rigid body bounced from a wall in 3D world?
How can I simulate a rigid sword bounced from a wall and hit the ground (like in physical world)?

I want to use this for a simple animation. I can detect the figure and the size of the sword (maybe needed in doing bounce). Rotation can be controlled by quaternions/matrix/euler angles. It should turn the head and do rotations and fly to the ground.

How can I simulate this physical process?

Maybe what I need is an equation and some parameters?

I need these data, and would combine them into my movie file, I use Mathematica to do the thing that generate the movie file(If I have the data, I can also export it into a 3DSMax script for example).

# Answer
> 1 votes
The easiest way to do this is to find yourself a physics engine. Since you're essentially asking how to create a physics engine. The equations and parameters you'd need are those of a collision detection and response system.

If it's just for a simple animation, you can fake it using techniques like Rotoscoping and Onion Skinning to create the animation from a video of a real object hitting a wall and falling.

Or you can use something like Blender, which has a physics engine, to set up and create your animation.

# Answer
> 0 votes
I don't know Mathematica, but if it can load external libraries you might be able to use the Bullet Physics (http://bulletphysics.org/).

---
Tags: physics, rigid-body-dynamics
---


# Question
Title: Need to know the origin and coordinates for 2d texture and 2d/3d vertices in webgl
**Long story short, I know my coordinates are off and I believe my indices might be off.**

I'm trying to render a simple 2d rectangle with a texture in webgl

here's the code I have for the vbo/ibo:

```
rectVertices.vertices = new Float32Array(
[
    -0.5, -0.5,  // Vertice 1, bottom /  left
     0.0,  0.0,  // UV 1

    -0.5,  0.5,  // Vertice 2,    top /  left
     0.0,  1.0,  // UV 2

     0.5,  0.5,  // Vertice 3,    top / right
     1.0,  1.0,  // UV 3

     0.5, -0.5,  // Vertice 4, bottom / right
     1.0,  0.0,  // UV 4
]);

rectVertices.indices = new Int16Array([
    0,1,2,2,0,3
]);

/* I'm assuming the vertices go like this

(-0.5, 0.5) ------ ( 0.5, 0.5)
            |    |
            |    |
(-0.5,-0.5) ------ ( 0.5,-0.5)

with the origin in the middle

and the texture coordinates go like this:

( 0.0, 1.0) ------ ( 1.0, 1.0)
            |    |
            |    |
( 0.0, 0.0) ------ ( 1.0, 0.0)

so as you can see I'm all messed up.

I'm also using:

gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);

*/

```

Here's the output of the program:

the texture I'm using is this:

**So, I guess I need to know the origins, but the triangle strip looks way off.**

I am doing this as well:

```
// create VBO and IBO
vbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
gl.bufferData(gl.ARRAY_BUFFER, triangleVertices.vertices, gl.STATIC_DRAW);

ibo = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, triangleVertices.indices, gl.STATIC_DRAW);

```

and:

```
gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo);

gl.vertexAttribPointer(vertexAttribute ,2, gl.FLOAT, false,FLOAT*2,FLOAT*0); // position
gl.vertexAttribPointer(textureAttribute,2, gl.FLOAT ,false,FLOAT*2,FLOAT*2); // texture
gl.enableVertexAttribArray(vertexAttribute);
gl.enableVertexAttribArray(textureAttribute);

gl.drawElements(gl.TRIANGLE_STRIP, 6, gl.UNSIGNED_SHORT, 0);

```

**It almost seems as though the Vertices and the UV coordinates are getting mixed up.**

# Answer
I think you should start your indices from 0 so it should become:

```
rectVertices.indices = new Int16Array([ 0,1,2,0,2,3  ]);

```

\[Edit\]

It seems you are using triangle strip rather than triangles. The indices you are using are for triangles, which I think is the usual thing to do unless you have some performance issues. Don't use triangle strips as they are meant to be some kind of mesh *compression*.

So you need to change the draw call from GL\_TRIANGLE\_STRIP to GL\_TRIANGLES.

In case you need to use triangles strips check how they should be connected here.
> 2 votes

# Answer
I think you can think of indices as how the vertices in order of as drawing goes. I got stuck on that for a bit because that lost me for a while. If you can imagine taking out a piece of paper, imagine the dots as vertices and drawing a rectangle without lifting up the pencil back to it's original vertex. You've just encountered how indices draw to the graphics card.

Example would be this:

```
Vertex 01: -1.0f, 1.0f, 0.0f
VERTEX 2: 1.0f 1.0f, 0.0f;
vertex 3: -1.0f, -1.0f, 0.0f;
vertex 4: 1.0f, -1.0f, 0.0f;

Indices : 0,1,2,3

```

If you have graph paper or something similar this could help a lot. So you can easily see the indices were drawn from the vertice 0 all the way to the vertex 4.
> 0 votes

---
Tags: textures, coordinates, vertex, webgl
---


title: Making video from 3D gaphics in OpenGL

text:
# Question
Title: Making video from 3D gaphics in OpenGL
What are some of the preferred methods or libraries for creating video from an OpenGL graphics simulation?

For example, I want to create a visualization(video) of an N-Body gravity simulation by rendering non-real-time OpenGL frames.

The simulation is already coded, I just don't know how to convert it to video.

**EDIT:** I am also interested in providing the described functionality: The user can adjust parameters including the time step between captured frames and then initiate the simulation. The user waits for the simulation to complete, and then can watch the results. The user is able to increase or decrease the playback speed of the simulation whereas in slow motion, more frames are used i.e., you see higher resolution time steps, and when the speed is increased, you see lower resolution time steps at a higher rate, but the frames per second flashing on the screen is constant.

# Answer
**The easy way:** Use glReadPixels on the framebuffer every time you are about to swap, then feed these frames into libavcodec / libavformat (ffmpeg).

---

If you would like a video larger than the screen, there is **the hard way:**

Use an FBO to render your frames into a texture, then retrieve your data through glGetTexImage and feed it to your video encoder.

(If performance is absolutely critical for some reason, instead of glGetTexImage, you would ask the graphics driver to do async DMA uploads using a PBO, and use multiple buffers to allow one image to copy & encode while the next renders)
> 3 votes

---
Tags: opengl, video
---


# Question
Title: std::map for storing static const Objects
I am making a game similar to Minecraft, and I am trying to fine a way to keep a map of Block objects sorted by their id. This is almost identical to the way that Minecraft does it, in that they declare a bunch of `static final` Block objects and initialize them, and then the constructor of each block puts a reference of that block into whatever the Java equivalent of a std::map is, so there is a central place to get ids and the Blocks with those ids.

The problem is, that I am making my game in C++, and trying to do the exact same thing. In Block.h, I am declaring the Blocks like so:

```
//Block.h
public:
    static const Block Vacuum;
    static const Block Test;

```

And in Block.cpp I am initializing them like so:

```
//Block.cpp
const Block Block::Vacuum = Block("Vacuum", 0, 0);
const Block Block::Test = Block("Test", 1, 0);

```

The block constructor looks like this:

```
Block::Block(std::string name, uint16 id, uint8 tex)
{
//Check for repeat ids
if (IdInUse(id))
{
    fprintf(stderr, "Block id %u is already in use!", (uint32)id);
    throw std::runtime_error("You cannot reuse block ids!");
}
_id = id;
//Check for repeat names
if (NameInUse(name))
{
    fprintf(stderr, "Block name %s is already in use!", name);
    throw std::runtime_error("You cannot reuse block names!");
}
_name = name;

_tex = tex;
//fprintf(stdout, "Using texture %u\n", _tex);

_transparent = false;
_solidity = 1.0f;

idMap[id] = this;
nameMap[name] = this;
}

```

And finally, the maps that I'm using to store references of Blocks in relation to their names and ids are declared as such:

```
std::map<uint16, Block*> Block::idMap = std::map<uint16, Block*>(); //The map of block ids
std::map<std::string, Block*> Block::nameMap = std::map<std::string, Block*>(); //The map of block names

```

The problem comes when I try to get the Blocks in the maps using a method called `const Block* GetBlock(uint16 id)`, where the last line is `return idMap.at(id);`. This line returns a Block with completely random values like `_visibility = 0xcccc` and such like that, found out through debugging.

So my question is, is there something wrong with the blocks being declared as const obejcts, and then stored at pointers and accessed later on? The reason I cant store them as `Block&` is because that makes a copy of the Block when it is entered, so the block wouldn't have any of the attributes that could be set afterwards in the constructor of any child class, so I think I need to store them as a pointer.

Any help is greatly appreciated, as I don't fully understand pointers yet. Just ask if you need to see any other parts of the code.

# Answer
> The reason I cant store them as Block& is because that makes a copy of the Block when it is entered,

Raw pointers should be avoided when possible.

I'm not sure exactly what you mean by 'makes a copy'. Containers themselves *can't* store raw references. Possibly you are making a function accepting a ref but then putting them into a container with a non-ref.

In C++11 (which I recommend using unless you have compiler restraints) you can also store references in a container with a std::ref or std::cref. You will need to make sure your compiler is compiling in C++11 mode.

```
#include <iostream>
#include <map>
#include <functional>
using namespace std;

class Block {
   public:
      Block(const std::string& name, const int block_id) {
         this->name = name;
         this->block_id = block_id;
      }
   private:
      std::string name;
      int block_id;
};

const Block block_1("Vacuum", 0);

int main(int argc, char* argv[]) {
   std::map<int, std::reference_wrapper<const Block>> array;
   array.insert(std::pair<int, reference_wrapper<const Block>>(0, block_1));
}

```

Otherwise you could make your own simple ref container:

```
class BlockRef {
   public:
      BlockRef(const Block& blockref): blockref_(blockref) {}
      operator const Block& () const { return this->blockref_; }
   private:
      const Block& blockref_;
};

```

You could also make a more advanced one with templates that's generic for any type.

Boost has them also if you are ok with using a library.
> 1 votes

# Answer
First off all To solve your problem, -if that was the only one-, unlike java, C++(MSVC) assigns 0xcccc for uninitialized variables in debug mode, you are not initializing it in the constructor, make sure to initialize all the variables in your class using the initialize list instead of assignment in the constructor, this has two advantage:

1. It has to do with calling the destructor in a throwable constructor.
2. It will only call the constructor and not both the constructor and the assignment operator.

Block::Block(std::string name, uint16 id, uint8 tex):\_visibility (0) {

}

> The reason I cant store them as Block& is because that makes a copy of the Block when it is entered

First of all you need to think of references as Object\* const x; this means the pointer is const and not the object itself. But the real reason you can't store references in stl containers is that:

* T must be default constructible (a reference can only be initilized)
* T must be copyable (a reference cannot be changed after initlization)

> Is there something wrong with the blocks being declared as const obejcts, and then stored at pointers and accessed later on?

Nothing wrong, as far as you are sure of the allocated object lifetime; don't delete it from other pointers referencing it.

You may want to create a class that will manage blocks (e.g. factory,manager etc) this will make managing resources easier.

\[Edit\] This is only a guess: It seems that both your Registry class and your Block object are define static or global. The problem is that C++ does not define the order in which static objects should be allocated. I suggest you create an Init() function that explicitly initialize your Block object by allocating them on the heap.
> 2 votes

---
Tags: opengl, c++, memory
---


# Question
Title: lwjgl request display close when undecorated
I want to create a custom titlebar/border for my display/window so I set the corresponding system property to "true" but how do I send a close request to the window manually to react to the `Display.isCloseRequested()`?

# Answer
> 1 votes
Listen to a preferred event and then do System.exit(0); Then you are good to go! Bear in mind , LWJGL is a OpenGL wrapper , it doesnt include any widgets physics engines and stuff. So make your own button and listen for an event

---
Tags: lwjgl
---


# Question
Title: Why doesn't my GameMaker step event work?
So I want to make some kind of floor that which the player when walks in gets his movement reduced but im having thousand of different issues implementing this since it doesnt appear to do anything ...

So i have tried different way:

1 - I have tried Step Event which had the following script:

```
if keyboard_check(ord('A'))
{
    player.x = -5;
}
if keyboard_check(ord('D'))
{
    player.x = -5;
}
if keyboard_check(ord('W'))
{
    player.x = -5;
}
if keyboard_check(ord('S'))
{
    player.x = -5;
}

```

2 - I have tried a Collision Event with the same code

3- I have tried a Step event with collision detection on a script

None of these options seem to work at all ... Can you help me?

# Answer
From the code , I can tell that you are setting the player's coordinates to -5. You should have a method that calculates the delta(or time/frames passed) and in your render method , draw the player at the x,y after you have setted the players coordinates multiplying them with the players velocity(that you should set in your code). So , here is some pseudo code:

```
//Calculating the delta
 //while initialization for first time:
 frame = currentTime // CALL THIS AT THE START OF YOUR LEVEL
 //while calculating
 delta = currentTime - frame
 frame = current time

//The player instance should have 2 variables , velocityX and velocityY
//Calculating the Δx ,Δy

x = x + (delta * velocityX)//move right
//or
x = x - (delta * velocityX)//move left

//same thing for the Y

```

Hope that this helps!You may have to make huge corrections tough
> 1 votes

---
Tags: game-maker
---


# Question
Title: Problems when rendering code on Nvidia GPU
I am following OpenGL GLSL cookbook 4.0, I have rendered a tesselated quad, as you see in the screenshot below, and i am moving Y coordinate of every vertex using a time based sin function as given in the code in the book.

This program, as you see on the text in the image, runs perfectly on built in Intel HD graphics of my processor, but i have Nvidia GT 555m graphics in my laptop, (which by the way has switchable graphics) when I run the program on the graphic card, the OpenGL shader compilation fails.

It fails on following instruction..

`pos.y = sin.waveAmp * sin(u);`

giving error\>\> `Error C1105 : Cannot call a non-function`

I know this error is coming on the sin(u) function which you see in the instruction. I am not able to understand why? When i removed **sin(u)** from the code, the program ran fine on Nvidia card. Its running with **sin(u)** fine on Intel HD 3000 graphics.

Also, if you notice the program is almost unusable with intel HD 3000 graphics, I am getting only 9FPS, which is not enough. Its too much load for intel HD 3000.

So, sin(X) function is not defined in the OpenGL specification given by Nvidia drivers or something else??

# Answer
> 6 votes
You seem to have a variable called `sin`, and that interferes with the built-in function. Try changing the value name to something else.

---
Tags: opengl, glsl
---


title: OpenGL - zNear and zFar Parameters

text:
# Question
Title: OpenGL - zNear and zFar Parameters
I am trying to figure out what each parameter does. In the meantime I am playing around with glOrtho . I have already understood how everything works except zNear and zFar .

# Answer
Considering the direction you are looking at, any vertices closer to you than znear will not be drawn, and any vertices that are farther than zfar will not be drawn.

If you are at origin, looking at +z direction, if there is a building with z coordinates 120, and your zfar is 100, than you won't see it.
> 1 votes

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


title: Glitch-free cross-fades in HTML5

text:
# Question
Title: Glitch-free cross-fades in HTML5
In my HTML5 canvas game, I need to cross-fade two sprites which have some glow around them. (Glow is backed into sprites.)

Initially, the first sprite is visible. During the cross-fade the first sprite should vanish, and be replaced with the second one. How exactly the cross-fade is done — does not matter, as long as it is smooth and there are no visual glitches.

I've tried two techniques:

1. During the cross-fade I simultaneously interpolate alpha of the first sprite from 1.0 to 0.0, and alpha of the second sprite — from 0.0 to 1.0.

With this technique I can see background in the middle of the cross-fade. That's because both sprites are semi-transparent most of the time.
2. During the cross-fade I first interpolate alpha of the second sprite from 0.0 to 1.0 (first sprite alpha is at 1.0), and then interpolate alpha of the first sprite from 1.0 to 0.0.

With this technique background is not seen, but the glow around sprites flashes during the cross-fide — when both sprites are near the full visibility.

In non-HTML5 game I'd use shaders to do cross-fade separately in RGB and alpha channels. Is there a trick to do the cross-fade I need in HTML5 without visual glitches?

# Answer
It seem to me what you actually want to do is create a canvas where the RGBA value of each pixel is the weighted average of the RGBA values of two pixels from two other canvases.

The Context2d has no functionality for this out-of-the-box. But you can write a function for this yourself. You can use getImageData to extract the content of a canvas as an array of pure RGBA values and you can use putImageData to write pure RGBA values to a canvas.

Here is the algorithm. It assumes that `weight` is a value between 0.0 and 1.0. A value of 0.25 would mean 25% sprite1 and 75% sprite2.

1. use getImageData to get the RGBA values of source1 and source2
2. use createImageData to create an empty target RGBA array
3. iterate the target-array. Set each R, G, B and A value to the corresponding value of `source1 * (1.0 - weight) + source2 * weight`
4. use putImageData to write the target array to the target canvas

Note that getImageData, putImageData and the pixel-based manipulation between them are quite slow because they are not hardware-accelerated. When you want to make a lot of use of this effect, or want to apply it to very large sprites, you should consider caching it.
> 2 votes

# Answer
I've just tried to implement this purely using 2D compositing operations and a secondary canvas, and I don't think it's possible. The problem is that there's no way to parameterize blending other than `globalAlpha`, and that's indistinguishable from the original image being more transparent, because it doesn't modify the compositing operation but rather modifies what compositing sees as the source image.

I recommend you consider switching from 2D-context to WebGL, which would allow you to use shaders to implement custom blending, as you suggest you already know how to do. You would have to rewrite your drawing code but it's still a `<canvas>`.
> 0 votes

---
Tags: graphics, html5, html-canvas
---


# Question
Title: Precision loss when transforming from cartesian to isometric
My goal is to display a tile map in isometric projection. This tile map has 25 tiles across and 25 tiles down. Each tile is 32x32. See below for how I'm accomplishing this.

**World Space**

**World Space to Screen Space Rotation (45 degrees)**

Using a 2D rotation matrix, I use the following:

```
double rotation = Math.PI / 4;
double rotatedX = ((tileWorldX * Math.Cos(rotation)) - ((tileWorldY * Math.Sin(rotation)));
double rotatedY = ((tileWorldX * Math.Sin(rotation)) + (tileWorldY * Math.Cos(rotation)));

```

**World Space to Screen Space Scale (Y-axis reduced by 50%)**

Here I simply scale down the Y value by a factor of 0.5.

**Problem**

And it works, kind of. There are some tiny 1px-2px gaps between some of the tiles when rendering. I think there's some precision loss somewhere, or I'm not understanding how to get these tiles to fit together perfectly. I'm not truncating or converting my values to non-decimal types until I absolutely have to (when I pass to the render method, which only takes integers). I'm not sure how to guarantee pixel perfect rendering precision when I'm rotating and scaling on a level of higher precision. Any advice? Do I need to supply for information?

# Answer
I am actually working on an isometric game right now. Here is how I did my rendering. I start by using images that are already transformed:

The tile itself is 64 x 32, but the actual image is 64 x 64 (there are 16 pixels of padding on top and bottom). This way I can add depth and height to certain tiles. I determine the resulting screen `x` and `y` coordinates like this:

```
screen_x = iso_x * (TILE_WIDTH / 2) - iso_y * (TILE_WIDTH / 2) - (TILE_WIDTH / 2);
screen_y = iso_x * (TILE_HEIGHT / 2) + iso_y * (TILE_HEIGHT / 2);

```

As you can see, we didn't even have to use `sin` or `cos`, and it is much more simple. The reason we subtract `TILE_WIDTH / 2` from the `x`, is because we want `0, 0` in our isometric world to represent the top left corner of the first tile. If we were leave that part out, `0, 0` (or any other coordinate) would actually point right here on the tile:

If you do everything right, it should look something like this:

If you look closely, you will notice that some tiles are overlapping the other tiles. This because the tile extends 3px above the top of the tile (`0, 0` \+ `0, -3`). This is why I have those extra 16 pixels of padding on the top and bottom. It allows me to add depth.

As for the reason why you have gaps, it may not be inaccuracy, but instead the tiles aren't **exactly** the right shape. So if you want, you can use the tile I have above as a template.
> 2 votes

# Answer
If you're willing to draw sprites pixel-by-pixel, you can make the math work. To make sure you don't leave untouched screen pixels, you can use the *inverse* transform.

i.e., instead of mapping source pixels to screen pixels, map screen pixels to source pixels.

Just build your regular transform matrix **M** as you mentioned above, and invert it, so:

screenPixel\[x, y\] = getSourcePixel(**M<sup>-1</sup>** * (x,y))

This may result in some artifacts, but they should be reasonable. We can learn from OpenGL how to handle those gracefully: In OpenGL, a fragment's (screen pixel) color will be chosen according to which polygon contains that fragment's center. OpenGL uses a bias to make sure that if an edge is lies exactly on a fragment center, one polygon is chosen consistently (see section 3.5.1 in OpenGL 1.3 spec). If you treat your source pixels as polygons (quads) you can determine which fragment center is inside which polygon, and choose that polygon's color as the fragment color.
> 0 votes

---
Tags: rendering, matrix, isometric, transformation, scale
---


# Question
Title: Speeding up procedural texture generation
Recently I've begun working on a game that takes place in a procedurally generated solar system. After a bit of a learning curve (having neither worked with Scala, OpenGL 2 ES or Libgdx before), I have a basic tech demo going where you spin around a single procedurally textured planet:

The problem I'm running into is the performance of the texture generation. A quick overview of what I'm doing: a planet is a cube that has been deformed to a sphere. To each side, a n x n (e.g. 256 x 256) texture is applied, which are bundled in one 8n x n texture that is sent to the fragment shader. The last two spaces are not used, they're only there to make sure the width is a power of 2. The texture is currently generated on the CPU, using the updated 2012 version of the simplex noise algorithm linked to in the paper 'Simplex noise demystified'. The scene I'm using to test the algorithm contains two spheres: the planet and the background. Both use a greyscale texture consisting of six octaves of 3D simplex noise, so for example if we choose 128x128 as the texture size there are 128 x 128 x 6 x 2 x 6 = about 1.2 million calls to the noise function.

The closest you will get to the planet is about what's shown in the screenshot and since the game's target resolution is 1280x720 that means I'd prefer to use 512x512 textures. Combine that with the fact the actual textures will of course be more complicated than basic noise (There will be a day and night texture, blended in the fragment shader based on sunlight, and a specular mask. I need noise for continents, terrain color variation, clouds, city lights, etc.) and we're looking at something like 512 x 512 x 6 x 3 x 15 = 70 million noise calls for the planet alone. In the final game, there will be activities when traveling between planets, so a wait of 5 or 10 seconds, possibly 20, would be acceptable since I can calculate the texture in the background while traveling, though obviously the faster the better.

Getting back to our test scene, performance on my PC isn't too terrible, though still too slow considering the final result is going to be about 60 times worse:

```
128x128 : 0.1s
256x256 : 0.4s
512x512 : 1.7s

```

This is after I moved all performance-critical code to Java, since trying to do so in Scala was a lot worse. Running this on my phone (a Samsung Galaxy S3), however, produces a more problematic result:

```
128x128 :  2s
256x256 :  7s
512x512 : 29s

```

Already far too long, and that's not even factoring in the fact that it'll be minutes instead of seconds in the final version. Clearly something needs to be done. Personally, I see a few potential avenues, though I'm not particularly keen on any of them yet:

* Don't precalculate the textures, but let the fragment shader calculate everything. Probably not feasible, because at one point I had the background as a fullscreen quad with a pixel shader and I got about 1 fps on my phone.
* Use the GPU to render the texture once, store it and use the stored texture from then on. Upside: might be faster than doing it on the CPU since the GPU is supposed to be faster at floating point calculations. Downside: effects that cannot (easily) be expressed as functions of simplex noise (e.g. gas planet vortices, moon craters, etc.) are a lot more difficult to code in GLSL than in Scala/Java.
* Calculate a large amount of noise textures and ship them with the application. I'd like to avoid this if at all possible.
* Lower the resolution. Buys me a 4x performance gain, which isn't really enough plus I lose a lot of quality.
* Find a faster noise algorithm. If anyone has one I'm all ears, but simplex is already supposed to be faster than perlin.
* Adopt a pixel art style, allowing for lower resolution textures and fewer noise octaves. While I originally envisioned the game in this style, I've come to prefer the realistic approach.
* I'm doing something wrong and the performance should already be one or two orders of magnitude better. If this is the case, please let me know.

If anyone has any suggestions, tips, workarounds, or other comments regarding this problem I'd love to hear them.

In response to Layoric, here's the code I'm using:

```
//The function that generates the simplex noise texture
public static Texture simplex(int size) {
    byte[] data = new byte[size * size * columns * 4];
    int offset = 0;
    for (int y = 0; y < size; y++) {
        for (int s = 0; s < columns; s++) {
            for (int x = 0; x < size; x++) {
                //Scale x and y to [-1,1] range
                double tx = ((double)x / (size - 1)) * 2 - 1;
                double ty = 1 - ((double)y / (size - 1)) * 2;

                //Determine point on cube in worldspace
                double cx = 0, cy = 0, cz = 0;
                if      (s == 0) { cx =   1; cy =  tx; cz =  ty; }
                else if (s == 1) { cx = -tx; cy =   1; cz =  ty; }
                else if (s == 2) { cx = - 1; cy = -tx; cz =  ty; }
                else if (s == 3) { cx =  tx; cy = - 1; cz =  ty; }
                else if (s == 4) { cx = -ty; cy =  tx; cz =   1; }
                else if (s == 5) { cx =  ty; cy =  tx; cz = - 1; }

                //Determine point on sphere in worldspace
                double sx = cx * Math.sqrt(1 - cy*cy/2 - cz*cz/2 + cy*cy*cz*cz/3);
                double sy = cy * Math.sqrt(1 - cz*cz/2 - cx*cx/2 + cz*cz*cx*cx/3);
                double sz = cz * Math.sqrt(1 - cx*cx/2 - cy*cy/2 + cx*cx*cy*cy/3);

                //Generate 6 octaves of noise
                float gray = (float)(SimplexNoise.fbm(6, sx, sy, sz, 8) / 2 + 0.5);

                //Set components of the current pixel
                data[offset    ] = (byte)(gray * 255);
                data[offset + 1] = (byte)(gray * 255);
                data[offset + 2] = (byte)(gray * 255);
                data[offset + 3] = (byte)(255);

                //Move to the next pixel
                offset += 4;
            }
        }
    }

    Pixmap pixmap = new Pixmap(columns * size, size, Pixmap.Format.RGBA8888);
    pixmap.getPixels().put(data).position(0);

    Texture texture = new Texture(pixmap, true);
    texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
    return texture;
}

//SimplexNoise.fbm
//The noise function is the same one found in http://webstaff.itn.liu.se/~stegu/simplexnoise/SimplexNoise.java
//the only modification being that I replaced the 32 in the last line with 16 in order to end up with
//noise in the range [-0.5, 0.5] instead of [-1,1]
public static double fbm(int octaves, double x, double y, double z, double frequency) {
    double value = 0;
    double f = frequency;
    double amp = 1;
    for (int i = 0; i < octaves; i++) {
        value += noise(x*f, y*f, z*f) * amp;
        f *= 2;
        amp /= 2;
    }
    return value;
}

```

# Answer
You could combine approaches (2) and (3) like this:

* First, use GPU to *generate* a number of noise textures and save them. This wll be your "noise cache"; you can only do it once on the first run.
* To generate a texture in-game, combine a few textures from cache - this should be real fast. Then, if needed, add special effects like vortices on top of that.
* Alternatively, you can pre-generate some "special-effects" textures too, and just blend them to get final result.
> 10 votes

# Answer
Procedural texture generation is a b\**** of a mofo in terms of compute time. It is what it is.

The best implementation of Simplex Noise I have found is Stefan Gustavson's.

Beyond improvement of *actual compute time* (it is actually pretty hard to get past the fact that you simply are asking *for a lot out of your computer* when you compute 1024x1024 procedural textures), one of the best ways to reduce *perceived* wait time is to have your app do as much background thread work as possible.

So start generating textures *at game launch on the background thread*, while the user is still fiddling with options and the menu or watching the level start trailer.

The other thing to consider is, just cache several hundred generated textures to disk and randomly select one of these at load time. More disk, but less load time.
> 2 votes

---
Tags: textures, performance, procedural-generation, perlin-noise
---


# Question
Title: How to tile multiple procedurally generated textures?
I'm trying to develop a procedural tile generator for a game, mostly for the ground tiles, instead of using "hand-drawn" tiles.

To achieve this I'm using Perlin noise and a sine wave with multiple parameters, which already gives me pretty nice results. I don't want to generate 1 tile and repeat that one forever for one ground type, but I want to avoid recurrences, so I'm generating n different tiles.

The problem I'm having now is that I want to tile the generated textures (smooth transitions).

At the moment I have this:

4 256x256 textures.

I thought a simple method would be to just add the positions of the different tiles to the noise generation algorithm, so that, when creating the 4 256x256 textures, it would behave like it would create a 512x512 texture, but that somehow didn't work as intented.

So how can I tile those textures?

# Answer
> 0 votes
There is a really good answer to another question about tileable Perlin noise here:

How do you generate tileable Perlin noise?

The basic idea is to get the gradient vectors at the gridpoints on the edges of each tile to 'match up' - so the gradient at the bottom left gridpoint should be the same as that at the top right, for example. N.B. To do this, you'll need to make sure that the edges of each tile are on gridlines.

If this doesn't make sense, check out the linked answer, which probably explains it better.

EDIT: I just noticed that you said that you'd already seen this answer. I know that you aren't trying to tile a single texture, but the same idea will work - you just need to make sure that the gradients on the edges of *all* the tiles in your set match up. More specifically, generate a single set of random gradient vectors for the tile edges, and use these for *all* textures. Then you can randomly generate the gradient vectors for gridpoints interior to the tiles separately for each of the n tiles.

I am not quite sure how you are using sine waves, but would imagine that you will want to make sure that the period of your sine functions matches up with the tile edges. So for example, if your tiles are 256x256, you could add sine functions like

```
sin(2 * PI * N * x / 256)

```

Where `x` is the pixel coordinate, and `N` is some natural number (i.e. 1,2,3,...). This function will match up at the edges of the grid, unlike for example `sin(x / 256)` which will be equal to zero on the left edge, and something close to 0.8 on the right.

You'll have to think carefully, and make up sine functions which always match at the edges of tiles. You could try to make sure that the functions are always zero at the edges of tiles, for example using functions of the form:

```
sin(2 * PI * N * x / 256) * sin(2 * PI * M * y / 256)

```

Where `N` and `M` are both natural numbers.

Wolfram alpha can be good for visualising functions like this (e.g. http://www.wolframalpha.com/input/?i=sin+x+sin+y)

I hope this helps!

# Answer
> 0 votes
if you make the texture from scratch, it's 3d, non repeating, tileable...

```
              //MARBLE BLUE formula code
              // float ht = sin((pos.y*.2+1*perlin(float3(pos.x, pos.y, pos.z),4))*3.1415);
              // ht = sqrt(ht+1)*.7071;
               //return float4(.3,.3 + .6*ht,.6 + .4*ht,1)*(2*i.color);

```

---
Tags: xna, c#, tiles, perlin-noise, procedural
---


title: XNA 2D line-of-sight check

text:
# Question
Title: XNA 2D line-of-sight check
I'm working on a top-down shooter in XNA, and I need to implement line-of-sight checking. I've come up with a solution that seems to work, but I get the nagging feeling that it won't be efficient enough to do every frame for multiple calls (the game already hiccups slightly at about 10 calls per frame).

The code is below, but my general plan was to create a series of rectangles with a width and height of zero to act as points along the sight line, and then check to see if any of these rectangles intersects a `ClutterObject` (an interface I defined for things like walls or other obstacles) after first screening for any that can't possibly be in the line of sight (i.e. behind the viewer) or are too far away (a concession I made for efficiency).

```
public static bool LOSCheck(Vector2 pos1, Vector2 pos2)
    {
        Vector2 currentPos = pos1;
        Vector2 perMove = (pos2 - pos1);
        perMove.Normalize();

        HashSet<ClutterObject> clutter = new HashSet<ClutterObject>();
        foreach (Room r in map.GetRooms())
        {
            if (r != null)
            {
                foreach (ClutterObject c in r.GetClutter())
                {
                    if (c != null
                        &&!(c.GetRectangle().X * perMove.X < 0)
                        && !(c.GetRectangle().Y * perMove.Y < 0))
                    {
                        Vector2 cVector = new Vector2(c.GetRectangle().X, c.GetRectangle().Y);
                        if ((cVector - pos1).Length() < 1500)
                            clutter.Add(c);
                    }
                }
            }
        }

        while (currentPos != pos2 && ((currentPos - pos1).Length() < 1500))
        {
            Rectangle position = new Rectangle((int)currentPos.X, (int)currentPos.Y, 0, 0);
            foreach (ClutterObject c in clutter)
            {
                if (position.Intersects(c.GetRectangle()))
                    return false;
            }
            currentPos += perMove;
        }
        return true;
    }

```

I'm sure that there's a better way to do this (or at least a way to make this method more efficient), but I'm not too used to XNA yet, so I figured it couldn't hurt to bring it here. At the very least, is there an efficient to determine which objects may be in front of the viewer with greater precision than the rather broad 90 degree window I've given myself?

# Answer
First, ahead of time, build a list of BoundingBox objects from your clutter. (If you're calling this 10 times a frame, there's no sense creating a list of them in the method itself. If removing objects that are definitely off-screen proves to be a useful optimization, then do that only once per frame and store the list of bounding boxes for repeated use.)

Second, build a Ray from your two positions. `pos1` will be origin of the ray; `pos2 - pos1` (normalized) will be the direction. You will also want to store the distance between the two points for later use.

Then, just loop over each object in your pre-built list of bounding boxes and call the Intersects method of your ray. You'll get back either `true` (if the line of sight is blocked by the box) or `false` (if it isn't). And because a ray is semi-infinite, it can actually return `true` if the box is past the end of the ray, so you need to check that the distance returned from the `Intersects` method is less than the distance between the two input points.

Note that both the `BoundingBox` and `Ray` types are 3D: just set the Z component to 0.

This method (ray tests against a list of blocking objects) is extremely standard and significantly quicker than marching along the line checking for intersections at each individual spot. As a bonus, if it's *still* too slow (which is unlikely), there are standard techniques for further optimization, all of which involve testing the ray against fewer boxes. But this should be plenty fast enough.
> 3 votes

# Answer
Calculating the line of sight between two objects, isn't so complicated to go through arrays and much more as you've illustrated. It just simply takes a few mathematical-provided functions to calculate radial-angle differences, so-long as you know the object positions and angles.

Works just by calculating the difference between radial-angles (converted to radians using no functions but a bit of mathematics) and vector distances.

```
public static bool InLOS(float AngleDistance, float PositionDistance, Vector2 PositionA, Vector2 PositionB, float AngleB)
{
    float AngleBetween = (float)Math.Atan2((PositionA.Y - PositionB.Y), (PositionA.X - PositionB.X));
    if ((AngleBetween <= (AngleB + (AngleDistance / 2f / 100f))) && (AngleBetween >= (AngleB - (AngleDistance / 2f / 100f))) && (Vector2.Distance(PositionA, PositionB) <= PositionDistance)) return true;
    else return false;
}

```

An example of its use:

```
if (InLOS(90, 500, Player.Position, Enemy.Position, Enemy.Angle)) //Do something

```

That example can translate into readable language like so: "If the player is within a 90 degree angle of the enemy and less than 500 pixels of difference between the player and the enemy, do something.."
> 0 votes

---
Tags: xna, xna-4.0, line-of-sight
---


title: Gesture Detector not firing

text:
# Question
Title: Gesture Detector not firing
So I'm trying to create a input class that implements a InputHandler & GestureListener in order to support both Android & Desktop. The problem is that not all the methods are being called properly.

Here is the input class definition & a couple of the methods:

```
public class InputHandler implements GestureListener, InputProcessor{
...
public InputHandler(OrthographicCamera camera, Map m, Player play, Vector2 maxPos) {
...
@Override
public boolean zoom(float originalDistance, float currentDistance) {
    //this.zoom = true;
    this.zoomRatio = originalDistance / currentDistance;
    cam.zoom = cam.zoom * zoomRatio;
    Gdx.app.log("GestureDetector", "Zoom - ratio: " + zoomRatio);
    return true;
}

@Override
public boolean touchDown(int x, int y, int pointerNum, int button) {
    booleanConditions[TOUCH_EVENT] = true;
    this.inputButton = button;
    this.inputFingerNum = pointerNum;
    this.lastTouchEventLoc.set(x,y);
    this.currentCursorPos.set(x,y);

    if(pointerNum == 1) {
        //this.fingerOne = true;
        this.fOnePosition.set(x, y);
    }
    else if(pointerNum == 2) {
        //this.fingerTwo = true;
        this.fTwoPosition.set(x,y);
    }

    Gdx.app.log("GestureDetector", "touch down at " + x + ", " + y + ", pointer: " + pointerNum);
    return true;
}

```

The touchDown event always occurs but I can never trigger Zoom (or pan among others...). The following is where I register and create the input handler in the "Game Screen".

```
public class GameScreen implements Screen {
...
   this.inputHandler = new InputHandler(this.cam, this.map, this.player, this.map.maxCamPos);
   Gdx.input.setInputProcessor(this.inputHandler);

```

Anyone have any ideas why zoom, pan, etc... are not triggering?

Thanks!

# Answer
After doing some investigation I switched the way I setup the project. I now have a controller class following a similar design as: http://www.badlogicgames.com/wordpress/?p=2668 where Mario describes his game architecture. Go to the controller section to see how he implemented his ControllerManager as mine is a near clone.

I use the controller in the following way:

```
public class GameScreen implements Screen {
...
    private ControllerManager controllerManager;
    ...
    public void show() {
        InputMultiplexer inputMulti = new InputMultiplexer();
        this.controllerManager = new ControllerManager(inputMulti);

        if(Gdx.app.getType() == ApplicationType.Desktop) {
            DeskController deskController = new DeskController(this.cam, this.map, this.player, this.map.maxCamPos);
            this.controllerManager.addController(deskController);
        }
        else {
            AndroidController androidController = new AndroidController(this.cam, this.map, this.player, this.map.maxCamPos);
            this.controllerManager.addController(androidController);
        }
        Gdx.input.setInputProcessor(controllerManager.getInputMultiplexer());

```

My deskController class is a standard inputProcessor, and androidController is a Gesture Detector.

Hope this helps someone else who is struggling with getting inputs from multiple devices.
> 1 votes

# Answer
I'm new in Java and libgdx world, so I'm not sure is this the best solution, but I had the same problem and I solved it a bit differently, and I would say simpler way. The thing is that you will never run your app on more than one device at the same time and that's why you'll never need multiple input types at the same time.

So, you still have to create two different classes. One should implement InputProcessor interface, for desktop devices, and other GestureListener for touch devices:

```
public class DesktopController implements InputProcessor{
    @Override
    public boolean keyDown(int keycode) {
        // TODO Auto-generated method stub
        return false;
    }

...

```

and other something like:

```
public class TouchController implements GestureListener{

    @Override
    public boolean touchDown(float x, float y, int pointer, int button) {
        // TODO Auto-generated method stub
        return false;
    }
...

```

But, you'll never use them both - just check on what device app is currently running and set appropriate input processor:

```
if(Gdx.app.getType() == ApplicationType.Desktop) {
    Gdx.input.setInputProcessor(new DesktopController(this));
}else{
    Gdx.input.setInputProcessor(new GestureDetector(new TouchController(this)));
}

```

This works well for me.
> 1 votes

---
Tags: libgdx
---


title: XNA calculate normals for linesegment

text:
# Question
Title: XNA calculate normals for linesegment
I am quite new to 3D graphical programming and thus far only understand that normal somehow define the direction in which a vertex faces and therefore the direction in which light is reflected. I have now idea how they are calculated though, only that they are defined by a Vector3.

For a visualizer that I am creating I am importing a bunch of coordinate which represent layer upon layer of line segments. At the moment I am only using a vertex buffer and adding the start and end point of each line and then rendering a linelist.

The thing is now that I need to calculate the normal for the vertices of these line segments so that I can get some realistic lighting. I have no idea how to calculate these normal but I know they all face sideways and not up or down. To calculate them all I have are the start and end positions of each line segment. The below image is a representation of what I think I need to do in the case of an example layer:

The red arrows represent the normal that should be calculates, the blue text represent the coordinates of the vertices and the green numbers represent their indices.

I would greatly appreciate it if someone could please explain to me how I should calculate these normal.

# Answer
> 2 votes
> The red arrows represent the normal that should be calculates.

2D is the only case that those red lines (or flipped) are the normals. for calculating a normal for 2D line segment (which is the title indicate), there are only two vectors perpendicular to any given vector, hence you can do the following:

```
 V = {x, y}
 Vperp = {-y,x}

```

\[Edit based on comments\] Your case is simply 2D in 3D space you only need to deal with Z as constant. (Which is actually the case of 2D where is always Z=0) I am assuming the layer are in plane Z = const value. This is also equivalent to rotating the vector by 90 degrees.

```
 V = {x, y, Z} // Z is const regardless of the value
 Vperp = {-y,x, Z}

```

In case Z was not const for each layer you only need to multiply the vector by a rotation matrix, but you need to figure out the axis that you should rotate around.

Otherwise for calculating a normal for 3D line segment, Well there are infinitely many perpendicular lines on a 3D line segments.

For calculating the normal for a face (which is I think is what the question wants) you can do the following:

Given a triangle with A,B,C, you need to take the cross product for any two non-parallel edges and then normalize it. This will give you a face normal. In order to calculate the normal for each vertex you need to average normal of each face that shares the vertex.

```
Vec3 a,b,c;
Vec3 faceNormal = (a-b) cross (c-a);
faceNormal = normalize(faceNormal);

for_each Face that share vertex:
    vertexNormal += FaceNormal;

vertexNormal = normalize(vertexNormal);

```

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


title: OpenGL ES 2.0. Sprite Sheet Animation

text:
# Question
Title: OpenGL ES 2.0. Sprite Sheet Animation
I've found a bunch of tutorials on how to make this work on Open GL 1 & 1.1 but I can't find it for 2.0.

I would work it out by loading the texture and use a matrix on the vertex shader to move through the sprite sheet.

I'm looking for the most efficient way to do it. I've read that when you do the thing I'm proposing you are constantly changing the VBO's and that that is not good.

**Edit:** Been doing some research myself. Came upon this two Updating Texture and referring to the one before PBO's. I can't use PBO's since i'm using ES version of OpenGL so I suppose the best way is to make FBO's but, what I still don't get, is if I should create a Sprite atlas/batch and make a FBO/loadtexture for each frame of if I should load every frame into the buffer and change just de texture directions.

# Answer
One way to do sprite animation with OpenGL ES shaders is achieved by using uniforms and changing texture coordinates in the vertex shader. To elaborate, suppose you have a 1024x128 sprite sheet with 8 frames.

1. Set up a quad whose vertices (clockwise) are `(-1, -1), (-1, 1), (1, 1), (1, -1)`.
2. Assign texture coordinates to the vertices with `(0, 0), (0, 1), (1, 1), (1, 0)`, respectively.
3. In the vertex shader, define a uniform `iSpriteFrame` which is set to the frame of the sprite animation you wish to draw (between zero and seven for this example).
4. When you draw the sprite at frame `n`, for each vertex with texture coordinate `tc` and position `p`, calculate the final texture coordinate `ftc` with

```
ftc.x = (iSpriteFrame + tc.x) * 0.125
ftc.y = tc.y

```
> 4 votes

---
Tags: textures, sprites, opengl-es2, spritesheet, spritebatch
---