# Question
Title: How to write an adjacency algorithm that compares position data?
I have a list of indexed triangles for which I need to generate adjacency data. I've already written a brute force algorithm that creates 3 edge data structures for each triangle and then compares the edge structures with those of other triangles like so:

```
public struct AdjEdge
        {
            public Vector3 _ref0;
            public Vector3 _ref1;
            public int _edge;
            public int _face;
            public bool _parsed;

            public AdjEdge(Vector3 ref0, Vector3 ref1, int edge, int face)
            {
                _ref0 = ref0;
                _ref1 = ref1;
                _edge = edge;
                _face = face;
                _parsed = false;
            }
        }

private static int[] GenerateAdjacency(Vector3[] positions,
            List<int> positionIndices)
        {
            int ncFaces = positionIndices.Count / 3;
            int ncVertices = positions.Length;

            // inst. adjacency array and set all values to -1
            int[] adjacency = Enumerable.Repeat(-1, 3 * ncFaces).ToArray();
            if (adjacency == null)
                throw new OutOfMemoryException("Failed to allocate memory for adjacency data");

            List<AdjEdge> edges = new List<AdjEdge>();

            for (int i = 0; i < positionIndices.Count; i+=3)
            {
                int iFace = i / 3;
                edges.Add(new AdjEdge(positions[positionIndices[i + 0]], positions[positionIndices[i + 1]], 0, iFace));
                edges.Add(new AdjEdge(positions[positionIndices[i + 1]], positions[positionIndices[i + 2]], 1, iFace));
                edges.Add(new AdjEdge(positions[positionIndices[i + 2]], positions[positionIndices[i + 0]], 2, iFace));
            }

            for (int i = 0; i < edges.Count - 1; ++i)
            {
                AdjEdge edgeA = edges[i];
                if (edgeA._parsed)
                    continue;

                for (int j = 3 - (i % 3) + i; j < edges.Count; ++j)
                {
                    AdjEdge edgeB = edges[j];
                    if (edgeB._parsed)
                        continue;
                    // CompareVectors() returns true if the vectors are separated by a distance less than 1e-6f
                    if (CompareVectors(edgeA._ref0, edgeB._ref1)
                        && CompareVectors(edgeA._ref1, edgeB._ref0))
                    {
                        adjacency[3 * edgeA._face + edgeA._edge] = edgeB._face;
                        adjacency[3 * edgeB._face + edgeB._edge] = edgeA._face;
                        edgeA._parsed = true;
                        edgeB._parsed = true;
                        break;
                    }
                }
            }

            return adjacency;
        }

```

Needless to say, time complexity is an issue here. What is the most efficient method for generating adjacency when comparing position data using an epsilon?

# Answer
> 2 votes
Disclaimer: this is not the academic approach to reduce complexity but it will work in this case.

1. Build a 3d uniform grid or an Octree (depending on data distribution) of Edge arrays around the scene.
2. Add each edge to the appropriate slot (based on the edge's center) in the grid / Octree.
3. If the edge's center is `epsilon` away from the inner border of the grid, compare that edge with neighboring edges that are on the other side of that inner border.

This should reduce computation time from O(n^2) to something that often completes in linear time.

This is a 2d representation but the idea is that you only need to compare edges that exist in the same slot in the Octree or grid. If I misunderstood and the edges don't need to be similar in length but only nearly parallel and a small distance away from one another than you need to use something akin to Bresenham's line algorithm and add the edges to multiple slots of the grid (in that case definitely use a grid and not an Octree).

# Answer
> 1 votes
Here is my implementation of Zehelvion's suggestion. An octree wasn't necessary but his suggestion helped to formulate the following method:

```
private static int[] GenerateAdjacency(Vector3[] positions,
        List<int> positionIndices)
    {
        // faces within mesh
        int ncFaces = positionIndices.Count / 3;

        // vertex count
        int ncVertices = positions.Length;

        // inst. adjacency array and set all values to -1
        int[] adjacency = Enumerable.Repeat(-1, 3 * ncFaces).ToArray();
        if (adjacency == null)
            throw new OutOfMemoryException("Failed to allocate memory for adjacency data");

        // the edge map will hold an edge center position as key and a list of edges that share the edge center position
        Dictionary<Vector3, List<AdjEdge>> edgeMap = new Dictionary<Vector3, List<AdjEdge>>();

        // edge center position
        Vector3 edgeVector = new Vector3();

        // iterate over list of position indices
        // there are 3 indices per face
        for (int i = 0; i < positionIndices.Count; i+=3)
        {
            // face index
            int iFace = i / 3;

            // compute edge center position
            edgeVector = Quantize((positions[positionIndices[i + 0]] + positions[positionIndices[i + 1]]) / 2);

            // if the edge center doesn't exist in the map then add a new entry
            if (!edgeMap.ContainsKey(edgeVector))
                edgeMap.Add(edgeVector, new List<AdjEdge>());

            // add the edge
            edgeMap[edgeVector].Add(
                new AdjEdge(positions[positionIndices[i + 0]], positions[positionIndices[i + 1]], edgeVector, 0, iFace));

            // compute edge center position
            edgeVector = Quantize((positions[positionIndices[i + 1]] + positions[positionIndices[i + 2]]) / 2);

            // if the edge center doesn't exist in the map then add a new entry
            if (!edgeMap.ContainsKey(edgeVector))
                edgeMap.Add(edgeVector, new List<AdjEdge>());

            // add the edge
            edgeMap[edgeVector].Add(
                new AdjEdge(positions[positionIndices[i + 1]], positions[positionIndices[i + 2]], edgeVector, 1, iFace));

            // compute edge center position
            edgeVector = Quantize((positions[positionIndices[i + 2]] + positions[positionIndices[i + 0]]) / 2);

            // if the edge center doesn't exist in the map then add a new entry
            if (!edgeMap.ContainsKey(edgeVector))
                edgeMap.Add(edgeVector, new List<AdjEdge>());

            // add the edge
            edgeMap[edgeVector].Add(
                new AdjEdge(positions[positionIndices[i + 2]], positions[positionIndices[i + 0]], edgeVector, 2, iFace));
        }

        // iterate over the edge map
        foreach (Vector3 key in edgeMap.Keys)
        {
            // list of edges sharing the same center position
            List<AdjEdge> edges = edgeMap[key];

            // iterate over source edges
            for (int i = 0; i < edges.Count - 1; ++i)
            {
                // source edge
                AdjEdge edgeA = edges[i];

                // do not parse edge twice
                if (edgeA._parsed)
                    continue;

                // iterate over comparison edges
                for (int j = i + 1; j < edges.Count; ++j)
                {
                    // comparison edge
                    AdjEdge edgeB = edges[j];

                    // do not parse edge twice
                    if (edgeB._parsed)
                        continue;

                    // compare the edges
                    if (CompareVectors(edgeA._ref0, edgeB._ref1)
                        && CompareVectors(edgeA._ref1, edgeB._ref0))
                    {
                        // the edges were similar so set adjacency for both edges
                        adjacency[3 * edgeA._face + edgeA._edge] = edgeB._face;
                        adjacency[3 * edgeB._face + edgeB._edge] = edgeA._face;

                        // set parsed state true
                        edgeA._parsed = true;
                        edgeB._parsed = true;

                        // break out of comparison loop
                        break;
                    }
                }
            }
        }
        return adjacency;
    }

```

---
Tags: c#, algorithm, vertex, mesh
---


title: Rotate an arrow on a plane?

text:
# Question
Title: Rotate an arrow on a plane?
I'm creating a display for a GPS-based embedded system and would like to have an arrow indicating the current bearing. I'd love the arrow to have a 3d appearance by rotating it on a plane tilted up toward the camera, as per these images.

My original idea was to have an ellipse that represents a circle on the tilted plane and plot the bearing angle as a point on the ellipse (this would be the 'head' of the arrow). The rest of the arrow would be drawn by offsetting the bearing by two fixed angles (say 160 and 200 degrees) to make the two points of the tail, then plotting those on the ellipse. The line connecting these two tail points would have its midpoint moved towards the head point to create the arrow shape.

As the target is a bitmap display and I would have to do the rendering myself, is there an algorithm for rotating a bitmap on an arbitrary plane given an angle of the plane and the angle of rotation? Or is there a better way to plot the arrow as a 3d shape, then translate to 2d?

# Answer
> 3 votes
1. Take an arrow image without any perspective

2. Rotate the image by the desired amount of degree

3. Scale the image vertically.

---
Tags: 2d, 3d, algorithm, vector
---


title: Loading textures as a method

text:
# Question
Title: Loading textures as a method
I want to load a texture when I need it, so I'd need a method in order to do so.

```
      LoadTexture(string fileName)

```

I'd only use that one parameter, but what would I put in the method? So far I've only ever loaded content at startup with something like

```
    content.Load<Texture2D>("blah");

```

But I want to move away from loading everything at startup and only load content when I need it.

EDIT: In order to explain what I'm going for, I'll give more detail. Say I have a chunk of blocks 50x50x50. Most of these won't be drawn, so it doesn't make sense to load the texture for the cubes not drawn. This is why I want a method that I can call whenever the texture needs to be loaded for the cube. Instead of loading 6 textures for 6 sides for 125,000 cubes, I cut back the amount of loading to only the visible cubes.

# Answer
> 1 votes
```
public Texture2D LoadTexture(string fileName)
{
    return Content.Load<Texture2D>(fileName);
}

```

That would be the method, but I don't see why you wouldn't just call Content.Load()?

# Answer
> 0 votes
XNA implicitly supports what you're doing via it's **GameComponent** classes. Taking advantage of these will solve your issue, but then you're shoehorned into using their design approach.

The `Game` class -- which your main object loop inherits from -- has a handy property called `Content`, which is a reference to a `ContentManager` instance. This is all set up for you by default. Now what's cool is when you create an instance of a `GameComponent`, it asks for a `Game` object.

```
public class SomeCustomClass : GameComponent
{
    public SomeCustomClass(Game game)
        : base(game)
    {
    }
}

```

The above code shows the minimum implementation for a `GameComponent`. But because you pass an instance of your game loop, it can now see *every public property in your Game, including Content*, which is accessed via `base.Game`

So from there, you'd implement a method to load/unload content as needed, using `base.Game.Content.Load<Texture2D>("someResource");` or something similar.

See also: http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game\_members.aspx

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


# Question
Title: Why does GameComponent have an Initialize() method?
I'm not sure if this exact question has been asked before, but all I could find were questions about how to work with GameComponent, or why something wasn't working.

I understand that you overload the Initialize, Draw, and Update methods with your own code, and XNA will then invoke them when the time is right. But what exactly is the purpose of Initialize? If you're writing something that extends from GameComponent, why wouldn't you just put all your initialize logic in the constructor?

For example, if my classes have a reference type that needs to be initialized, such as a collection or dictionary, I make of point of doing so in the constructor, and this pattern follows me into my GameComponent class design.

---

**EDIT**: Having worked with it a bit more, it looks like the primary purpose is to allow for more flexibility.

For example, `IGameComponent` merely exposes one method -- `Initialize()` -- and by implementing this, you are allowed to plug it into the `Game.Components` collection. This means that `GameComponent`, with all of its various properties, even the reference to `Game`, is just an implementation detail.

Another use I've found is when one component contains a collection of other components. In this case, the constructor for the container is called, and you now have empty collections. This pattern allows you to populate the collections, then call the initialize on both the parent and children objects.

I'm still stumped as to what I would specifically put into Initialize, but I understand the reasoning behind it.

# Answer
> 5 votes
The reason you wouldn't put the initialize logic in the constructor is because `Initialize` is the first point where you can be sure that `GraphicsDevice` is set up.

Recall that, while your constructor for your `Game`-derived class may create `GraphicsDeviceManager`, the graphics device itself is only created when `Game.Run()` is called (an instance method, so it requires an instance, which requires calling the constructor).

---

A more interesting question would be: Why is there `Initialize` *and* `LoadContent`? Why not just `LoadContent`?

Partly this goes back to XNA 1.0 (there's a certain degree of backwards-compatibility in the API). Back then, there was no `LoadContent` method, but instead there was a `LoadGraphicsContent` method. That method would get called whenever the graphics device was reset, in order to reload all of your GPU resources - such as textures (you were expected to handle this correctly).

(Aside: A device reset can happen if the user minimises the window, locks their workstation, etc.)

From XNA 2.0 onwards, XNA will automatically reload textures (and other GPU resources) for you - and the method was renamed `LoadContent`. Although, in the very rare case where the automatic-reload fails, XNA will *still* call `LoadContent` to attempt to recreate the resources from scratch.

(Most people don't bother writing `LoadContent` carefully enough to handle this situation correctly.)

In either case, having an `Initialize` method gives you a separate code-path that is only called once at startup, when the graphics device is available, but is not part of the reset-handling.

The methods in (`Drawable`)`GameComponent` are the way they are largely to mirror what is in `Game`, but the same reasoning as above applies.

---

You might also find this answer interesting.

---
Tags: xna, c#, game-component
---


# Question
Title: Collision detection between 2 irregular shapes
I need to implement a collision system for a vertical-shotter and the bullets can have any type of shape; i've implemented the shape class with an array of choords and an array of lines which have the references of start and end points; in case the line is bezier it have an array of anchor points.

so:

```
Line { Choord Start,End; Choord [] Anchors = null; ... }
Choord { float X, Y; ... }
Shape { Choord [] Vertexs; Line [] Lines; ... }

```

i have to handle a collision like this:

anyone have a general idea for check collision with this type of shapes? and this model can work?

i've tryed with SAT collisions but it works only for convex polygons.

# Answer
In general you can check if any Intersection exist between your two polygon (even non-convex) as below.

**Problem:** Given **n** line segments; Report all(as **k** in algorithms) Intersections.

You can implement any of these two algorithm in your desire language and use them. they take your line segments as input and return if any intersection ( Collision in your case) exists.

Note: **Time/Space complexity of these algorithms for collision detection break with k=1**. because as you see first intersection, you can stop algorithm and report collision.

---

**Solution 1:** Sweep Algorithm (Bentley, Ottmann '79)

**Time Complexity: O(n\*lg(n)+k)**

**Space Complexity: O(n+k)**

**Pseudo Code:**

```
ReportIntersections()
{

    Initialize event queue EQ = all segment endpoints;
    Sort EQ by increasing x and y;
    Initialize sweep line SL to be empty;
    Initialize output intersection list IL to be empty;

    While (EQ is nonempty) {
        Let E = the next event from EQ;
        If (E is a left endpoint) {
            Let segE = E's segment;
            Add segE to SL;
            Let segA = the segment Above segE in SL;
            Let segB = the segment Below segE in SL;
            If (I = Intersect( segE with segA) exists)
                Insert I into EQ;
            If (I = Intersect( segE with segB) exists)
                Insert I into EQ;
        }
        Else If (E is a right endpoint) {
            Let segE = E's segment;
            Let segA = the segment Above segE in SL;
            Let segB = the segment Below segE in SL;
            Delete segE from SL;
            If (I = Intersect( segA with segB) exists)
                If (I is not in EQ already)
                    Insert I into EQ;
        }
        Else {  // E is an intersection event
            Add E’s intersect point to the output list IL;
            Let segE1 above segE2 be E's intersecting segments in SL;
            Swap their positions so that segE2 is now above segE1;
            Let segA = the segment above segE2 in SL;
            Let segB = the segment below segE1 in SL;
            If (I = Intersect(segE2 with segA) exists)
                If (I is not in EQ already)
                    Insert I into EQ;
            If (I = Intersect(segE1 with segB) exists)
                If (I is not in EQ already)
                    Insert I into EQ;
        }
        remove E from EQ;
    }
    return IL;
}

```

---

**Solution 2:** Divide & Conquer Algorithm (Balaban '95)

**Complexity: O(n\*lg(n)+k)**

**Space Complexity: O(n)**
> 2 votes

---
Tags: collision-detection
---


# Question
Title: Filling up the empty blocks when the player touches the safe zone again! using cocos2d
Hi guys i am stuck with filling up the data of all the blocks which are empty like the ones in the image. As you can see there i have a pacman like object where i will be moving around.

But when you are in the empty space where there are no Blue boxes available i should be able to add new blocks in the path of my pacman and when it touches any other blue boxes like in the below case if my pacman touches the top row of the blue box i should be able to fill all the empty boxed inside the border of the path created by pacman.

For now i am using a 2d bool array to store all the filled boxed info like if there is a box inside i am making that cell in an array as true.

But how to fill the area with blue boxes after player finishes his path ?

Any help would be great thank you.

More info about this problem is here: filling the empty spaces in a certain region in a grid using c++ Same problem

# Answer
> 0 votes
The easiest way would be to use the flood fill algorithm. In your specific case you will probably want to fire off two different flood fills, one to the right of Pacman and one to the left. Whichever one is suitable to fill (the smaller one, the one with no obstacles detected, etc.) is filled and the other is discarded.

# Answer
> 0 votes
You just need a simple DFS algorithm !

**Here you go:**

1. Run DFS every time player go on a empty block.
2. Your DFS should navigate empty block until reach a filled (blue) block. this is stop
3. condition of your DFS.
4. Then in DFS, check if all DFS-branches stuck to a filled block. not your game-world border.
5. if yes, Run That DFS again, and fill all blocks which DFS navigate on. otherwise Nothing to do.

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


# Question
Title: How can I access a script variable from another script in Unity?
I'm creating a space shooter (think Space Invaders or Galaga) where the GameManager persists between scenes but the player and enemies don't. I need to access a boolean value from the player and enemies to define when and how the game should end. The `PlayerController` script contains a `playerDead` variable (attached to the `Player` `GameObject`) to tell the `GameManager` if the player has died and a `enemiesDead` variable to tell if all enemies have died.

Because the `GameManager` persists but the others don't, it loses the references when a new level is loaded. I tried to have the `GameManager` find the script references dynamically, to no avail. It always errors with `Object reference not set to an instance of an object` when a new level is loaded.

I've tried to get them with `GameObject.FindGameObjectWithTag()` and then using `GetComponent<ScriptName>()` to get the script and the variable in it. It compiles nicely and everything seems dandy, but then there's still no object reference. Am I just doing it wrong?

So how can I reference a script and get a value from it without even touching the Inspector?

EDIT:

Below is some code (everything else except the essential is scrapped) from the `GameManager` script, I tried to use `Object.FindObjectsOfType()` like this:

```
GameObject player;
GameObject enemies;

void Awake()
    {
        DontDestroyOnLoad (gameObject);
    }

void Start ()
    {
        Reinitialize ();
    }

void Update ()
    {
        if (enemies.GetComponent<EnemyGrid>().enemiesDead == true)
        {
            gameEnd = true;
        }

        if (player.GetComponent<PlayerController>().playerDead == true)
        {
            gameEnd = true;
        }
    }

void Reinitialize()
    {
        player = Object.FindObjectOfType(typeof(PlayerController)) as GameObject;
        enemies = Object.FindObjectOfType (typeof(EnemyGrid)) as GameObject;
    }

```

But there's still no object reference. My intention was to run the `Reinitialize()` funtion each time a new scene was loaded, so that way the `GameManager` would grab the new objects each time.

# Answer
Getting null reference exception is normal since they were created in the previous scene and destroyed in the current one. To move them to the next scene, you need to call DontDestroyOnLoad.

Why don't you create your assets after the scene is loaded? GameManager should be responsible for creating player and enemy objects and keep track of the game state. In addition, try to use c# **event**s to communicate with the manager in order to notify events such as EnemyDestroyed or PlayerDied etc. In this way, you don't need to ask both player and enemies whether they are dead at each frame.
> 1 votes

---
Tags: unity, 2d, architecture, software-engineering, gameobject
---


# Question
Title: How do I load a model through AssimpNet into Monogame?
I am new to MonoGame and to 3d and I'm stuck on how to import a model. It seems the best way to import a mesh model and 3d animations in Monogame in Windows 8 is through AssimpNet. I can't find a basic-level tutorial on this.

I am looking for code to import in a format Blender supports (DAE, OBJ, 3DS), view the imported mesh and perform something basic like a camera rotation around it.

Is there a way to load data imported through AssimpNet into the Model object in Monogame?

# Answer
> 2 votes
So I took a look through the MonoGame content pipeline code to see how it works and turns out its using AssImpNET. So importing your models via the MonoGame pipeline is a solution to your question.

Just from reading the AssImp documentation it looks like this code could handle formats other than ".fbx", ".x" dictated by the annotation. Issues would arise if different file structures would alter how the \_scene is laid out which would require you to transform the scene so that it lines up with what MonoGame requires.

```
    [ContentImporter(".fbx", ".x", DisplayName = "Open Asset Import Library - MonoGame", DefaultProcessor = "ModelProcessor")]

```

**MonoGame:OpenAssetImporter.cs**

```
    public override NodeContent Import(string filename, ContentImporterContext context)
    {
        var identity = new ContentIdentity(filename, string.IsNullOrEmpty(ImporterName) ? GetType().Name : ImporterName);

        using (var importer = new AssimpContext())
        {
            _scene = importer.ImportFile(filename,
                //PostProcessSteps.FindInstances | // No effect + slow?
                PostProcessSteps.FindInvalidData |
                PostProcessSteps.FlipUVs |
                PostProcessSteps.FlipWindingOrder |
                //PostProcessSteps.MakeLeftHanded | // Appears to just mess things up
                PostProcessSteps.JoinIdenticalVertices |
                PostProcessSteps.ImproveCacheLocality |
                PostProcessSteps.OptimizeMeshes |
                //PostProcessSteps.OptimizeGraph | // Will eliminate helper nodes
                PostProcessSteps.RemoveRedundantMaterials |
                PostProcessSteps.Triangulate
                );

            _globalInverseXform = _scene.RootNode.Transform;
            _globalInverseXform.Inverse();

            _rootNode = new NodeContent
            {
                Name = _scene.RootNode.Name,
                Identity = identity,
                Transform = ToXna(_scene.RootNode.Transform)
            };

            _materials = ImportMaterials(identity, _scene);

            FindMeshes(_scene.RootNode, _scene.RootNode.Transform);

            if (_scene.HasAnimations)
            {
                var skeleton = CreateSkeleton();
                CreateAnimation(skeleton);
            }

            // If we have a simple hierarchy with no bones and just the one
            // mesh, we can flatten it out so the mesh is the root node.
            if (_rootNode.Children.Count == 1 && _rootNode.Children[0] is MeshContent)
            {
                var absXform = _rootNode.Children[0].AbsoluteTransform;
                _rootNode = _rootNode.Children[0];
                _rootNode.Identity = identity;
                _rootNode.Transform = absXform;
            }

            _scene.Clear();
        }

        return _rootNode;
    }

```

---
Tags: models, monogame, assimp
---


# Question
Title: What is the relationship between glVertexAttribPointer index and GLSL location?
I've been getting some strange results when trying to implement a normals buffer for the purpose of rendering lighting. It seems to be related to the indexes for glEnableVertexAttribArray, glVertexAttribPointer and the location value in the vertex shader. Take a look at the following code for example:

```
  gl.glEnableVertexAttribArray(1);
  gl.glEnableVertexAttribArray(0);

  //bind vertex data - why does the index have to be 1?
  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[VERTICES_IDX]); //the vertex data
  gl.glVertexAttribPointer(1,3,GL4.GL_FLOAT, false,  0,0);

  // Select the VBO, GPU memory data, to use for colors
  // - why doe the index have to be 0??
  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[COLOR_IDX]);
  gl.glVertexAttribPointer(0, 3, GL4.GL_FLOAT, false, 0, 0);

  //bind IBO
  gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, vboHandles[2]);

```

Where do the values for the indexes used in the above functions come from? If I were to switch them and make the color buffer 1 and the vertex buffer 0, nothing renders. It seems logical to me that the vertices should be applied first and then the colors? My confusion is compounded when I try to pass the data to a shader. I thought the location value in the shader program referred to the index in glVertexAttribPointer but that doesn't seem to be the case. In fact it looks like location is being completely ignored (targeting GLSL 430). Have a look at this:

**From the shader:**

```
layout (location=0) in vec3 vertexPosition;
layout (location=1) in vec3 vertexNormal;

```

**The Java code:**

```
//with glEnableVertexAttribArray 0 and 1 enabled all of the cubes render but they
//are individually lighted - ie the shading doesn't propagate over the whole scene,
//only over each cube.
//if i rem 1, the scene looks lighted properly.  So only 1 vertex array enabled
//and it still works?
  gl.glEnableVertexAttribArray(0);
  gl.glEnableVertexAttribArray(1);
  //gl.glEnableVertexAttribArray(2);

  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[VERTICES_IDX]);
  //with the index set to 5 (doesn't relate to any other index) the scene still
  //renders...
  gl.glVertexAttribPointer(5,3,GL4.GL_FLOAT, false,  0,0);

  //normals
  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[3]);
  gl.glVertexAttribPointer(1, 3, GL4.GL_FLOAT, false, 0, 0);

      // Select the VBO, GPU memory data, to use for colors
  //almost strangest of all.  If I remove colors the program crashes.  I don't
  //even use this buffer..
  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[COLOR_IDX]);
  gl.glVertexAttribPointer(0, 3, GL4.GL_FLOAT, false, 0, 0);

  //bind IBO
  gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, vboHandles[2]);

```

There is obviously something fundamental here that I am not understanding. I would think that by setting the glVertexAttribPointer index for the vertices to 5 it would unlink from the shader **in** variable as its location is 0. I need to know what is going on here especially now that I am implementing lighting. So, what is the relationship between the glVertexAttribPointer index and the shader location value? Also, why does the index have to be certain value (eg 0 for color, 1 for vertex)?

# Answer
> 2 votes
You can explicitly get those numbers from `id = glGetAttribLocation(program, name);` after linking; the name is the string that appears in the vertex shader for the attribute. For example if you passed "vertexPosition" for name then you would get `0`.

If the layout information is not in the shader then openGL will create a default layout (usually in order as they appear) or you can define your own binding with `glBindAttribLocation(progam, id, name)` before linking.

---
Tags: opengl, java, glsl
---


title: Alternative to Update()

text:
# Question
Title: Alternative to Update()
Here is my noobish scenario I'm trying to understand:

Some class, Terrain:

```
       void Start()
        {
...
            switch (Type)
            {
                case TerrainType.StartPoint:
                    renderer.material.color = Color.blue;
                    break;
                case TerrainType.EndPoint:
                    renderer.material.color = Color.red;
                    break;
                case TerrainType.Wall:
                    renderer.material.color = Color.black;
                    break;
                default:
                    renderer.material.color = Color.green;
                    break;
            }
...
        }

```

some other class, SomeOtherClass: ('target' is Terrain object)

```
void Awake()
{
...
temp = (Terrain) Instantiate(target, new Vector3(0,0,0), Quaternion.identity);
...
}

```

At this point everything is ok.

If, down the road, i try assigning different type to one of the existing Terrain objects, the type will change sure, but the color will not since color change switch is in `Start()`

If i put the color updating code in `Update()` function sure it works and the color is changed but is this the right way of doing something like this?

I feel like it is an overkill since Update is called every frame and i might have only one or two calls to change the type throughout the whole game life time.

# Answer
> 1 votes
Trigger an event, or just call the change method when you change the type of terrain object. Pull you color switching code out of start and put it in its own method. Then, have start call the `SetColor` method, and have your code that switches terrain types also call `SetColor` whenever the type changes.

It's not something that needs to be done every frame, you're correct there. It's something that needs to happen when something else happens. So, you just call the code when that other event happens (in this case changing the terrain type).

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


# Question
Title: Unrealistic sphere behavior on inclined plane
I am trying to model a ball rolling down an inclined surface in Unity based on what I am observing in real life but it is still quite off.

1. In Unity it takes the ball about 3 seconds to travel from a place to another specified place where in real life it only takes 1 second.
2. The ball isn't as fast to react to the incline as in real life (even though I have tried giving the ball and surface low or zero friction values).
3. The ball does not accelerate nearly as fast as it does in real life.

What do I do to give the ball more realistic behavior ? I have tried messing around with mass, physics materials, drag, and angular drag on the ball and surface but it doesn't seem to help.

# Answer
> 3 votes
I would check your scale. Physics in Unity are designed to work at real life scales (1 unit = 1 meter) If you create a scene that is not to the correct scale, you are going to have a terrible time getting it to look correct.

**Example:**

Lets assume your ball is supposed to be a basketball. A standard basketball is 23cm (0.23m) If you build everything to scale and have normal gravity it should accelerate at 9.8m/s^2. In game space that would be 9.8 units/second squared.

If you just made the ball the size of a unit sphere and scaled the environment up. It would look visually like everything was correct but, you have done is created a giant (~5x) basketball in a giant world. When you hit play the ball would appear to be affected by gravity at a different rate, 2.254 Units/second squared.

The temptation in this moment would be to try to adjust gravity and the relative masses to compensate for the scale being off. The problem is that PhysX is actually only built to work well at one scale, the real world (1 unit = 1 meter). If you deviate from that standard scale you are going to an increasingly difficult time getting anything behaving correctly.

# Answer
> 1 votes
Try adjusting the **Max Angular Velocity** in the Physics Manager.

You can access the Physics Manager by selecting Edit-\>Project Settings-\>Physics from the menu bar.

The default value is **7**.
Maybe try a value around **100**. That seemed to work well for me.

You can override the Project Settings value of Max Angular Velocity for any Rigidbody by scripting Rigidbody.maxAngularVelocity.

I hope this works the way you are expecting! It did for me, but I didn't test the side effects of having set a high value. If anyone here can explain why adjusting the Max Angular Velocity may be a poor decision, please let us know.

# Answer
> 0 votes
Anko was right with his comment.

`Physics.gravity` is a static vector 3 variable that you can change in your code.

http://docs.unity3d.com/ScriptReference/Physics-gravity.html

You can modify gravity along with things like friction and drag to give desirable results.

---
Tags: c#, unity, physics
---


title: Infinite loop of prerendered 3d graphic

text:
# Question
Title: Infinite loop of prerendered 3d graphic
I have a game where I want a never ending pathway for the character to walk along. So in my 3d modeling tool I created a path like this:

now I want to loop that model over and over in my prerendered 2d game for the character to walk on (most of the other game elements are in 2d). The problem is that simply overlaying one image on top of another results in the tiles facing opposite directions. Here's another picture I slapped together so you'll get the idea. In the final game the outer border of the pathway won't separate the two paths.

as you can see, the tile pattern looks unnatural, like one pathway segment is a mirror of the other. How can I change the lens/render the model differently so that it can become a seamlessly looping 2d texture?? Can it be done using only the camera view, without a "quadrilateral reshape" or falsely stretching the back end of the platform in my 3d modeler?

# Answer
There are a multitude of 3D projections out there with different properties and any 3D modelling tool worth its salt ought to be able to configure the cameras to achieve those looks.

A perspective projection like the one you have used have diminishing widths and heights as you go further away, which will result in the trapezoid shape that you illustrate.

You may be better served by a projection with different properties. An oblique projection (by 3D game developers often called orthographic) does not have the foreshortening you demonstrate and will as such end up with more tileable edges. The look where lines remain parallel may not be one that fits your intended artstyle, of course.
> 3 votes

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


# Question
Title: Libgdx - IsometricTiledMapRenderer and light shading
I am wondering if there is any way to simulate light shading in Libgdx using an IsometricTiledMapRenderer.

Here is my code to draw an isometric map, it's able to be moved around with the mouse and you can zoom in and out with the mouse scroll wheel.

```
package com.iso.game.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Buttons;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.IsometricTiledMapRenderer;
import com.iso.game.Main;

public class GameScreen extends AbstractScreen
{
    private TiledMap map;
    private IsometricTiledMapRenderer renderer;
    private OrthographicCamera camera;

    public GameScreen(Main game)
    {
        super(game);
    }

    public void load()
    {
        map = new TmxMapLoader().load("map.tmx");
        renderer = new IsometricTiledMapRenderer(map);

        renderer.getSpriteBatch().setShader(null);

        camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        camera.position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0);
    }

    public void render(float delta)
    {
        Gdx.gl.glClearColor(0f, 0f, 0f, 1f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        camera.update();

        renderer.setView(camera);
        renderer.render();
    }

    public boolean scrolled(int amount)
    {
        camera.zoom += 0.1 * amount;
        // Don't go below the map
        if (camera.zoom < 0.01)
            camera.zoom = (float) 0.01;
        return false;
    }

    public boolean pan(float x, float y, float deltaX, float deltaY)
    {
        camera.position.add(camera.zoom * -deltaX, camera.zoom * deltaY, 0);
        return false;
    }

    public boolean touchDown(int screenX, int screenY, int pointer, int button)
    {
        if (button == Buttons.MIDDLE)
            camera.zoom = 1;
        return false;
    }

    public void resize(int width, int height)
    {
        camera.viewportWidth = width;
        camera.viewportHeight = height;
    }

    public void dispose()
    {
        map.dispose();
        renderer.dispose();
    }
}

```

And here is an image of what this code looks like (Note, this class is not the entirety of my code. If you need to rest for some reason please let me know).

Can anyone give me an example on how to simulate lighting with this map? Such as a point light that spreads out and looks isometric, perhaps choosing some tiles as objects that block or distort light. I have no idea how to get started and I couldn't really find anything useful online.

Thank you for your help in advance.

# Answer
I, you may have a look at Box2d light box2D light. The idea is to create shape in a box2D world and then use Box2D light to perform the shadow casting and light rendering.

You then have to render the light on top of your scene.
> 1 votes

---
Tags: java, libgdx, lighting, isometric
---


# Question
Title: what is the name for the category of game that use a real time clock as the game time like die2nite.com
I was looking for more game like http://www.die2nite.com and http://mush.twinoid.com/ They use real time as the fictional time. Player are given a number of action point they can use freely during a 24 hour cycle.

It was quite common to see these kind of games 10 years ago and would really like to explore some more. Any idea what the category is called and where could I find more game like this. Any more example of such games would be great,

Thanks

# Answer
Any game that involves elements taken directly from present realty in real-time or things in that vein are often called "Alternate reality" games. Normally they involve getting game content through unorthodox channels like social network sites.

For instance, if the game is about an investigation, you might get a lead sent in facebook chat or as an annonymous email to your gmail account.

They are sometimes reffered to as "ARG" for short (Alternate Reality Game) and the common denominator is that they "bleed" in to the real world in some way.
> 1 votes

---
Tags: terminology
---


# Question
Title: Calculating gameObjects hit by a directional light source
I am trying to figure out in my current game whether a gameObject is lit by a directional light or not. Below is my image inside the Unity game engine

As my game runs around a Day/Night cycle, I need to constantly check which hex tiles are lit and which are not. I am using one directional light source in my scene and I am rotating it around the x-axis for the day night cycle.

Currently, I am using the dot product to calculate if the tile is lit by the directional light but its not very accurate.

```
 Vector3 forward = Light.transform.TransformDirection(Vector3.forward);
 float dot = Vector3.Dot(forward, -(tile.transform.position - Light.transform.position));

```

Is there a better way to do check this inside Unity??

# Answer
If you have the normal vector for the "top" face of the hex and the vector for the directional light it should be easy to determine if that hex is facing the light.

Note that this will check if the hex and the light are facing each other. This will not detect of another object is in between casting a shadow over the hex.

```
Vector3 lightDirection = directonLight.transform.forward;

Vector3 hexNormal = hex.transform.up;

//assumes normalized vectors
if (Vector3.Dot(lightDirection, hexNormal ) < 0) {
    //These vectors form an angle >90 and <270 degrees.
    //This means that the light is shining on this face
}
else {
    //these vectors form an angle either <=90 or >=270 degrees.
    //This means that the light is not shining on this face.
}

```

If for some reason you are unable to determine the hex's orientation using one of the transform's axes, you could calculate it by comparing the hex's position with the center of the planet.

```
Vector3 hexNormal = (hex.transform.position - planetCenter.transform.position).normalized;

```
> 2 votes

# Answer
Interesting case. One way I can think of solving this would be to have an up normal on each hex tile. You would dot each hex's normal with the light source direction vector, and if the angle between them is more than 90 degrees you ignore all light calculations for the whole hex tile.
> 1 votes

---
Tags: unity, mathematics
---


title: Game Center Leaderboard not dismissing

text:
# Question
Title: Game Center Leaderboard not dismissing
I was implementing Game Center into my app and all was going well except for the leaderboard done button not dismissing the leaderboard even with gameCenterControllerDidFinish added in. I call up the leaderboard with the touch of a button in the .m file as so:

```
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
 UITouch *touch = [touches anyObject];
 CGPoint location = [touch locationInNode:self];
 SKNode *node = [self nodeAtPoint:location];

 if ([node.name isEqualToString:@"rankButton"]) {

    [self runAction:[SKAction playSoundFileNamed:@"fishtran.m4a" waitForCompletion: NO]];
     GKGameCenterViewController *gameCenterController = [[GKGameCenterViewController alloc]
  init];
        if (gameCenterController != nil)
   {

        gameCenterController.viewState = GKGameCenterViewControllerStateAchievements;
        UIViewController *vc = self.view.window.rootViewController;
        [vc presentViewController: gameCenterController animated: YES completion:nil];
    }
} else if ([node.name isEqualToString:@"Leaderboard"]) {
    GKGameCenterViewController *gameCenterController = [[GKGameCenterViewController alloc]
  init];
    if (gameCenterController != nil)
    {

        gameCenterController.viewState = GKGameCenterViewControllerStateLeaderboards;
        UIViewController *vc = self.view.window.rootViewController;
        [vc presentViewController: gameCenterController animated: YES completion:nil];
    }
}

```

... and then I added thegameCenterControllerDidFinish immediately after as so:

```
- (void)gameCenterControllerDidFinish:(GKGameCenterViewController*)gameCenterController {

    UIViewController *vc = self.view.window.rootViewController;
    [vc dismissViewControllerAnimated:YES completion:nil];
}

```

and the done button still doesn't work and i haven't been able to find any solutions. And yes, I do have GKGameCenterControllerDelegate in my .h file. Any help would be greatly appreciated, Thanks!

# Answer
just use `gameCenterController` for dismissing.

```
[gameCenterController dismissViewControllerAnimated:YES completion:nil];

```
> 1 votes

---
Tags: ios, game-center, xcode, spritekit
---


# Question
Title: Who owns content which creation was outsourced?
What license or contract type is normally used by independent developers, when outsourcing game resources like graphics or sounds? Is there something like a template floating around? How much ownership of the work can I demand?

I'm alone, so the contract is only between me and another person who's doing graphics, sounds or so on.

# Answer
> 4 votes
Usually, the person paying the bills is the one that gets the rights for the job.

If you are paying him for making the graphics, then usually you should have all the rights. He just gets money for his time.

Conversely, if he's paying *you* for your programming, then he should get all the rights: code and art.

If you are both investing - either with an initial inversion or by not getting paid until the game is released - then you both should share all the rights. A usual move would be creating a society, and giving the rights to the society. But it really depends on your local legislation.

# Answer
> 1 votes
Usually contracts like that are work for hire. The person doing the work has no rights to what they create for you since it's yours.

# Answer
> 1 votes
This really depends on the contract.

If the contract say that the buyer just gets a licence to use the work, then the rights usually stays with the creator who then can do whatever with the product. This is not unheard of in the games industry when producing non-hero assets, like city buildings and grass textures and such often needed "extra assets".

# Answer
> 0 votes
This depends on the wording of the contract agreement and the governing countries laws (some states you cannot sign away your rights). Best to consult a legal counselor when drafting contracts so as to iron out the details and not have any issues for later IMHO.

---
Tags: licensing, outsourcing
---


# Question
Title: Per vertex diffuse lighting not propogating across entire model
I'm not sure how to describe this problem so I've added a picture. When I add per vertex diffuse lighting to my model (just a field of cubes for simplicity) the lighting effect applies to each surface individually instead of having the lighting gradually intensify or drop off across the entire plane.

As you can see, each plane has it's own version of the shading effect. I was expecting the collection of planes to be treated as a single surface with a uniform shading effect spread across it. What would cause this? Is it a common lighting mistake? I have hardcoded the vertex normals for now as:

```
float[] normals = {0,0,1, //front
      -1,0,0,//left
      0,0,-1,//back
      1,0,0,//right
      0,1,0,//top
      0,-1,0//bottom
};

int[] idxBuffer = {0,1,2,2,3,0, //front
      4,0,3,3,4,5, //left
      4,6,7,7,5,4, //back
      1,6,7,7,2,1, //right
      3,2,7,7,5,3, //top
      0,1,6,6,4,0 //bottom
      };

float[] vertBuffer = {-1,-1,1,//0
      1,-1, 1,//1
      1,1,1,//2
      -1,1,1,//3
      -1,-1,-1,//4
      -1,1,-1,//5
      1,-1,-1,//6
      1,1,-1//7
};

//after initializing/linking shader...
  /****
   * Diffuse
   */
  //get indexes from shader variables...
  iModelView = shader.getUniform("ModelviewMatrix");
  iNorm = shader.getUniform("NormalMatrix");
  iMVP = shader.getUniform("MVP");
  iLightPos = shader.getUniform("LightPosition");
  iKd = shader.getUniform("Kd");
  iLd = shader.getUniform("Ld");

  //set the constant values in shader.
  float[] kd = {0.8f, 0.45f, 0.3f};
  shader.setUniform(iKd, kd, Shade.MatDataType.VEC3);
  float[] ld = {1.0f, 1.0f, 1.0f};
  shader.setUniform(iLd, ld, Shade.MatDataType.VEC3);

  /**
   * Prepare the normals.
   *This is my original attempt at creating per vertex normals.
   */
  for(int i = 0; i < idxBuffer.length; i+=3)
  {
     Vector3 v0 = new Vector3( vertBuffer[(idxBuffer[i]*3)],vertBuffer[(idxBuffer[i]*3)+1],vertBuffer[(idxBuffer[i]*3)+2]);
     Vector3 v1 = new Vector3( vertBuffer[(idxBuffer[i+1]*3)],vertBuffer[(idxBuffer[i+1]*3)+1],vertBuffer[(idxBuffer[i+1]*3)+2]);
     Vector3 v2 = new Vector3( vertBuffer[(idxBuffer[i+2]*3)],vertBuffer[(idxBuffer[i+2]*3)+1],vertBuffer[(idxBuffer[i+2]*3)+2]);

     //Vector3 normal = Vector3.Normalize(Vector3.Cross(v2 - v0, v1 - v0));
     Vector3 normal = Vector3.Normalize(Vector3.Cross(Vector3.Sub(v2,v0) , Vector3.Sub(v1,v0)));

     normals[i+0] += normal.X;
     normals[i+1] += normal.Y;
     normals[i+2] += normal.Z;

  }
  for(int i = 0; i < idxBuffer.length; i+=3)
  {
      Vector3 tmp = new Vector3(normals[i+0],normals[i+1],normals[i+2]);
      Vector3 norm = Vector3.Normalize(tmp);
      normals[i+0] = norm.X;
      normals[i+1] = norm.Y;
      normals[i+2] = norm.Z;
  }

  vboHandles = new int[3];
  gl.glGenBuffers(3, vboHandles, 0);

  //populate the position buffer
  FloatBuffer fbData = Buffers.newDirectFloatBuffer(vertBuffer);
  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[VERTICES_IDX]); //the vertex data
  gl.glBufferData(GL4.GL_ARRAY_BUFFER, fbData.capacity() * 4,
          fbData, GL4.GL_STATIC_DRAW);
  fbData.clear();

   //populate the normals buffer
  FloatBuffer fbnorm = Buffers.newDirectFloatBuffer(normals);
  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[NORMALS_IDX]); //the normals data
  gl.glBufferData(GL4.GL_ARRAY_BUFFER, fbnorm.capacity() * 4,
          fbnorm, GL4.GL_STATIC_DRAW);
  fbnorm.clear();

//index buffer IBO Vertex
  IntBuffer dtaIndc = Buffers.newDirectIntBuffer(idxBuffer);
  gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, vboHandles[IBO_IDX]); //bind the indices to the vertex data
  gl.glBufferData(GL4.GL_ELEMENT_ARRAY_BUFFER, dtaIndc.capacity() * (Integer.SIZE / Byte.SIZE),
          dtaIndc, GL4.GL_STATIC_DRAW);
  dtaIndc.clear();

  //set vertex array index
  IntBuffer intBuffer = BufferUtil.newIntBuffer(1);
  gl.glGenVertexArrays(1, intBuffer);
  iVao = intBuffer.get(0);
  gl.glBindVertexArray(iVao);

  gl.glEnableVertexAttribArray(VERTICES_IDX);
  gl.glEnableVertexAttribArray(NORMALS_IDX);

  //normals
  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[NORMALS_IDX]);
  gl.glVertexAttribPointer(1, 3, GL4.GL_FLOAT, true, 0, 0);

  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[VERTICES_IDX]); //the vertex data
  // Associate Vertex attribute 1 with the last bound VBO
  gl.glVertexAttribPointer(0,3, GL2ES2.GL_FLOAT, false,0,0);

  //bind IBO
  gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, vboHandles[2]);

```

**The Vertex shader**

```
layout (location=0) in vec3 vertexPosition;
layout (location=1) in vec3 vertexNormal;

out vec3 LightIntensity;

//uniform mat4 ProjectionMatrix;
uniform mat4 ModelviewMatrix;
uniform mat3 NormalMatrix;
uniform mat4 MVP;

uniform vec4 LightPosition;  //light position in eye coords.
uniform vec3 Kd;  //diffuse light reflectivity
uniform vec3 Ld;  //light source intensity

void main(void) {

    //convert normal and position to eye coords
    vec3 tnorm = normalize( NormalMatrix * vertexNormal );
    vec4 eyeCoords = ModelviewMatrix * vec4(vertexPosition, 1.0);
    vec3 s = normalize( vec3(LightPosition - eyeCoords) );

    //the diffuse shading equation
    LightIntensity = Ld * Kd * max( dot( s, tnorm ), 0.0);

    //convert position to clip coordinates and pass along
    gl_Position = MVP * vec4(vertexPosition, 1.0);

}

```

**The Display routine**

```
GL4 gl = drawable.getGL().getGL4();
gl.glClear(GL4.GL_COLOR_BUFFER_BIT | GL4.GL_DEPTH_BUFFER_BIT);

float x = 0;
float z = 0;

Quaternion q = new Quaternion();

FloatUtil.makeIdentity(view2);
FloatUtil.makeIdentity(vw2);

//10 is the distance from centre to ground that eye is looking.
float eyeY = (float) (10 * Math.cos(Math.toRadians(rotAngleY)));
float eyeZ = (float) (10 * Math.sin(Math.toRadians(rotAngleY)));

float[] eye = {0, 5 + eyeY, -30 + eyeZ};
float[] center = {0,0,0};
float[] up = {0,1,0};
float[] mat4Tmp = new float[16];
FloatUtil.makeLookAt(vw3, 0, eye, 0, center, 0, up, 0, mat4Tmp);

float[] lp = {5.0f,5.0f,2.0f,1.0f};

shader.setUniform(iLightPos, multiply4(lp, vw3), Shade.MatDataType.VEC4);

int yyy = 0;
//draw field
for ( x = -60  ;x < 60 ; x+=2){
    for ( z = -60  ; z < 60 ; z+=2){

        view2 = vw3;

        //rotate the scene
        q = q.setIdentity();
        q = q.rotateByAngleNormalAxis( (float) Math.toRadians(rotAngle), 0, 1, 0);
        q = q.normalize();

        q.toMatrix(vw2, 0);

        //mult rotation and perspective
        view2 = multiply( view2, vw2);

        //apply the updated translation co-ords to vertices
        if ((x % 10) == 0){yyy = 1;}else{yyy=0;}
        view2 = translate(view2, (float)-transX-x, transY+yyy, -(transZ-z));

        shader.setUniform(iModelView, view2, Shade.MatDataType.MAT4);

        float[] norm = {view2[0],view2[1],view2[2],
                view2[4],view2[5],view2[6],
                view2[8],view2[9],view2[10]
        };

        shader.setUniform(iNorm, norm, Shade.MatDataType.MAT3);
        shader.setUniform(iMVP, multiply(projection,  view2), Shade.MatDataType.MAT4);

      //link view matrix to 'mat4 modelView' on vertex shader.

         //draw 12 triangles (36 vertices).
        gl.glBindVertexArray(iVao);
        //gl.glDrawArrays(GL4.GL_TRIANGLES, 0, 6);
        gl.glDrawElements(
                 GL4.GL_TRIANGLES,      // mode
                 idxBuffer.length,    // count
                 GL4.GL_UNSIGNED_INT,   // type
                 0           // element array buffer offset
             );

    }
}

```

Any help, hints or tips would be greatly appreciated.

# Answer
> 7 votes
How are you passing your normals to the vertex shader? It looks like those are the normals for each of the six faces of a cube, but the vertex shader operates on vertices, not faces. Unless you're doing something unusual, you need to specify a normal for each vertex.

In addition, if you want a cube to look right, you will need 24 vertices rather than 8, so that the vertex normals for each of the four vertices around one face point in the same direction. If you just have 8 vertices (which probably seems most natural, for a cube), each vertex will be shared by three faces. This is good for most situations, where you want smooth lighting across faces, but probably not what you're looking for when trying to light a cube.

---
Tags: opengl, java, glsl
---


# Question
Title: XNA: How do I match Spritebatch View/Projection Matrices with BasicEffect Matrices?
I'm rendering a bunch of 2D content using `SpriteBatch`es to a default XNA viewport. A simple 2D camera is used to move around the scene, which generates a transformation matrix passed to each `SpriteBatch.Begin()`-call.

I want to draw custom polygons on top of my `SpriteBatch`es, which I'm doing via `DrawIndexedPrimitives` (straightforward, as well). I'm using a `BasicEffect` to shade them.

How can I best match up the `SpriteBatch`'s implicit view and projection matrices with the `BasicEffect`'s matrices? Currently, I create the matrices for the `Effect` from scratch, using the `Viewport`'s properties. How can I get around this? Can I access the `Viewport`'s matrices and pass them into the `BasicEffect`?

So far, Google has come up empty on this.

# Answer
> 1 votes
So there is a DirectX library called the DirectX Tool Kit which is a porting of the underlying XNA code written by people who were members of the XNA team. Below is the code relevant to you question.

## SpriteBatch.cpp

---

**PrepareForRendering()**

```
// Set the transform matrix.
XMMATRIX transformMatrix = (mRotation == DXGI_MODE_ROTATION_UNSPECIFIED)
                           ? mTransformMatrix
                           : ( mTransformMatrix * GetViewportTransform(deviceContext, mRotation) );

mContextResources->constantBuffer.SetData(deviceContext, transformMatrix);

```

**GetViewportTransform()**

```
// Generates a viewport transform matrix for rendering sprites using x-right y-down screen pixel coordinates.
XMMATRIX SpriteBatch::Impl::GetViewportTransform(_In_ ID3D11DeviceContext* deviceContext, DXGI_MODE_ROTATION rotation )
{
    // Look up the current viewport.
    if ( !mSetViewport )
    {
        UINT viewportCount = 1;

        deviceContext->RSGetViewports(&viewportCount, &mViewPort);

        if (viewportCount != 1)
            throw std::exception("No viewport is set");
    }

    // Compute the matrix.
    float xScale = (mViewPort.Width  > 0) ? 2.0f / mViewPort.Width  : 0.0f;
    float yScale = (mViewPort.Height > 0) ? 2.0f / mViewPort.Height : 0.0f;

    switch( rotation )
    {
    case DXGI_MODE_ROTATION_ROTATE90:
        return XMMATRIX
        (
             0,       -yScale,  0,  0,
             -xScale, 0,        0,  0,
             0,       0,        1,  0,
             1,       1,        0,  1
        );

    case DXGI_MODE_ROTATION_ROTATE270:
        return XMMATRIX
        (
             0,       yScale,   0,  0,
             xScale,  0,        0,  0,
             0,       0,        1,  0,
            -1,      -1,        0,  1
        );

    case DXGI_MODE_ROTATION_ROTATE180:
        return XMMATRIX
        (
            -xScale,  0,       0,  0,
             0,       yScale,  0,  0,
             0,       0,       1,  0,
             1,      -1,       0,  1
        );

    default:
        return XMMATRIX
        (
             xScale,  0,       0,  0,
             0,      -yScale,  0,  0,
             0,       0,       1,  0,
            -1,       1,       0,  1
        );
    }
}

```

---
Tags: xna, matrix, projection, viewport, view
---


# Question
Title: Add a Countdown Timer that increments in JavaScript and resets per level(Resovled)
I am currently developing a Simon says type game using jquery and javascript.

I have linked a fully copy of the game on github

Github download and unzip to see the game fully https://github.com/Jamiex304/Simon\_Says\_Game\_Demo(Disabled because resolved)

And I have reached a problem I want to add a timer that the player can see ?

currently the level will just go on til the user clicks the wrong button in the sequence.

Some Basic info on the game the user will see a random sequence each level a new sequence is added with one more extra move Each time the user enters the right sequence they go to the next level all info can be found in the attached JavaScript with comments

WHAT I WANT HELP ADDING

I just want to add a timer that starts at 10 seconds when the user clicks the start button Each time the enter the right sequence the timer starts again when they reach 5 right sequences the timer adds 5 extra seconds and so

I already have a div made for it called Timer so the user can see it in the middle of the screen

I have attached the html code and the JavaScript that the game events and the github link offers the full game

Javascript

```
var game={ //game object
    level: 1, //current level
    turn: 0, //current turn
    difficulty: 1, // user difficulty
    score: 0, //current score
    active: false, //whether a turn is active or not
    handler: false, // whether the click and sound handlers are active
    shape: '.shape', // cached string for the pad class
    genSequence: [], //array containing the generated/randomized pads
    plaSequence: [], //array containing the users pad selections

    init: function(){                   //initialises the game
        if(this.handler === false){     //checks to see if handlers are already active
            this.initPadHandler();      //if not activate them
        }
        this.newGame();             //reset the game defaults

    },

    initPadHandler: function(){

        that=this;

        $('.pad').on('mouseup',function(){

            if(that.active===true){

                var pad=parseInt($(this).data('pad'),10);

                that.flash($(this),1,300, pad);

                that.logPlayerSequence(pad);

            }
        });

        this.handler=true;

    },

    newGame: function(){            //resets the game and generates a starts a new level

        this.level=1;
        this.score=0;
        this.newLevel();
        this.displayLevel();
        this.displayScore();

    },

    newLevel: function(){

        this.genSequence.length=0;
        this.plaSequence.length=0;
        this.pos=0;
        this.turn=0;
        this.active=true;

        this.randomizePad(this.level); //randomize pad with the correct amount of numbers for this level
        this.displaySequence(); //show the user the sequence

    },

    flash: function(element, times, speed, pad){ //function to make the pads appear to flash

        var that = this;                        //cache this

        if(times > 0){                          //make sure we are supposed to flash
            that.playSound(pad);                //play the corresponding pad sound
            element.stop().animate({opacity: '1'}, {        //animate the element to appear to flash
                duration: 50,
                complete: function(){
                element.stop().animate({opacity: '0.6'}, 200);
                }
            });                                             //end animation

        }

        if (times > 0) {                                    //call the flash function again until done the correct amount of times
            setTimeout(function () {
                that.flash(element, times, speed, pad);
            }, speed);
            times -= 1;                     //times - 1 for each time it's called
        }
    },

    playSound: function(clip){              //plays the sound that corresponds to the pad chosen

        var sound= $('.sound'+clip)[0];
        console.log(sound);
        console.log($('.sound'+clip));
        sound.currentTime=0;                //resets audio position to the start of the clip
        sound.play();                       //play the sound

    },

    randomizePad: function(passes){         //generate random numbers and push them to the generated number array iterations determined by current level

        for(i=0;i<passes;i++){

            this.genSequence.push(Math.floor(Math.random() * 4) + 1);
        }
    },

    logPlayerSequence: function(pad){       //log the player selected pad to user array and call the checker function

        this.plaSequence.push(pad);
        this.checkSequence(pad);

    },

    checkSequence: function(pad){           //checker function to test if the pad the user pressed was next in the sequence

        that=this;

        if(pad !== this.genSequence[this.turn]){    //if not correct

                this.incorrectSequence();

            }else{                                  //if correct
                this.keepScore();                   //update the score
                this.turn++;                        //incrememnt the turn

            }

        if(this.turn === this.genSequence.length){  //if completed the whole sequence

            this.level++;                           //increment level, display it, disable the pads wait 1 second and then reset the game
            this.displayLevel();
            this.active=false;
            setTimeout(function(){
                that.newLevel();
            },1000);
        }
    },

    displaySequence: function(){                    //display the generated sequence to the user

        var that=this;

        $.each(this.genSequence, function(index, val) {     //iterate over each value in the generated array

            setTimeout(function(){

                that.flash($(that.shape+val),1,300,val);

            },500*index*that.difficulty);               // multiply timeout by how many items in the array so that they play sequentially and multiply by the difficulty modifier
        });
    },

    displayLevel: function(){                           //just display the current level on screen

        $('.level h2').text('Level: '+this.level);

    },

    displayScore: function(){                           //display current score on screen
        $('.score h2').text('Score: '+this.score);
    },

    keepScore: function(){                              //keep the score

        var multiplier=0;

        switch(this.difficulty)                         //choose points modifier based on difficulty
        {
            case '2':
                multiplier=1;
                break;

            case '1':
                multiplier=2;
                break;

            case '0.5':
                multiplier = 3;
                break;

            case '0.25':
                multiplier = 4;
                break;
        }

        this.score += (1 * multiplier);                 //work out the score

        this.displayScore();                            //display score on screen
    },

    incorrectSequence: function(){                      //if user makes a mistake

        var corPad = this.genSequence[this.turn],       //cache the pad number that should have been pressed

            that = this;
            this.active=false;
            this.displayLevel();
            this.displayScore();

        setTimeout(function(){                          //flash the pad 4 times that should have been pressed
            that.flash($(that.shape+corPad),4,300,corPad);
        },500);

        $('.start').show();                             //enable the start button again and allow difficulty selection again
        $('.difficulty').show();

    }

};
$(document).ready(function(){                           //document ready

    $('.start').on('mouseup', function(){               //initialise a game when the start button is clicked
        $(this).hide();
        game.difficulty = $('input[name=difficulty]:checked').val();
        $('.difficulty').hide();
        game.init();

    });

});

```

# Answer
> 0 votes
Got it working full javascript below

```
var game = { //game object
    level: 1, //current level
    turn: 0, //current turn
    difficulty: 1, // user difficulty
    score: 0, //current score
    active: false, //whether a turn is active or not
    handler: false, // whether the click and sound handlers are active
    shape: '.shape', // cached string for the pad class
    genSequence: [], //array containing the generated/randomized pads
    plaSequence: [], //array containing the users pad selections

    init: function () { //initialises the game
        if (this.handler === false) { //checks to see if handlers are already active
            this.initPadHandler(); //if not activate them
        }
        this.newGame(); //reset the game defaults

    },

    initPadHandler: function () {

        that = this;

        $('.pad').on('mouseup', function () {

            if (that.active === true) {

                var pad = parseInt($(this).data('pad'), 10);

                that.flash($(this), 1, 300, pad);

                that.logPlayerSequence(pad);

            }
        });

        this.handler = true;

    },

    newGame: function () { //resets the game and generates a starts a new level

        this.level = 1;
        this.score = 0;
        this.newLevel();
        this.displayLevel();
        this.displayScore();

        //initialize timer to 10 seconds (10.0)
        this.timer = 10;

    },

    newLevel: function () {

        this.genSequence.length = 0;
        this.plaSequence.length = 0;
        this.pos = 0;
        this.turn = 0;
        this.active = true;

        this.randomizePad(this.level); //randomize pad with the correct amount of numbers for this level
        this.displaySequence(); //show the user the sequence
    },

    flash: function (element, times, speed, pad) { //function to make the pads appear to flash

        var that = this; //cache this

        if (times > 0) { //make sure we are supposed to flash
            that.playSound(pad); //play the corresponding pad sound
            element.stop().animate({
                opacity: '1'
            }, { //animate the element to appear to flash
                duration: 50,
                complete: function () {
                    element.stop().animate({
                        opacity: '0.6'
                    }, 200);
                }
            }); //end animation

        }

        if (times > 0) { //call the flash function again until done the correct amount of times
            setTimeout(function () {
                that.flash(element, times, speed, pad);
            }, speed);
            times -= 1; //times - 1 for each time it's called
        }
    },

    playSound: function (clip) { //plays the sound that corresponds to the pad chosen

        var sound = $('.sound' + clip)[0];
        console.log(sound);
        console.log($('.sound' + clip));
        sound.currentTime = 0; //resets audio position to the start of the clip
        sound.play(); //play the sound

    },

    randomizePad: function (passes) { //generate random numbers and push them to the generated number array iterations determined by current level

        for (i = 0; i < passes; i++) {

            this.genSequence.push(Math.floor(Math.random() * 4) + 1);
        }
    },

    logPlayerSequence: function (pad) { //log the player selected pad to user array and call the checker function

        this.plaSequence.push(pad);
        this.checkSequence(pad);

    },

    checkSequence: function (pad) { //checker function to test if the pad the user pressed was next in the sequence

        that = this;

        if (pad !== this.genSequence[this.turn]) { //if not correct

            this.incorrectSequence();

        } else { //if correct
            this.keepScore(); //update the score
            this.turn++; //incrememnt the turn

        }

        if (this.turn === this.genSequence.length) { //if completed the whole sequence

            this.level++; //increment level, display it, disable the pads wait 1 second and then reset the game
            this.displayLevel();
            this.active = false;

            // Stop counting when sequence is correct to avoid time running out before starting next level
            clearInterval(this.timerInterval);

            //Add 5.0 seconds each 5th level
            this.timer = 10 + 5 * Math.floor(this.level / 5);

            //Update timerdisplay to show fulltime while displaying next level sequence
            $(".Timer p").html(this.timer);

            setTimeout(function () {
                that.newLevel();
            }, 1000);
        }
    },

    // Countdown and update timer, call incorrectsequence when time's up
    countDown: function () {
        this.timer -= 0.1;
        $(".Timer p").html(this.timer.toFixed(1)); // Display 9.0 instad of 9
        if (this.timer < 0.1) {
            this.incorrectSequence();
        }
    },

    displaySequence: function () { //display the generated sequence to the user

        var that = this;

        var timerCount = 0;

        $.each(this.genSequence, function (index, val) { //iterate over each value in the generated array
            timerCount = index;
            setTimeout(function () {

                that.flash($(that.shape + val), 1, 300, val);

            }, 500 * index * that.difficulty); // multiply timeout by how many items in the array so that they play sequentially and multiply by the difficulty modifier
        });

        // Wait to start timer until full sequence is displayed
        setTimeout(function () {
            that.timerInterval = setInterval(function () {
                that.countDown()
            }, 100)
        }, 500 * timerCount * that.difficulty);
    },

    displayLevel: function () { //just display the current level on screen

        $('.level h2').text('Level: ' + this.level);

    },

    displayScore: function () { //display current score on screen
        $('.score h2').text('Score: ' + this.score);
    },

    keepScore: function () { //keep the score

        var multiplier = 0;

        switch (this.difficulty) //choose points modifier based on difficulty
        {
            case '2':
                multiplier = 1;
                break;

            case '1':
                multiplier = 2;
                break;

            case '0.5':
                multiplier = 3;
                break;

            case '0.25':
                multiplier = 4;
                break;
        }

        this.score += (1 * multiplier); //work out the score

        this.displayScore(); //display score on screen
    },

    incorrectSequence: function () { //if user makes a mistake

        //Stop counting down timer and display start message
        clearInterval(this.timerInterval);
        $(".Timer p").html("Get Ready your time starts when you click start");

        var corPad = this.genSequence[this.turn], //cache the pad number that should have been pressed

            that = this;
        this.active = false;
        this.displayLevel();
        this.displayScore();

        setTimeout(function () { //flash the pad 4 times that should have been pressed
            that.flash($(that.shape + corPad), 4, 300, corPad);
        }, 500);

        $('.start').show(); //enable the start button again and allow difficulty selection again
        $('.difficulty').show();

    }

};
$(document).ready(function () { //document ready

    $('.start').on('mouseup', function () { //initialise a game when the start button is clicked
        $(this).hide();
        game.difficulty = $('input[name=difficulty]:checked').val();
        $('.difficulty').hide();
        game.init();

    });

});

```

# Answer
> 0 votes
Javascript has the `setInterval(function(), milliseconds)` function which could help here.

If you need to get rid of the interval once you're done with it you can store your interval like so, and then clear it:

```
var timer = setInterval(tick, 1000);
clearInterval(timer);

```

# Answer
> 0 votes
I guess you want something like this:

```
var givenTime=10000
var timeLimit
var clockInterval
resetClock()
function updateClock(){
    var now=new Date().getTime()
    if(now<timeLimit){
        //Set the displayed clock to timeLimit-now
    }
    else{
        //Time has run out
        clearInterval(clockInterval)
    }
}
function resetClock(){
    timeLimit=new Date().getTime()+givenTime
    clearInterval(clockInterval)
    clockInterval=setInterval(updateClock,10)
}

```

You have `timeLimit` set to the point in time where the timer runs out, and then a function in an interval recalculate the time left approximately once every 10 ms. Beware that you can't count on `setInterval` to fire exactly as often as you ask for, see setTimeout or setInterval?

---
Tags: javascript, game-mechanics, html5, timer, jquery
---


# Question
Title: How does the SDL dynamic API inject itself in statically linked code
I've been using SDL2 for development almost since it came out. Long story short, I stumbled upon the SDL dynamic API explanation. I've looked in `SDL_Dynapi.c` to understand how it works. I get that the jump table can be updated with function pointers to newer versions of the functions, but what I don't get is how one would actually goes about doing that dynamically.

Did I miss a function declaration, is there some specific function to call outside the application? I have no idea how an updated `dynapi` loads itself.

# Answer
> 6 votes
It's pretty straightforward, if not entirely well documented. Reading the source (not sure if the released version differs significantly) tells me that you must export an environment variable `SDL_DYNAMIC_API` with the name of the .so you want to load. That .so must contain a symbol `SDL_DYNAPI_entry` with signature: `Sint32(SDLCALL*)(Uint32 apiver, void *table, Uint32 tablesize)`. If the library exists and the symbol exists, it will be loaded and the function called.

A combination of `apiver` (which is equal to `SDL_DYNAPI_VERSION`) and `tablesize` (roughly the number of dynamic functions) can be used to fill in the table at `table`. The `apiver` will only change if the ABI changes in a non-compatible way. The `tablesize` may grow, but hypothetically this is ok: it just means that the SDL library has new dynamic functions that you don't have to care about and you can safely only update the parts of `table` you already know about. The function should return non-zero on success and zero on failure.

The current code doesn't actually do anything on failure. It just carries on like nothing happened, so essentially SDL will just work like normal.

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


# Question
Title: Avoiding memory allocation in Android game development
For obvious reasons, allocating memory on the fly in Android game development is not recommended. For example:

http://developer.android.com/training/articles/perf-tips.html:

> There are two basic rules for writing efficient code:
>
> * Don't do work that you don't need to do.
> * Don't allocate memory if you can avoid it.

I'm following this advice and am avoiding any memory allocation whilst the game is in progress; however, it's limiting my approach to certain tasks. Whilst I could change my code to see what happens, there's a fair amount of it, and it's not going to tell me about the resulting performance on anything other than the limited range of hardware I have available to test it on.

I was wondering if there are any general rules of thumb which can provide an insight into this problem, such as how much allocation/deallocation you can get away with; whether it's the individual size of the allocation or the overall amount that's most important; things you can do to mitigate against the problem (I'm assuming the problem is chiefly having the garbage collector kick in and damage performance, and/or insufficient memory being available if it doesn't fire frequently enough); does it affect some versions of Android more than others, etc.

# Answer
In my experience with android, it is the garbage collection the kills the performance, not the allocation, although these two are tied hand and hand. As mentioned on the comments, pre-allocation is a way to deal with this issue. This is known as a memory pools. Another similar solution is object pool pattern. An object pool allocates as needed, but does not immediately destroy an object. If an object is needed and an old object is still alive, the old object is issued. this saves on the allocation and destroying of a frequently used, short lived objects.

In both cases, the objects are checked in and out of the pool, so you are never creating or destroying the objects yourself.

This object pool example is a generic pool, which you can use to create a pool for any object type.
> 3 votes

---
Tags: java, android, performance, opengl-es2, optimization
---


# Question
Title: Is there a way to prevent the user from playing the game simultaneously on 2 devices
Our game uses Google Play Services for authentication, multiplayer and cloud saves. We save the users inventory as a cloud save, and as the player partakes in multiplayer matches they might use items out of their inventory (coins, etc). Also, they may use in app purchases to add items to their inventory.

I want to try and avoid the hassle of cloud save game conflicts when the player (for whatever reason) decides to play the game on 2 devices at the same time.

I worry they may lose data when resolving save games and as their save games may contain coins and other items obtained via IAPs, this is unacceptable.

Is there a way to check if the user is currently logged in to the game on anther device and is actively playing on that device? We don't have our own servers and use GPS for all our work. What is a possible solution here?

# Answer
The client side asks the service "Am I allowed to keep playing with you?" every five seconds and the server responds with `true` or `false`. You store the date value that represents the last time the player "pinged" the service. Also store a single session key that is randomized and sent to the client upon logging in or at the beginning a game (if no login is needed). The client keeps polling with a packet or http request or whatever is good for you that tells the server and in turn, the database the player is connected and active.

When *someone* connects the server with the same identity, the server replaces the session key. When the previous player or device continues to communicate with the old session key, they get informed that they have been disconnected because someone connected the game with their identity from another device. This happens as a response to the "Are we still good packet".

The alternative is to check when was the last time the user with this identity was *alive* and if that date is less than say 15 seconds ago, tell the new person / device attempting to connect that this account is already active.

As you may have constraints as far as the amount of requests that could be made to the server, simply add this "You are still allowed to play" response as an answer to every request you are already making. Only save player state when they make a valid request and they are still allowed to play the game.

Like you suggested, you could store the unique session ID in the saved state, if a player logs in from another device, they will do a login request, randomize another session ID and update the DB. When the other device makes any request, the server will kindly notify them this session has been discontinues as another session was started with a different device.

This way it won't cost you any additional API calls (I think).

After reading this question once more, I wonder if you could simply save the state for multiple devices like branches, then perhaps merge the delta as needed. Instead of overwriting, load the current state that will describe the the amount of achievements and or accomplishments on each device so far and when you save back, save changes for the currently used device.
> 4 votes

---
Tags: savegame, synchronization, google-play-services
---


# Question
Title: How to combine the camera that follows the player and the camera shake effect in Unity?
I need to combine both camera that follows the player and the camera shake effect in the same moment. The problem is in that, if I make the shake effect for the camera, then the camera doesn't follow the player and if I make the camera follow the player, then the shake effect doesn't appear. The basic idea of my script is next:\`

```
Vector3 originalPos;
GameObject targetPlayer;
bool canShake;
void OnEnable()
 {
     originalPos = camTransform.localPosition;
 }

 void Update()
 {
         // Camera shakes
     if (CanShake)
     {
         transform.localPosition = originalPos + Random.insideUnitSphere * shakeAmount;
     }
         // Camera follows the player
     else
     {
         transform.position = new Vector3(targetPlayer.transform.position.x, transform.position.y, transform.position.z;
     }
 }

```

Does anyone have ideas how to combine these two things (camera shake effect and camera that follows the player) at the same moment?

# Answer
A simple solution would be to create and empty object( Camera container ) that follows the player and have the camera as a child. You can animated the shake independently however you want with the camera gameobject as long as it's a child of the container.

-- Container Object (Follow player)

└ Camera Object ( do animation )
> 1 votes

---
Tags: unity, camera
---


title: Location of "units" in Code

text:
# Question
Title: Location of "units" in Code
So, I've been playing around with the concept of a game, mechanically think of the Civilization games(Tile, turn-based strategy) but I am quite uncertain about where I should store the units location in the code. The tiles exist on a X and Y coordination of integers and that's how I imagine that the unit's would work too.

To clarify, I am unsure what's most effective, if it's example one: To have the tiles have a variable for which units are standing upon it and then when the unit move destroy them and recreate them on the tiles they are moving to.

That way when the tile is clicked it should be very easy to get the unit but it seems like it might be unsafe to remove and recreate units or sending a variable along. This might also be very unpractical when issuing an order to move somewhere, though, I am don't know.

The second example is to add the units to some kind of unit arraylist (or alike) but by that the game would have to find the unit with the right coordinates in said list (right?), this might appear as if the game is unresponsive and slow. Though it might not matter when you sort the list every x interval...

Any other ways to do it, ideas, fixes or even comments from you guys would be much appreciated.

# Answer
It's called a Hash data structure aka an associative array. It is often used to represent a sparse array. For instance like in your case, a huge world with myriads of tiles, that is sparsely occupied by only hundreds or thousands of units.

It is very fast because it knows where to look for values (in your case units) with a certain key (in your case positions \[x, y\] or tiles).

When a unit is created in some position, populate the hash with the position as key \[x, y\] (or alternatively use the tile it's on), and if there is no group of units under that key, add the unit as a new group `if (hash[tile] == null) hash[tile] = new ArrayList<Unit>(unit);`. If units exist there, add the new unit to the existing "positional" group `else hash[tile].append(unit); // Code is untested`.

Now you populate the Hash only with positions of interest as keys instead of having 10000's of objects that represent units (one for each tile).

When a unit moves from one place to another, you remove that unit from the collection stored under the key \[x, y\] or `Tile XYZ` and add it under the key \[xNew, yNew\] or `Tile someOtherNiftyTile`. You definitely don't delete and recreate, simply use list manipulation. If the old position is completely vacant now (empty list of units), you could delete the old key from the hash completely and that empty list as well; you could also put that list in a pool and simply remove the key.
> 1 votes

---
Tags: java, 2d, optimization
---


# Question
Title: How does the Maya ASCII FBX format store positions within animation?
I want to understand Maya's ASCII FBX format so I can convert animations in it to OSG (OpenSceneGraph) format.

I have a simple sphere, with a translation in one direction for 30 frames baked into an animation. I was expecting to see a list of values like this:

```
Frame #, X-position, Y-position, Z-position

```

However, I find nothing like it in the output file. For example, at frame 1, `X/Y/Z = -7.189/0/10.136`, but I cannot find any of these, or any other `X/Y/Z` position anywhere in the file.

What am I missing?

Could someone point out the frame/xyz position in the file?

# Answer
> 1 votes
So I found it - posting the response here for future reference

X/Y/Z = -7.189/0/10.136 in the Maya channel editor are rounded off values - the values themselves have a larger number of significant digits - e.g. -7.188707 so search for the first 2 decimal places only

---
Tags: animation, maya, file-format, fbx
---


# Question
Title: how to guarantee the order of response in a service-oriented mmo server cluster
i'm working on a mmo server these days. it's a service-oriented architecture, every service is one process which processes a specific type of request, and i have inventory service, battle service, etc. when received a request from client, the request will be dispatched to some corresponding service, based on the request type. let's assume we received two requests from one client in the cluster-side request message queue, first request1 and then request2, then the two requests will be dispatched to service1 and service2. so request2 may be handled first and the client will receive response2 first and then response1, which will not be what the client expect. so i'm wondering how to guarantee that response will go back in the same order request come?

# Answer
A slideshow (note: written in Korean language) say that Vindictus is a kind of service-oriented architecture MMO server.

Service-oriented architecture can handle massive concurrent players with its scale-out ability, but it is a kind of inter-process asynchronous programming. Like other asynchronous programming, service-oriented architecture must be taken into care or you will suffer from many Heisenbugs.

In Vindictus server case, the server is split into two kinds: front-end and back-end. front-end server is horizontally sharded so every front-end server do the same role. Front-end servers are directly connected to game clients. Meanwhile, back-end servers do the service role and they do different roles. Game clients never connect directly to back-end servers.

Every request from clients is always arrived front-end servers, so their processing is always ordered. Each request is dispatched to a back-end server then it will response to the same front-end server. \[#2\] If the request needs more processing by another back-end server, then it is dispatched to it and then returns. \[#1\]

Such a service-oriented architecture is a good way for scale-out servers, but this method makes too long latency to use it for fast-action gameplay of Vindictus. So it uses P2P networking in gameplay itself.
> 1 votes

---
Tags: networking, server
---


# Question
Title: How can I create an aperture-closing effect?
I'm looking to create an effect like this in a game I'm making:

I would describe it as a camera aperture closing.

I have the following requirements:

1. I need to be able to reverse the fade (open the aperture instead of close it)
2. The hole should close/open towards/from a given center point.

I can't really think of a great way to do this. I'm so used to `SpriteBatch` and `Texture2D` that I don't know how I could draw an ellipse style effect.

My current thoughts would be to make a few `Texture2D` frames and then animated them on the screen but that seems crazy.

If I just wanted to create pseudo-code to do it, it would probably look something like this (coming from a GDI/GDI+ background):

```
Call: Create_Relevant_Ellipse_Bounds;
Call: Set_Graphics_Exclusion_Clip_From_Ellipse;
Call: Fill_BackColor_With_Black_Using_Clip;
Call: Update_Ellipse_Bounds;
Call: Wait_For_Next_Draw;

```

# Answer
A point `p` is inside a circle at `c` with radius `r` when

```
(p.x - c.x)^2 + (p.y - c.y)^2 < r^2

```

is true. Using this equation you can color any points inside a circle one color (such as "transparent") and anything outside the circle a different color (such as "black"). You can even fade the edges of the circle, if you are so inclined.

You can write a custom shader to do this, and apply it to a full-screen quad. Set up shader constants defining the center of the circle and the current radius, and draw your quad. Every frame, decrease the radius by some factor to animate the circle getting smaller.

`SV_Position` contains the fragment position in D3D10 and up, but it's not available in D3D9 (which is what XNA is based on). Instead you can use the `VPOS` semantic (more information here). This will give you the position of `p` for the above equation. `c` and `r` come from your shader constants.

You can use the `step` function to return 0 or 1 based on which side of the equation is greater. This will allow you to avoid an actual *branch* in the shader, so you can compute the alpha component of your final color like this:

```
// alpha will be 1 if (r * r) is greater, meaning c is outside the radius.
// Ptherwise it will be zero.
float alpha = step(pow(p.x - c.x, 2) + pow(p.y - c.y, 2), r * r)

return (0,0,0,alpha);

```

If you didn't have `SV_Position` *or* `VPOS` available, you could always just put texture coordinates in the quad vertices. These will be interpolated across the face of the quad during rasterization, and can be used as an approximate coordinate system for specifying the position and radius of the camera aperture.
> 3 votes

# Answer
Thanks @JoshPetrie for getting me on the right track. I know XNA is basically dead but I could not find a good sample to do something that should be simple. Below I've posted all relevant code to perform an aperture close or open effect.

Before you run, add a sprite called `Background` to your project. The result of the code should be an aperture closing and opening over the center of your background sprite.

**`Game1.cs`**

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

    #region fields

    GraphicsDeviceManager graphics;
    Effect apertureEffect;
    QuadRenderer quadRenderer;
    SpriteBatch spriteBatch;
    Texture2D backgroundSprite;

    // flag to indicate direction of aperture effect
    private bool open = true;

    #endregion

    #region constructors

    public Game1()
    {
        this.graphics = new GraphicsDeviceManager(this);

        base.Content.RootDirectory = "Content";
    }

    #endregion

    #region methods

    protected override void LoadContent()
    {
        this.spriteBatch = new SpriteBatch(base.GraphicsDevice);
        this.backgroundSprite = base.Content.Load<Texture2D>("Background");
        this.apertureEffect = base.Content.Load<Effect>("Aperture");
        this.quadRenderer = new QuadRenderer(base.GraphicsDevice);

        // center screen for circle start
        float x = base.GraphicsDevice.Viewport.Width / 2f;
        float y = base.GraphicsDevice.Viewport.Height / 2f;

        this.apertureEffect.Parameters["c"].SetValue(new float[] { x, y });
        this.apertureEffect.Parameters["r"].SetValue(10f);

    }

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

        float radius = this.apertureEffect.Parameters["r"].GetValueSingle();

        if (this.open && radius > (base.GraphicsDevice.Viewport.Height / 2f))
            this.open = false;
        else if (!this.open && radius <= 0f)
            this.open = true;

        // adjust increment for "shutter speed"
        float increment = 1.0f;
        if (!this.open)
            increment = -increment;

        this.apertureEffect.Parameters["r"].SetValue(radius + increment);
    }

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

        // render any background sprite to showcase transparency
        // if no background sprite is rendered you will only see black
        this.spriteBatch.Begin();
        this.spriteBatch.Draw(this.backgroundSprite,
                              new Rectangle(0, 0,
                                            base.GraphicsDevice.Viewport.Width,
                                            base.GraphicsDevice.Viewport.Height),
                              Color.White);
        this.spriteBatch.End();

        // render the full-screen quad
        this.quadRenderer.Render(this.apertureEffect);

        base.Draw(gameTime);
    }

    #endregion

}

```

**`QuadRenderer.cs`**

```
internal sealed class QuadRenderer
{

    #region fields

    private VertexPositionTexture[] triangles;
    private GraphicsDevice device;
    private short[] indexData = new short[] { 0, 1, 2, 2, 3, 0 };

    #endregion

    #region constructors

    public QuadRenderer(GraphicsDevice device)
    {
        this.device = device;

        // texture coordinates semantic not used or needed
        this.triangles = new VertexPositionTexture[]
                         {
                           new VertexPositionTexture(new Vector3(1, -1, 0),
                                                     Vector2.Zero),
                           new VertexPositionTexture(new Vector3(-1, -1, 0),
                                                     Vector2.Zero),
                           new VertexPositionTexture(new Vector3(-1, 1, 0),
                                                     Vector2.Zero),
                           new VertexPositionTexture(new Vector3(1, 1, 0),
                                                     Vector2.Zero)
                         };
    }

    #endregion

    #region methods

    public void Render(Effect effect)
    {
        foreach (EffectPass p in effect.CurrentTechnique.Passes)
            p.Apply();

        this.Render();
    }

    private void Render()
    {
        this.device.DrawUserIndexedPrimitives(PrimitiveType.TriangleList,
                                              this.triangles, 0, 4,
                                              this.indexData, 0, 2);
    }

    #endregion

}

```

**`Aperture.fx`**

```
// center point of circle
float2 c;

// radius of circle
float r;

float4 ShadeVertex(float3 pos : POSITION0) : POSITION0
{
    return float4(pos, 1);
}

float4 ShadePixel(float2 p : VPOS) : COLOR0
{
    float alpha = step(r * r, pow(p.x - c.x, 2) + pow(p.y - c.y, 2));

    // black or transparent
    return float4(0, 0, 0, alpha);
}

technique Simple
{
    pass FirstPass
    {
        VertexShader = compile vs_3_0 ShadeVertex();
        PixelShader = compile ps_3_0 ShadePixel();
    }
}

```
> 1 votes

---
Tags: xna, graphic-effects
---