title: OpenGL - can't use glew 3.0

text:
# Question
Title: OpenGL - can't use glew 3.0
I've been trying to follow a tutorial of glew, but i can't run this **glGenVertexArrays**, it always leads to a memmory access violation!...

I tried `glExperimental = GL_TRUE` too, also updated my video card driver 2 times, but it doesn't run.

Btw, there's my code (to TRY to generate a simple triangle):

```
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

#include <glew.h>
#include <glfw.h>
#include <glm/glm.hpp>
using namespace glm;

#define GLFW_DLL
//#pragma comment(linker,  "/SUBSYSTEM:WINDOWS")
//#pragma comment(linker, "/ENTRY:mainCRTStartup")

int main()
{

    //glewExperimental = GL_TRUE;

    if(!glfwInit())
    {
        cout << "Failed to load graphics... " << endl;
        return -1;
    }

    GLuint VertexArrayID;
    glGenVertexArrays(1, &VertexArrayID);
    glBindVertexArray(VertexArrayID);

    static const GLfloat g_vertex_buffer_data[] =
    {
        -1.0f, -1.0f,  0.0f,
         1.0f, -1.0f,  0.0f,
         0.0f,  1.0f,  0.0f,
    };

    GLuint vertexbuffer;
    glGenBuffers(1, &vertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);

    glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4);
    glfwOpenWindowHint(GLFW_VERSION_MAJOR, 3);
    glfwOpenWindowHint(GLFW_VERSION_MINOR, 1);
    //glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwOpenWindowHint(GLFW_OPENGL_PROFILE, 0);

    if(!glfwOpenWindow(1024, 768, 0, 0, 0, 0, 32, 0, GLFW_WINDOW))
    {
        cout << "Failed to open window";
        glfwTerminate();
        return -2;
    }

    glfwSetWindowTitle("IfUSeeingThisMsgTheShitWorked");

    glfwEnable(GLFW_STICKY_KEYS);

    //Main loop
    do
    {
        cout << "happaned";
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
        glVertexAttribPointer(0,3, GL_FLOAT, GL_FALSE, 0, (void*) 0);

        glDrawArrays(GL_TRIANGLES, 0, 3);
        glDisableVertexAttribArray(0);

        glfwSwapBuffers();

    }while(glfwGetKey(GLFW_KEY_ESC) != GLFW_PRESS && glfwGetWindowParam(GLFW_OPENED));

    return 0;
}

```

Also, I want to point out that this function doesn't work:

```
glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

```

so I had to change it to:

```
glfwOpenWindowHint(GLFW_OPENGL_PROFILE, 0);

```

Does it have anything to do with my error? hm.

I'm posting it here, just to make sure that there's no other thing I can do, other than buy a new video card. I really want to use the modern OpenGL, it is pointless to learn the old one.

# Answer
You're not actually calling glewInit in your code, so you're not even loading the GL entry points. You should add a call to glewInit *after* your glfwInit call, like so:

```
if(!glfwInit())
{
    cout << "Failed to load graphics... " << endl;
    return -1;
}

if (glewInit () != GLEW_NO_ERROR)
{
    cout << "Failed to initialize GLEW... " << endl;
    return -1;
}

// check for required GL_VERSION and extensions here and error out if requirements not met

// and everything else should follow the same as before from here...
GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);

```
> 1 votes

# Answer
You're apparently not using Glew at all: you don't initialise the library. It looks like you haven’t even read the first sentence of the first paragraph of the GLEW documentation.

Another thing you do before even creating the OpenGL context is create a vertex buffer. That cannot work either: OpenGL doesn’t exist until you create an OpenGL context.

This is the order in which you need to do things:

* Create an OpenGL context (using glfw)
* Initialise GLEW
* Use OpenGL functions
> 3 votes

---
Tags: opengl
---


title: Bullets Spawning in same direction

text:
# Question
Title: Bullets Spawning in same direction
I'm using XNA to make a Bullet Hell Shooter game, and I'm running into some troubles when I try to change the direction in which the bullets move. Been trying to debug for awhile, but haven't gotten anywhere.

The effect that I am trying to have is

I've included all code that might have any dealing with the code.

Custom Box class(really only used for holding the Rectangle and Velocity)

```
    class Box
    {
        public Rectangle rect;
        public Vector2 velo;
        public Box()
        {
            rect = new Rectangle();
        }

        public Box(Rectangle r, Vector2 v)
        {
            rect = r;
            velo = v;
        }
    }

```

Global Declaration:

```
    List<Box> bullets;
    List<int> bulletType;

```

Bullet Logic:

```
    public void bulletStuff()
    {
        if (bullets.Count > 100)
        {
            while (bullets.Count > 99)
            {
                bullets.RemoveAt(0);
                bulletType.RemoveAt(0);
            }
        }

        for (int i = 0; i < bullets.Count; i++)
        {
            bullets[i].rect.Y -= (int)bullets[i].velo.Y;
            bullets[i].rect.X += (int)bullets[i].velo.X;

            if (bullets[i].rect.Y < 0)
            {
                bullets.RemoveAt(i);
            }
        }
    }

```

Collision w/ Enemy & Enemy Logic(Also a Box)

```
        public void enemyStuff()
        {
            for (int i = 0; i < enemyRects.Count; i++)
            {
                enemyRects[i].rect.Y += (int)enemyRects[i].velo.Y;
                enemyRects[i].rect.X += (int)enemyRects[i].velo.X;

                if (enemyRects[i].rect.Y >= 800)
                {
                    enemyRects.RemoveAt(i);
                    break;
                }

                if (enemyRects[i].rect.Intersects(playerRect))
                {
                    playerHealth--;
                    enemyRects.RemoveAt(i);
                    break;
                }

                for (int j = 0; j < bullets.Count; j++)
                {
                    if(bullets[j].rect.Intersects(enemyRects[i].rect))
                    {
                        bullets.RemoveAt(j);
                        bulletType.RemoveAt(j);
                        enemyHealth[i]--;
                    }
                }

                if (enemyHealth[i] <= 0)
                {
                    enemyRects.RemoveAt(i);
                    enemyHealth.RemoveAt(i);
                    enemiesKilled++;
                    break;
                }
            }
        }

```

Update Method

```
            if ((curKeyState.IsKeyDown(Keys.Space) && !preKeyState.IsKeyDown(Keys.Space)) || (curMouseState.LeftButton == ButtonState.Pressed && preMouseState.LeftButton == ButtonState.Pressed))
            {//Spawning the Elements
                Box Temp;
                if (level == 0)
                {
                    Temp = new Box();
                    Temp.rect = new Rectangle(playerRect.X + (playerRect.Width / 2) - 2, playerRect.Y - (playerRect.Height / 2), 5, 5);
                    Temp.velo = new Vector2(0, 10);
                    bullets.Add(Temp);
                    bulletType.Add(0);
                }
                else if (level == 1)
                {
                    Temp = new Box();
                    Temp.rect = new Rectangle(playerRect.X + (playerRect.Width / 2) - 2, playerRect.Y - (playerRect.Height / 2), 10, 10);
                    Temp.velo = new Vector2(-2, 10);
                    bullets.Add(Temp);
                    bulletType.Add(1);
                    Temp.velo = new Vector2(2, 10);
                    bullets.Add(Temp);
                    bulletType.Add(2);
                }
                else if (level == 2)
                {
                    Temp = new Box();
                    Temp.rect = new Rectangle(playerRect.X + (playerRect.Width / 2) - 2, playerRect.Y - (playerRect.Height / 2), 10, 10);
                    Temp.velo = new Vector2(-2, 10);
                    bullets.Add(Temp);
                    bulletType.Add(1);
                    Temp.velo = new Vector2(2, 10);
                    bullets.Add(Temp);
                    bulletType.Add(2);
                }
                else
                {
                    Temp = new Box();
                    Temp.rect = new Rectangle(playerRect.X + (playerRect.Width / 2) - 2, playerRect.Y - (playerRect.Height / 2), 10, 10);
                    Temp.velo = new Vector2(-2, 10);
                    bullets.Add(Temp);
                    bulletType.Add(1);
                    Temp.velo = new Vector2(2, 10);
                    bullets.Add(Temp);
                    bulletType.Add(2);
                }

            }

            playerRect.X = curMouseState.X - playerRect.Width / 2;
            playerRect.Y = curMouseState.Y - playerRect.Height / 2;

            levelStuff();
            bulletStuff();
            enemyStuff();

            if (playerHealth == 0)
            {
                ScreenManager.Instance.addScreen(new TitleScreen(myGame)); //Exits to menu
            }

            base.Update(gameTime);
        }

```

What is occurring currently is this:

As you can see, it is spawning both new bullets(which are supposed to go opposite of each other) moving in the same direction.

# Answer
> 4 votes
Allow me to comment a little bit of your code:

```
Temp = new Box(); //create a new box
Temp.rect = new Rectangle(playerRect.X + (playerRect.Width / 2) - 2,
  playerRect.Y - (playerRect.Height / 2), 10, 10); //set its size and position
Temp.velo = new Vector2(-2, 10); //set its velocity to (-2, 10)
bullets.Add(Temp); //add it to the bullets list
bulletType.Add(1); //add a type...
Temp.velo = new Vector2(2, 10); //now change its velocity (this is still accessing the object stored in the list).
bullets.Add(Temp); //add it AGAIN to the list. Now we have two bullets with a velocity of (2, 10)
bulletType.Add(2); //add a type.

```

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


# Question
Title: pytmx: issue trying to get the correct texture rectangle for sprite for objetcs on map
:D Hello :D

I am currently developing a game engine. I'm using maps designed with Tiled and I placed several objects on a test map to develop the feature of loading objects as sprites/entities and I'm not able to get the correct texture rectangle for certain `GID` (with correct, I mean the chunk of image that I place as an object on the map), even thought that I'm looking for such `GID`s on the same place that I look for pattern tiles. anyway, I have two screenshots to illustrate.

Where I am right now: bad http://ompldr.org/vaGg4eA/Captura%20de%20pantalla%20de%202013-02-15%2017:05:51.png

What I want to achieve: good http://ompldr.org/vaGg5MA/Captura%20de%20pantalla%20de%202013-02-15%2017:20:08.png

There is the relevant source code:

```
def loadmap(self, mapfilepath=None):
    """ Load the map of the corresponding scene.

    Not need to implement this method.
    All map files must be read in
    tmx format, Tiled Map Editor Software
    http://www.mapeditor.org/"""
    if mapfilepath:
        self.__tmxmapfile = common.settings.joinpaths(
            common.settings.getrootfolder(),
                                        "maps", mapfilepath)
        self.tmxmapdata = tmxloader.load_tmx(self.__tmxmapfile)

        heightlist = []
        widthlist = []
        tilesets = []

        # These list of vertexarrays carry only visible vertices,
        # By layer.
        self.__vertexarraytodraw = []
        for i in xrange(0, len(self.tmxmapdata.tilelayers)):
            self.__vertexarraytodraw.append(
                sfml.VertexArray(sfml.PrimitiveType.QUADS))

        # Add a list of empty lists to place sprites
        # Each empty list represents a layer.
        self.sprites = []
        for i in xrange(0, len(self.tmxmapdata.tilelayers)):
            self.sprites.append([])

        objgid = []
        for gid in self.tmxmapdata.getObjects():
            # Registers the actual GID.
            rgid = self.tmxmapdata.registerGID(gid.gid)
            if rgid not in objgid and rgid != 0:
                # The returned GID is the GID used internally by pytmx
                objgid.append(rgid)
        logging.info("GIDs de objetos: {0}".format(objgid))

        logging.info("Cargando las baldosas del escenario...")
        # Load all the tiles from the set of tiles
        # Based on code written by bitcraft.
        self.tmxmapdata.images = [0] * self.tmxmapdata.maxgid

        for firstgid, tile in sorted((tile.firstgid, tile) for tile in \
                                  self.tmxmapdata.tilesets):
            filename = os.path.basename(tile.source)
            tilesets.append(
                media.loadimg("maps/tilesets/{0}".format(filename)))

            w, h = tilesets[-1].size
            widthlist.append(w)
            heightlist.append(h)
            totalheight = sum(heightlist[1:], 0)
            real_gid = tile.firstgid - 1
            logging.debug("tile.firstgid: {0}".format(
                    tile.firstgid))

            tilewidth = tile.tilewidth + tile.spacing
            tileheight = tile.tileheight + tile.spacing

            # some tileset images may be slightly larger than the tile area
            # ie: may include a banner, copyright, ect.
            # this compensates for that
            width = ((int((w - tile.margin * 2) + tile.spacing) / tilewidth) \
                     * tilewidth) - tile.spacing
            height = ((int((h - tile.margin * 2) + tile.spacing) / tileheight) \
                      * tileheight) - tile.spacing

            # using product avoids the overhead of nested loops
            p = product(xrange(tile.margin, height+tile.margin, tileheight),
                        xrange(tile.margin, width+tile.margin, tilewidth))

            for (y, x) in p:
                real_gid += 1

                gids = self.tmxmapdata.mapGID(real_gid)
                quad = None

                # This GID is used somewhere in the scene?
                if gids and gids[0][0] in objgid:
                    # This GID belongs to an object that will be drawn
                    # Within the scenario.

                    texpos = sfml.Vector2(float(x), float(y + totalheight))
                    texsize = sfml.Vector2(tilewidth, tileheight)
                    quad = sfml.Rectangle(texpos, texsize)
                    # sfml.Rectangle(
                    #     (x, y + totalheight),
                    #     (tilewidth,
                    #      totalheight + tileheight))
                elif gids:
                    # This GID belongs to a tile.
                    v1 = sfml.Vertex((0, 0), None, sfml.Vector2(
                            float(x), float(y + totalheight)))
                    v2 = sfml.Vertex((0, 0), None, sfml.Vector2(
                            v1.tex_coords.x + tilewidth,
                            v1.tex_coords.y))
                    v3 = sfml.Vertex((0, 0), None, sfml.Vector2(
                            v1.tex_coords.x + tilewidth,
                            v1.tex_coords.y + tileheight))
                    v4 = sfml.Vertex((0, 0), None, sfml.Vector2(
                            v1.tex_coords.x,
                            v1.tex_coords.y + tileheight))
                    quad = (v1, v2, v3, v4,)

                elif gids == []:
                    # This GID is not used for anything.
                    continue

                # Stores the object, no matters if a tuple with vertexs
                # or a sfml's rectangle
                for gid, flag in gids:
                    logging.debug("real_gid: {0}, gid:"
                                  " {1}, flag: {2}".format(real_gid,
                                                           gid, flag))
                    self.tmxmapdata.images[gid] = quad

```

Thanks! :)

# Answer
and as I should have guessed, this is related to a bug on pytmx, more details here: https://github.com/bitcraft/PyTMX/issues/9#issuecomment-13922180
> 1 votes

---
Tags: tiles, maps, python, sfml
---


# Question
Title: Can I take pictures of things I own and use them in a game as art assets or is that an IP violation?
For example what if I take a picture of a Tonka truck, can I use that as an art asset? What if the toy is more generic?

# Answer
Usual caveat: I am not a lawyer, this is not legal advice, the relevant laws vary from country to country, city to city, etc.

The basic concepts are these: you own one instance of the truck. You can sell your instance of the truck to someone else (according to the first sale doctrine, which states that the Copyright owner's **distribution rights** only apply to the first sale of each particular instance of a protected work). You may not create new instances of the truck -- those **reproduction rights** are still possessed by the copyright owner.

What you're asking here is whether the copyright owner maintains his **adaptation rights** -- the ability to take one work (a model of a truck) and use it to make a different, related work (a photo of a model of a truck). The law here is a little less settled. We could point at different cases which have ruled in different ways, about whether or not the copyright owner surrenders his adaptation rights at the same time he surrenders his distribution rights, via the first sale doctrine.

WIPO's position on the topic is that one needs explicit approval from the copyright holder in order to adapt a copyrighted work into another form -- that the first sale doctrine only applies to **distribution rights**, not **adaptation rights**, but even they acknowledge that the issue is unclear at the current time.

Best advice is to ask a qualified lawyer who practices in your area, who knows the relevant up-to-the-minute case law, and how it's interpreted in your area. This really isn't the sort of thing that you want to get wrong. :)
> 6 votes

---
Tags: art, intellectual-property
---


title: in the shadow of a sphere

text:
# Question
Title: in the shadow of a sphere
(Related, but somewhat different, to my previous question)

How can I determine in a fragment shader if a fragment is in the ***shadow*** of a sphere?

That is, if it is occluded by the sphere and is past the sphere's horizon from the camera (if you are in front of the horizon you are not in the shadow even if you are *in* the sphere; the sphere is not solid)

In perspective, the horizon of the sphere is in front of the centre-point. Imagine holding a football at arms-length and stare at a point on the horizon of it; now move the football closer to you eye; what happens? It is no longer visible; the closer the sphere is to the eye, the less of the surface you can see:

As I imagine it, it is:

1. are you in the cone that is from the camera and passes through the horizon of the sphere as seen from the eye? and
2. are you past that horizon?

How do you compute the plane of the horizon, the cone, and how do you test for it in the fragment shader?

1. Imagine you had a ray that was through camera and fragment. The nearest distance between that ray and the *centre* of the sphere being less than the sphere's radius would tell you if it was in the 'cone' of the sphere.
2. Now imagine you knew the distance the camera to the horizon; if the closest point on the ray was less than this distance, its in front of the sphere; else its past the horizon. (We can make this simplification the fragments we want to test are never deep in the middle of the sphere.)

With these two values, you determine if a fragment is 'in the shadow' of the sphere.

But how do you compute this? What, even, is the coordinate of the camera (`0,0,-1` if orthogonal projection, else `0,0,0`?)? And how far away is the horizon of the sphere?

And what's the code for nearest point on ray to point? What I've come up with is\[src\]:

```
t = (P-B).(A-B) / (A-B).(A-B)

```

If `P` is the sphere's centre, and `A` is the fragment's position and `B` is the camera (at `0,0,0` so can be omitted as its a no-op):

```
// its a unit sphere:
var sphereCentre = mat4_vec3_multiply(
    mat4_inverse(mat4_multiply(pMatrix,mvMatrix)),
    [0,0,0]);
gl.uniform3fv(program.sphereCentre,sphereCentre);
gl.uniform1f(program.sphereRadius,1);

```

Then the vertex shader just has to pass the fragment position along:

```
precision mediump float;
attribute vec3 vertex;
uniform mat4 pMatrix, mvMatrix;
varying vec3 p;
void main() {
    gl_Position = pMatrix * mvMatrix * vec4(vertex,1.0);
    p = gl_Position.xyz/gl_Position.w;
}

```

And the fragment shader sees if its inside-the-cone using distance to sphere centre:

```
precision mediump float;
uniform vec4 fgColour, bgColour;
uniform vec3 sphereCentre;
uniform float sphereRadius; // always 1 in my game fwiw
varying vec3 p;
void main() {
    float t = dot(sphereCentre,p) / dot(p,p); // where on line?
    vec3 d = (p*t) - sphereCentre; // distance from nearest point to sphere
    //### now we need to know if its in front of the horizon to force fgColour ???
    gl_FragColor = (dot(d,d) <= sphereRadius*sphereRadius)? fgColour: bgColour;
}

```

This might be along the right track, but its not working (it looks hopeful drawn in ortho; in perspective it often draws things in the wrong colour). And how to compute the horizon?

# Answer
> 0 votes
To answer my own question:

The camera is at `0,0,0` in *view* space.

The sphere's centre has to be converted to view space and passed in as a uniform; this means multiplying it by the modelview matrix.

The vertex shader passes on the fragment's coordinate in view-space:

```
precision mediump float;
attribute vec3 vertex;
uniform mat4 pMatrix, mvMatrix;
varying vec4 pos;
void main() {
    pos = (mvMatrix * vec4(vertex,1.0));
    gl_Position = pMatrix * pos;
}

```

The fragment shader does the check:

```
precision mediump float;
uniform vec4 fgColour, bgColour;
uniform vec3 sphereCentre;
uniform float sphereRadius2; // always 1 in my game fwiw
varying vec4 pos;
void main() {
    vec3 p = pos.xyz/pos.w;
    float t = dot(sphereCentre,p)/dot(p,p);
    vec3 d = (p*t)-sphereCentre;
    gl_FragColor = (dot(d,d) > sphereRadius2 || t<=1.0)? fgColour: bgColour;
}

```

This computes where on the fragment's ray the nearest point is, as a ratio `t`.

It also computes the distance (squared - `dot(d,d)`) between the nearest point and the sphere's centre.

If the nearest point is beyond the sphere or the intersection of the line is less than 1 (meaning it is in front of the sphere) then it is in the foreground.

To compute point sprites correctly you need an extra check if it is in the background because the check outlined above is for the centre-point of the sprite and not each fragment in the sprite. If its possibly in the shadow of the sphere, you need to additionally check the exact fragment in the sprite.

# Answer
> 1 votes
The generalized solution would be to (in world space) draw a line between the fragment's location and the camera. If said line passes through or intersects the sphere your fragment falls behind the sphere and will not be visible.

Here is a breakdown of the math you would use for checking the intersection.

# Answer
> 1 votes
It suddenly occurs to me that there's a *really* easy solution to all this, which requires no shader logic at all. Just use the depth buffer.

Draw a (filled in) circle at the proper location and distance from the camera, pointed straight at the camera. Just use the `glColorMask` to turn off depth writes when you do draw the circle.

Once the depth is laid down, any fragments you draw later that are behind it will be culled by the depth buffer.

I'll assume you know how to draw a filled-in circle of a given radius, location, and facing. So instead, I'll cover how to compute where it goes.

Given the world-space position of your sphere P, with a world-space sphere radius R, and a camera location in world-space C, the world-space location of your circle should be this.

We compute the distance from P to place our circle. This is done with this equation:

```
dist = (R*R) / length(P - C)

```

We then use the distance to compute the the actual location, by getting the direction from P towards C and multiplying it by the distance.

```
dir = normalize(C - P)
pos = dir * dist

```

Note that `dir` is the direction towards the camera which the circle plane must face.

Oh, and don't forget to turn the color mask back *off* after you draw the sphere.

---
Tags: opengl, graphics, glsl, geometry
---


title: How to start in animating my model?

text:
# Question
Title: How to start in animating my model?
I got a model from TurboSquid. Which is an archer and when i imported the model I got all the textures to be put on properly. The thing is the actual character has no children nodes, is it possible to still animate this model. I have looked throughout the files and there are a bunch of textures, but I don't happen to see any animations.

Along side that the asset comes with an Avatar, I looked on the docs and still a little confused as to what that is about. If I cannot animate this model how could I force it to animate somehow or how could I make my own model.

I am not a artist at all and just focus on the gaming logic and and programming, and I am working solo. Just wondering what are some options to get a game up and running with some decent graphics. So, far I use the model to get the game play down, but now I want to make it visually appealing.

# Answer
> 3 votes
You can animate your model in a 3D animation-software that supports skeletal animation. The process of applying a skeleton to a mesh is called *rigging*.

Depending on the current pose of the model, the rigging can be easier or more difficult to do. Normally you'll want a pose with arms spread out, much like in this drawing of Leonardo da Vinci:

If your model is already in an "action-pose", it's going to be harder to rig and animate. Also animations that deviate a lot from the "base" pose of the model will be much more challenging.

So your first step would be the rigging (applying a skeleton to your mesh) and then animating. You can then export the model with animations and play these in Unity.

# Answer
> 0 votes
ZYeek, What is the file extension on the model that you downloaded(\*.3ds, \*.obj, etc.)? Providing that will allow people answering your question to give you a better direction on what steps to take. Blender (as Shivan suggested) is probably your best bet, it works well with Unity,it's free, has strong & helpful community support, can import and export the more popular model formats, and there are even skeletal rigs that are structured to be quickly added for prototyping (for typical biped characters), that you can attach to your model, an example is the BlenRig System. The only down side is the time to learn rigging, if your willing to learn it, or would rather use a site like Maximo. In the long run your best bet would be to put in the time to learn character rigging, using your program of choice, modeling and rigging your own characters will give you the most complete coverage on your animations.

# Answer
> 0 votes
If you have Unity 4, you can use Unity's new Mecanim animation tool. Here's a tutorial: http://video.unity3d.com/video/7362044/unity-40-mecanim-animation. Also, on the asset store, you can get 150 free Mecanim animations: https://www.assetstore.unity3d.com/#/content/5330

---
Tags: unity, animation
---


# Question
Title: How to make a simple HUD with no library
I am writing a simple game in c++ using opengl in a windows system.

I have the scene and I need some informative text to appeared to the left top/bottom of the screen

I am printing these messages with a little plane and the text on it, but I want them to be aligned at the corners of the screen.

So I've read this question here and I thought it seemed quite good and closer to my needs.

So, this is **some** of my code already used:

In init function of openGL:

```
glShadeModel (GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glClearDepth(1);
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);

```

In the Resize function:

```
if (window_height == 0) window_height = 1;
glViewport(0, 0, window_width, window_height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, (float)window_width/(float) window_height, 1.0, 550.0);

```

And finally in the render function:

```
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0, 0, -250); //is used for making the scene visible
RenderScene();
glutSwapBuffers();

```

I've tried using the ready3D() and then RenderScene() functions but the scene looked a lot different to what I was aiming.

How can I achieve this simple HUD (printing messages aligned to the window's corners)?

**Edit #1:**

This is what I see (terrain and message below):

I want the message to be aligned at the bottom left corner as well as other messages.

# Answer
> 3 votes
You should set the projection matrix properly first, from OpenGL FAQ 9.030,

To set up a 2D projection, you need to change the Projection matrix. Normally, it's convenient to set up the projection so one world coordinate unit is equal to one screen pixel, as follows:

```
 glMatrixMode (GL_PROJECTION);
 glLoadIdentity ();
 gluOrtho2D (0, windowWidth, 0, windowHeight);

```

You can have more details from the OpenGL FAQ

---
Tags: c++, opengl, gui
---


title: Debug Render In Cocos2d Android

text:
# Question
Title: Debug Render In Cocos2d Android
I want to implement debug render for cocos2d android.So I can view how bodies are created. Right now I use gdx.jar file for box2d and load that jar file following way.

```
static {
      System.loadLibrary("gdx.jar");
}

```

All the desire bodies are created but I need box2d debug renderer. I have search many place for this question but I could not found anything. So please anybody has knowledge regarding this then suggest me.

# Answer
> 1 votes
You can use GLES\_Render class in TestCpp, which is located in

```
 ./samples/TestCpp/Classes/Box2DTestBed/GLES-Render.cpp
 ./samples/TestCpp/Classes/Box2DTestBed/GLES-Render.h

```

of the download package.

To implement the debug draw, you can draw the debug renderer with your world data after CLayer::draw(); as demonstrated in samples/TestCpp/Classes/Box2DTestBed/Box2dView.cpp ,

```
void Box2DView::draw()
{
    CCLayer::draw();

    ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position );

    kmGLPushMatrix();

    m_test->m_world->DrawDebugData();

    kmGLPopMatrix();

    CHECK_GL_ERROR_DEBUG();
}

```

If you are using old cocos2d-x library you have follow guide here.

---
Tags: box2d, physics, cocos2d, cocos2d-x, jbox2d
---


# Question
Title: Different shaders for different objects DirectX 11
I am learning `Direct3D 11`, and in all basic tutorials I found on shader writing, Vertex and Pixel shaders are written so they transform whole scene same way. Tutorials like render cube with texture...

But I wonder, how do you differentiate objects? What if you want, for example, to simulate mirror surface on some object and use different shaders to render rest of the scene? I think that most games must use many vertex and pixel shaders to achieve various look and transformations.

Thank you.

# Answer
Yes, a game engine will in general have a variety of different shaders. The typical pattern is:

1. While initializing the engine and loading the game world, prepare all the shaders you will use for rendering. By "prepare" I mean load them into memory, compile them if necessary, and do all the `ID3D11Device::CreatePixelShader` and similar calls to get the D3D shader objects allocated and ready to go. Keep the objects in an array or some other data structure.

Usually you will have a one-to-one relationship between vertex shaders and pixel shaders that are designed to work together. I think of them as a single object, which I just call a "shader", even though it really contains a vertex shader and a pixel shader (and maybe geometry/hull/domain shaders as well).
2. Each frame, once you have found the list of objects (meshes) to render, sort them by shader. The idea is to minimize the number of times you switch shaders in a frame, by drawing all the objects with a given shader together. This is because switching shaders is a somewhat expensive operation (although you can certainly do it several hundred or a thousand times per frame, so it's not really *that* expensive).

In fact, you can go one step further and sort meshes by shader first and material second. By "material", I mean a combination of a shader and a set of textures and parameters for it. Shaders usually have some textures and numeric parameters (stored in constant buffers) that feed into them, so for instance a brick material and asphalt material might use the same shader code, just with different textures.
3. To draw, just loop over the shaders, set each shader in the `ID3D11DeviceContext`, set any parameters (constant buffers, textures, etc.), then draw the objects. In pseudocode, including the shaders/materials distinction I mentioned:

```
for each shader:
    // Set the device context to use this shader
    pContext->VSSetShader(shader.pVertexShader);
    pContext->PSSetShader(shader.pPixelShader);

    for each material that uses this shader:
        // Set the device context to use any constant buffers, textures, samplers,
        // etc. needed for this material
        pContext->VSSetConstantBuffers(...);
        pContext->PSSetConstantBuffers(...);
        pContext->PSSetShaderResources(...);
        pContext->PSSetSamplers(...);

        for each mesh that uses this material:
            // Set any constant buffers containing parameters specific to the mesh
            // (e.g. world matrix)
            pContext->VSSetConstantBuffers(...);

            // Set the context to use the vertex & index buffers for this mesh
            pContext->IASetInputLayout(mesh.pInputLayout);
            pContext->IASetVertexBuffers(...);
            pContext->IASetIndexBuffer(...);
            pContext->IASetPrimitiveTopology(...)

            // Draw it
            pContext->DrawIndexed(...)

```

There's a lot more that could be said about managing objects, meshes, shaders, input layouts, constant buffers, etc. but this should be enough to get you started. :)
> 25 votes

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


title: How to learn 2d animation?

text:
# Question
Title: How to learn 2d animation?
Where can I learn how to do simple 2d animation well? Or is it really just literally drawing every single frame of something in photoshop? Is there tips or tricks? Tutorials to help get started?

Also, what software options are there (preferably open source or even just free)?

# Answer
Right now, I can think of a few ways you can do a 2-D animation:

* Moving an object's x,y coordinates around (e.g. to slide a rectangular menu - you change the y-coordinates every few ms)
* Drawing every single frame out in an image editor and choosing the right frame to draw at the right moment (e.g. drawing a flame animation)
* combining the two above (e.g. having a sprite walk across a screen)

It's all about giving the *illusion* of movement.

How to do it well?

* It has to be timed properly to make it appear smooth (be aware of hardware constraints)
* The more frames you have, the more details you can show, and the better it will look (however you end up having to draw more frames)

Tips and tricks?

Software options?

* I would say it depends on what you are trying to animate. If you want to animate sprites or simple objects, then MS Paint will probably suffice
* GIMP is an open source alternative to Photoshop
* Photoscape is another free photo editor. It also allows you to make animated GIFs - good for testing the timing in your animations
* Synfig Is the libre alternative to ToonBoom for doing animations without taking care about the tweening and then export them to video, gif, or maybe saving some frames as images for the sprites
* InkScape Is a vector vector graphics editor that is the libre alternative to Adobe Illustrator

As for tutorials, I think this depends a lot on your goal. If you are doing a flash game, then search flash tutorials. Drawing is one thing, but you also need to time (and possibly move) the images to animate it properly - and so you might as well learn how to do it in the platform you are going for.
> 19 votes

# Answer
Classical 2D animations are created frame by frame. What you'll see often is that they use a reduced framerate (eg. every frame is displayed twice) to lower the amount of images that have to be drawn.

Flash is a very good tool for 2D animation. It provides you with onion-skinning (previous frames shine through while you're drawing your new frame), tweening and shape-morphing. Since version CS4, it also comes with bones and inverse kinematics which makes animating characters with limbs so much easier.

There's also "Toon Boom". They have a lot of different software-packages available, for hobby/fun up to professional animation software.

Tools like GIMP and Photoshop also provide some functionality for animation but that's really just for very basic stuff.

Another, not so obvious option for 2D animation is using a 3D Program. Did you know that later episodes of Southpark were animated using Maya?

With an orthographic camera projection, proper lighting and flat-shading you can create animations that look 2D, but are created in a 3D software. Most 3D programs have sophisticated animation tools like bones, inverse kinematics, constraints, soft-bodies etc. Blender would be a good (free) choice to get started.
> 10 votes

# Answer
There are plenty of resources available to do this.

Heres a good tutorial to get you started on one particular method using Sprite Sheets. Sprite Sheets are just that, a sheet of sprite that you run in code similar to a flip book animation in real life. But you use code to do it. It can be difficult to get started, but I feel is the most rewarding and grants the most control.

http://www.dreamincode.net/forums/topic/194878-xna-animated-sprite/

Here is the first thing I found using flash which is also a good tool. I personally have not used flash perhaps another poster can chime in with their experience.

http://animation.about.com/od/2danimationtutorials/2D\_Computer\_Animation\_Tutorials\_StepbyStep\_Lessons\_in\_Flash.htm
> 4 votes

# Answer
2D animation is a whole art and profession. And actually a very hard one to master. Not every animator out there does good animation, indeed. But for basic animation as you said... It depends. It's mostly simple to achieve an ok level of sprite animation for mobiles using like 4 frames for a walk cycle 24x24 pixels sprite. You can do that indeed just with Gimp and using layers transparency to have the previous or next frame in overlay as a guide.("onion skinning") .It has other features to help in this.

As you go trying to do higher resolution 2d animation, the thing gets more complex. A fast advice is to draw, in a, for example, 13 frames walk cycle, the frames 1, 7, 13. Then draw ibetweens of those, like 4, 10. Then the remaining ones. (is a bad example, tho)

All this, using onion skinning feature. There are many softwares, I'd advice using Pencil and Gimp. For pixel art, low res sprites, might want to check as well GraphicsGale. And of course, is a lot about checking constantly the flow and animation.
> 4 votes

# Answer
I would recommend you the book "The Animators Survival Kit", it's not directly targeted at 2D animation using computer software but more about general animation techniques (and quite entertaining to read).

Amazon link
> 2 votes

# Answer
Just go for this book with your eyes closed! **The ILLUSION OF LIFE: DISNEY ANIMATION**.

I can't emphasis enough how awesome this book is.I am just quoting form wikipedia.

> The Twelve Basic Principles of Animation is a set of principles of animation introduced by the Disney animators Ollie Johnston and Frank Thomas in their 1981 book The Illusion of Life: Disney Animation. Johnston and Thomas in turn based their book on the work of the leading Disney animators from the 1930s onwards, and their effort to produce more realistic animations. The main purpose of the principles was to produce an illusion of characters adhering to the basic laws of physics, but they also dealt with more abstract issues, such as emotional timing and character appeal.
>
> The book and its principles have become generally adopted, and have been referred to as the "Bible of animation."\[2\] In 1999 the book was voted number one of the "best animation books of all time" in an online poll.\[3\] Though originally intended to apply to traditional, hand-drawn animation, the principles still have great relevance for today's more prevalent computer animation.

For free and open source 2d art application I like MyPaint very much. Painting here feels very natural. Though it lacks a lot basic features. For complimenting basic features there is old friend GIMP.You can even try Krita. Its brush engine is better then Gimp.

For animation + painting there is another solution called Pencil where you can create basic animation with some basic drawing tools. Its very fun to work with.

You can try out Alchemy(painting only) too.
> 1 votes

# Answer
I'd suggest taking what I refer to as a development detour ... something where you take off 3-6 months to dig deep into an adjacent domain, which when you become competent, **really** supports your current thrust of work. for this, I'd highly suggest taking the time to learn 3D Mesh Modeling, specifically Blender. The concepts you'll learn will greatly support your gaming efforts from the primary objects you are looking to create to the effects you seek to create in supporting your game. Blender animations can also be exported as transparent PNG's which can be combined to form sprite sheets (very useful) fairly easily. I think it'd be worth your time.
> 1 votes

# Answer
Climb aboard a brief Google of the name **Sculptris**. You should, in your journey, discover a three-dimensional modeling program of the same name. In my own two-dimensional-sprite-modeling endeavours, I too came to the conclusion that **ProfVersaggi** has. Unfortunately, I dissolved countless frustrated hours letting my brain slither over the program know as **Blender**. I found that I share a need with many others for a more rapid return on my "labors". **Sculptris** gave me this. Also, it's free as of this posting. A caveat; this program is still in development, and does experience crashing. That said, the creators of **Sculptris** were kind enough to implement a crash recovery feature, making the crashes little more than a mild nuisance. Open wide. Drink deep. Swallow no frustration. Digest only **knowledge**. Make us proud. To *summarize*, **Sculptris** is an easy way to create a 3d models for your sprites. Then, you can even press the "prtsc" or "print screen" button to copy an image of whatever is displayed on your screen to be pasted in a 2d animating software like **Graphicsgale** or a paint program like **Paint Shop Pro**. I simply cannot make it any easier for you short of doing it for you lol
> 1 votes

---
Tags: 2d, animation
---


title: Asset workflow for Blender models?

text:
# Question
Title: Asset workflow for Blender models?
As a coder, I don't have much experience in asset creation workflow. I'm trying to figure out the best way to work effectively with Unity + Blender combo. I don't export to FBX, I prefer to work directly with Blender files, with no intermediate export step.

I have parts of the map that I place in the scene: walls, decorations, whole rooms, etc - I keep them in one Blender file. I have models of collectibles, like treasures, keys and the like - I keep them in another Blender file. I have models of characters, which I keep in another one. It has worked OK so far, however I feel like it's not the best way to work. While it makes sense in Blender, it gets messy in Unity.

What is an effective way of working with this combo? Or with asset import in a larger project, in general? Should I export to FBX instead of using Blender files directly? I'd like to understand now how and why to adapt the workflow than have everyone involved being slowed down later.

# Answer
Pros of single model per file:

* Imported nodes contain only what's related to a specific single prefab
* Editor needs to re-import only what has changed, not the whole file

Cons of single model per file:

* Can't easily work with multiple models at the same time
* Can't compare model scale and alignment easily in Blender
* Can't reuse materials or textures easily
* Multiple Blender files will take more space than just a few
> 1 votes

---
Tags: unity, blender, import, asset-workflow
---


title: XNA project won't target .NET 4.0

text:
# Question
Title: XNA project won't target .NET 4.0
I am trying to reference the System.Threading.Task assembly. If I am not mistaken, it should be part of mscorlib. But no matter what I do, my project always defaults to the .net 2.0 runtime. Even if I create a brand new XNA 4.0 Windows Phone project, it wants to use the .net 2.0 runtime. Any ideas what I could be missing?

# Answer
Windows Phone is limited to C# 3.0 and .NET 3.5. You have to use the Task Parallel Library to achieve this.
> 3 votes

---
Tags: xna, xna-4.0, windows-phone-7
---


title: A big light with shadows

text:
# Question
Title: A big light with shadows
To have better texture2D quality in my 2D game, I had to recreate every textures with 300% of their original size. But the lights have to bright 3 times more.

For lights, I'm using this : Catalin's blog

I have to render some lights, but with only 1 with 800 pixels of radius, my game works with around 15fps or less. And if I improve the light quality, I have an issue with the (gpu ?) memory.

How must I do to render a light with 800 pixels of radius without this gpu cost ?
Should I use another effect ? Do you have some to suggest ?
(example : Andrew Russell's game : "Dark" has a lots of big lights, and the game works perfectly)
Hope you can help.

# Answer
As promised, I have written a very long article about **how I optimised the shadow renderer in my game "*Dark*"**.

<sub>(source: andrewrussell.net)</sub>

My article goes into a lot of detail, reaching a whopping 2500 words, plus illustrations, so I won't repost it here. But I will give a quick overview:

There are two major things that I had to optimise, for Dark: First of all, my fill-rate. Each light requires drawing over large areas of the screen. And second of all, the number of batches I was sending to the GPU - as every light must redraw the level geometry in order to cast shadows against it.

The major techniques I used were scissor rectangles, and culling respectively. Although merging static geometry would have been better, for the latter. More interesting, however, is the tricky ways that I made use of these techniques to squeeze out even more performance and get more lights into my levels.

But the he *most vitally* important thing that I describe in my article is the ***measuring*** that I did to assess the performance impact of particular things, determining what measurement constituted the "limit" for that thing, and *then* figuring out how to bring that thing in under that limit.

(Speaking of performance limits, I have an answer over here that lists many of the limits you will come up against when doing graphics programming and game development.)

I really hope that helps :)
> 5 votes

# Answer
Consider doing lighting with much lower resolution images instead of the ones you render in the scene. You can use a 32x32 version of a 128x128 image so long as it properly approximates the shapes in the larger source image. You don't need lighting to match rendered shapes exactly, just approximate it closely enough to look good. Same goes for physics and picking and so on.

You can also render the lighting into a small buffer even and "stretch" (magnify) the lighting texture when you render. It'll cause some artifacts, but very likely (if you pick a good size) it'll look fine.
> 1 votes

---
Tags: xna, c#, lighting, shadows
---


# Question
Title: Difference between "staggered" isometric and "normal" isometric tilemaps?
The Tiled Map Editor v0.9 recently added support for *staggered* tilemaps in addition to its usual isometric tilemap support.

What are the exact technical differences between these two types of isometric tilemaps? What are their advantages/disadvantages?

# Answer
> 61 votes
"Staggered" refers to the jagged edges of isometric maps that have an overall rectangular shape. These maps emphasize the north/south and west/east axes, and often have North up (example: Civilization 2). Diamond maps on the other hand emphasize the diagonal orientation and movement. North is often at the top right (example: Simcity 2000). Also notice the different coordinate systems:

**"Normal" or "diamond" isometric map:**

Notice the overall shape of the map is a diamond.

**"Staggered" isometric map:**

Notice the overal shape of the map is a (rough) rectangle

See also this explanation:

> The math in terms of rendering both types of maps is similar but has its differences. Diamond maps are a bit more tricky particularly in terms of optimizing the render loop.
>
> Diamond maps are typically used in RTS and Tactical Combat types games whereas Staggered/Block maps tend to be used for RPG's and Turn-Based Strategy games.

In terms of the Tiled XML, staggered adds a new possible value for the attribute "orientation" of the map.

Finally, don't confuse these staggered maps with staggered *square* maps. The latter are a way to get pseudo-hexes:

Note how the tiles are squares, but movement and adjacencies conform to those of a hexgrid.

---
Tags: tiles, tilemap, isometric, tiled
---


title: Extending ModelProcessor

text:
# Question
Title: Extending ModelProcessor
How can one extend a model processor inside Windows Forms. In a normal XNA game you would simply create a new class like so(I think...):

```
[ContentProcessor]
public class ExtendedModelProcessor : ModelProcessor
{
    protected override ModelContent Process(NodeContent input,
        ContentProcessorContext context)
    {
        ModelContent m = base.Process(input,context)
        //my own code
    }
}

```

How can I duplicate this inside Windows Forms project, I am working on a project from microsoft site, "WinFormsContentLoading sample". I tried creating a class like above, but didnt work, then I tried to change the processor on `contentBuilder.Add(...,"ExtendedModelProcessor")`. And I also tried creating a new .dll **ContentExtensionLibrary** and then adding it inside `ContentBuilder` class, under:

```
static string[] pipelineAssemblies =
{
    "Microsoft.Xna.Framework.Content.Pipeline.FBXImporter" + xnaVersion,
    "Microsoft.Xna.Framework.Content.Pipeline.XImporter" + xnaVersion,
    "Microsoft.Xna.Framework.Content.Pipeline.TextureImporter" + xnaVersion,
    "Microsoft.Xna.Framework.Content.Pipeline.EffectImporter" + xnaVersion,
    Application.StartupPath + "\\myDll.dll"
};

```

And adding the .dll to the same folder as the program. But nothing worked. How can I create an extension for ModelProcessor inside Windows Forms?

Thanks

# Answer
> 1 votes
Everything you have done so far seems correct. You just need the last step, which is to change the content builder configuration so that it actually uses your processor to build the model.

So open up `MainForm.cs` (right click it and select "View Code") and scroll down to line 100 (in the original sample). Then change this:

```
contentBuilder.Add(fileName, "Model", null, "ModelProcessor");

```

To match the name of your content processor, like this:

```
contentBuilder.Add(fileName, "Model", null, "ExtendedModelProcessor");

```

---

If you get an error message that says:

> Cannot find content processor "ExtendedModelProcessor".

Then you need to fix up the path you specify in `pipelineAssemblies` (in `ContentBuilder.cs`) that points to your DLL. Any other error probably means that there's something wrong with your processor itself.

---

I notice you were trying to do this without creating a DLL at first. You can certainly do that, if you like. You can use your EXE in place of a DLL (they are both assemblies). But you still need to specify its path in the `pipelineAssemblies` array.

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


# Question
Title: Which version of AndEngine (gles1 or gles2) should I learn?
I m new to Game Development. I've chosen AndEngine, but there are 2 versions: gles1 and gles2. I tried sample code from both and found that gles2 code is not run on an emulator, but required an actual device. And in gles2 there are also `BaseGameActivity` and `SimpleBaseGameActivity`. I'm a little confused. Which is best?

# Answer
## USE GLES2

AndEngine is a little tricky to get configured properly the first time you try. I recommend installing the version stored at RealMayo's github, which is a stable version. That's a version of GLES2 and yes, it's definitely worthwhile to use GLES2 over GLES1. Many new features were added that make life easier, improve performance, and add great features to your games and projects. When you're ready to install, follow the instructions at this link and follow them precisely.

GLES2 **WILL** run on an emulator, I do it every day, so if you're having some problem running your app, you need to show us the log output. It might be a memory issue if your computer doesn't have enough memory to run the emulator and install it to the emulator. See this thread.

## BaseGameActivity versus SimpleBaseGameActivity

> The first thing that we have to realize is that BaseGameActivity for GLES2 (the version we are using) and BaseGameActivity for GLES1 are completely different. When AndEngine updated, so did BaseGameActivity, but a lot of people that were using GLES1 didn’t like the changes and wanted to work with a class they were already familiar with. Therefore, SimpleBaseGameActivity was created for GLES2. SimpleBaseGameActivity is practically the same as BaseGameActivity for GLES1, which is what a lot of the AndEngine developers wanted at the time.

(source). My advice (and practice) is to use GLES2 with the BaseGameActivity.
> 6 votes

---
Tags: opengl-es, andengine, opengl-es2
---


# Question
Title: How to share Lua script between instances?
I'm doing an agent based framework with **C++** and **Lua**. I want to use **Lua** to code the Agent behaviour having an `AgentClass` class that have the name and source code and an `AgentInstance` class that have the lua\_State. I want to have a few `AgentClass` instances during execution but hundreds or thousands of `AgentInstance` objects.

Is there any way to share the same lua script with different `lua_State`? Or Is there a better way to get hundreds of agents without too much performance penalty?

¿Options?:

* Having compiled **Lua** code in `AgentClass`.
* Having `lua_State` only on `AgentClass`, setting a *self* variable in every `AgentInstance` update.
* Other.

# Answer
I have compile the lua code in the AgentClass object, and in the AgentInstance code I call funcions passing this pointer like:

```
lua_getfield( L, LUA_GLOBALSINDEX, SCRIPT_AGENT_NAME );
lua_getfield( L, -1, "init");
lua_getfield( L, LUA_GLOBALSINDEX, "Agent" );
lua_pushstring( L, "__obj" );
lua_pushlightuserdata( L, (void*)this );
lua_rawset( L, -3 );
auto ret = lua_pcall( L, 1, 0, 0 );

```
> 3 votes

# Answer
You only need a single lua\_State for your game, so long as your scripts aren't making questionable changes to the standard tables. (If you are installing random scripts off the 'Net or something, you need tighter sandboxing; if you aren't, trust your devs to not be stupid.)

If you want globals to be stored per-entity, you can modify the metatable (or envionment, if using recent Lua) so calls to \__index and \__newindex map to a per-entity table, with fallbacks to the original shared global table for \__index.

There are examples of this on the Lua Users' site last I checked, as well as a lot of code on the mailing list about the best way to do this.

Having multple Lua states wastes a lot of memory and slows things down because each agent access completely different sets of Lua memory blocks which is CPU cache unfriendly.
> 2 votes

---
Tags: entity-system, lua
---


# Question
Title: CPU Usage on the UI thread Warning - XNA WP7.1
When I run the Store Test Kit's profiler against my game, I get a warning that says something along the likes of "Very high CPU usage on the UI thread for operations other than frame drawing."

According to the library I am using, I am still getting around 59-61 fps when I test it on a WP8, WP7.8, and a first gen WP7.5 device.

Should I be concerned? If I were to use Tasks or Parallel, does it throw it off to another thread? Or is this simply just a matter of optimizing my code.

# Answer
> 2 votes
It's something you should look into. There's an article on MSDN about this warning. Essentitally, it's a matter of optimizing you code, but it's important to profile the code so you know *what* to optimize. These are the steps listed in the article:

> To investigate high CPU usage on the UI thread
>
> 1. To investigate a high CPU usage warning, click the arrow next to Performance Warnings and then click Frames and then Functions in the menu. The Functions view will be displayed. The Functions view shows every method that was called during the selected part of the timeline. These can be methods in platform code or app code.
> 2. Click the Inclusive Samples column header until the functions are sorted by these values in descending order (highest to lowest).
> 3. Look for methods that are part of your app code on the top of the list. One or more the apps methods will likely be up at the top of the highly-sampled functions. This could, meaning you may be calling the method very often, or the method might be inefficient or take a long time to successfully execute. Either way, it is causing a UI block that is leading to a problem with the app’s responsiveness.
> 4. Optimize the code for that method or move it to non-UI thread.

---
Tags: xna, xna-4.0, windows-phone-7
---


# Question
Title: How to implement A.I. for checkers/draughts?
I saw this checkers game and I wondered how the A.I. was implemented.

How should I implement an A.I. for checkers (draughts, dama, dame)? Are there any known algorithms?

---

Very thnaks full to all. I m very wonder to see this Tic Tac Toe game tutorial blog post.

So, i want dama game algorithm open source code and blog post.. Is there any helpful link or any doc file..? please let me know..

# Answer
> 27 votes
Oh I do love these games!

So first things first, in order for a computer to play a game, it needs:

1. a structure to work with
2. rules to play by
3. a win condition to work towards

Let's tackle this one piece at a time.

---

## Structure

Since the board is an 8x8 grid (but could easily scale), and each grid space may exist in only one of five states, let's define those states:

```
[EMPTY, WHITE_PIECE, BLACK_PIECE, WHITE_PIECE_PROMOTED, BLACK_PIECE_PROMOTED]

```

Respectively ENUM'd to:

```
[0, 1, 2, 3, 4]

```

Now that we know what each space can be we need some way to represent all the spaces, or the board if you will. Almost every strong language will support a multi-dimensional array (an array where each element is an array holding data). So take the following slack-code for defining our array:

```
BOARD_ARRAY = array(8, 8)

```

This will give us an 8 x 8 array in which we can store integers (our enums from before):

```
(
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
)

```

Now you can already see how that this is beginning to look like a board! I've never played the variant mentioned in the youtube video but it appears to start with 2 rows of white pieces one row from the bottom, and 2 rows of black pieces one row from the top. Which would mean when we start a game our array should look like this:

```
(
[0, 0, 0, 0, 0, 0, 0, 0],
[2, 2, 2, 2, 2, 2, 2, 2],
[2, 2, 2, 2, 2, 2, 2, 2],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0],
)

```

(Remember 2 represents 'BLACK\_PIECE' and 1 represents 'WHITE\_PIECE')

So now the computer has a structure to work with. Step 1 complete!

---

## Rules

Let's imagine you had an actual board set up in front of you, playing against a master player. If you tried to move one of his pieces, you'd get your hand slapped. If you tried to move a piece in a way you couldn't, you'd get your hand slapped. If you tried to cheat well... you get the idea. But the problem is, computers don't. So it's our job to provide **strict** rules to play within.

We need to create a way to check if any given move is 'legal'. Which means we first need some way to represent a 'move'. One way would be to use array positions; For example to move a piece from \[0, 0\] to \[0, 1\], we could create a function that will update the board given that move. So back to slack:

```
MY_MOVE = array( [0, 0], [0, 1] )

```

The above represents one piece, moving one space down from the top corner of the board (assuming 0, 0 is the top left corner). You may also notice I chose to use a multidimensional array for the move. This is because pieces may theoretically move a great number of times in one turn (for 'jumping' other pieces). So let's pretend at 0, 1 there was an opponents piece, meaning we would land at 0, 2:

```
MY_MOVE = array( [0, 0], [0, 2] )

```

Pretty simple eh. The program should understand that if we skip a space we are jumping another piece (or else it's an illegal move, and should throw an error). Now let's jump two pieces:

```
MY_MOVE = array ( [0, 0], [0, 2], [0, 4] )

```

This gives us a way to describe any move on the board. Yay! Now since I don't fully understand the rules of the exact game in question (although I've played a bit of Canadian checkers in my day) the exact move legality will need to be defined by you. A good flow up to this point would look like:

```
FUNCTION_FIND_ALL_LEGAL_MOVES( MY_BOARD ) Returns: array ALL_LEGAL_MOVES
FUNCTION_FIND_BEST_MOVE( MY_BOARD, ALL_LEGAL_MOVES ) Returns: array MY_MOVE
FUNCTION_DO_MOVE( MY_BOARD, MY_MOVE ) Throws: error ILLEGAL_MOVE Updates: MY_BOARD
repeat from start for each turn

```

The above assumes you can cycle through each piece to find all it's legal moves, then given a collection of all the legal moves somehow choose the best one (strategy here). The move is then applied to the board, or throws an error. Then the next player takes their turn. So we have an AI that knows how to play! Joy! Moving on.

---

## Winning

Simple games are wonderful, because winning is defined by a very simple state. Ain't no white pieces on the board? Well I guess you've won! This is implemented in step 2 when we choose the best move to take us closer to the winning condition.

To make some very intelligent AI you could keep a database that stored every possible board as a state, with every possible move from every possible state, to find chains towards winning.

You could also create strategies, like: if there is a piece that WILL be jumped, save that piece or if a piece is able to jump more than one other piece do that jump.

---

That should give you a good jumping off point, it is only one method of literally unlimited possibilities. You could theoretically build a giant robot to draw with crayons then conduct spectral analysis on the drawing to choose moves... but it wouldn't work very good, or fast. This way has worked in the past, and worked well (: Hope that helps!

---

## A Few Words On Implementation

Checkers is what is referred to as a 'solved' game, in that we can calculate every move with no unknowns. But that's a whole whack of moves! So there is no way to do it all manually... if only there was some... oh right we're programmers. *fist pump*

SQL is a wonderful tool for storing all these seemingly endless moves. For those with no experience with SQL, mySQL is a free (fairly easy to use) and open source SQL server. SQL is used for managing databases, sorta like a spreadsheet on steroids. It is also able to hold seriously large amounts of data and work with it very quickly.

So how can we use this? Since we know that if the board is in an exact state (each piece in a certain position) we can calculate all the available moves, and save them. For example:

```
+Board State+          +All Possible Moves+               +Best Move+
([0,0,1,2,3],[3..)     ([0,1],[0,2]), ([7,6],[7,7],[5..)  ([7,6],[7,7])
([0,0,2,2,3],[3..)     ([0,1],[0,2]), ([7,6],[7,7],[5..)  ([5,5],[5,4])
([0,0,1,3,3],[3..)     ([0,1],[0,2]), ([7,6],[7,7],[5..)  ([4,4],[4,3])
etc...

```

So when the computer needs to make a move it simply looks up the board state (stored as the primary key) in the database, and can either choose the best move (should be unbeatable) or one of the other moves to make a more friendly AI.

Great now let's build this database. First we need to calculate every board state. Which can be done with a great big nasty loop, if someone wants to spend some time and work it out that would be awesome. Look at the array as one big number, then count upwards, except in base 5 (0, 1, 2, 3, 4), and condition that each player may only have 16 pieces.

At this point we should have every board state stored and can go through calculating all possible moves.

Once all possible moves are calculated comes the fun part of pathfinding the best possible moves. This is where my knowledge begins to fall short, and things like Minimax or A\* start to come into play. Sorry I can't be of more help on that :/

# Answer
> 30 votes
At any point in the game the amount of possible moves for a player is quite low\* (around 5) this means that thinking a few moves ahead, evaluating every possible move and selecting the best move is doable.

This approach is called minimax (wikipedia).

To implement minimax you'll need a evaluation function that returns a score for a given board layout and player. For draughts a naive implementation would be a function that returns one point for every piece the player has alive.

A visualisation of a minimax decision tree (from the wikipedia article). Down the left hand side is the turn number. The leaf nodes each have an evaluated score which is fed back up the tree to make a decision.

`*` however draughts is the game with the highest branching factor that has been completely solved.

# Answer
> 5 votes
Alpha–beta pruning is a search algorithm that seeks to decrease the number of nodes that are evaluated by the minimax algorithm in its search tree. It is an adversarial search algorithm used commonly for machine playing of two-player games (Tic-tac-toe, Chess, Go, etc.). It stops completely evaluating a move when at least one possibility has been found that proves the move to be worse than a previously examined move. Such moves need not be evaluated further. When applied to a standard minimax tree, it returns the same move as minimax would, but prunes away branches that cannot possibly influence the final decision.

---
Tags: algorithm, ai
---


title: Quaternion handedness issue

text:
# Question
Title: Quaternion handedness issue
At least I think it is. I have the following functions:

* kmQuaternionRotationAxis - Constructs a Quaternion from an axis and angle
* kmMat4RotationQuaternion - Constructs a 4x4 matrix from a quaternion
* kmMat4RotationAxisAngle - Constructs a 4x4 matrix from an axis and angle

My problem is, when I run the following code:

```
kmQuaternion q;
kmMat4 initialized;
kmMat4 quaternion_rotated;

kmQuaternionRotationAxis(&q, &KM_VEC3_POS_Z, kmDegreesToRadians(90));
kmMat4RotationAxisAngle(&initialized, &KM_VEC3_POS_Z, kmDegreesToRadians(90));

kmMat4RotationQuaternion(&quaternion_rotated, &q);

```

I would expect \*quaternion\_rotated\* to match *initialized*, but they don't.

Initialized:

```
 | 0 -1  0  0 |
 | 1  0  0  0 |
 | 0  0  1  0 |
 | 0  0  0  1 |

```

quaternion\_rotated:

```
 | 0  1  0  0 |
 | -1 0  0  0 |
 | 0  0  1  0 |
 | 0  0  0  1 |

```

The contents of initialized looks like I would expect, but I can't figure out how quaternion\_rotated is wrong. I've included all the code below, where is my conversion code wrong?

```
kmQuaternion* kmQuaternionRotationAxis(kmQuaternion* pOut, const kmVec3* pV, kmScalar angle)
{
    kmScalar rad = angle * 0.5f;
    kmScalar scale  = sinf(rad);

    pOut->w = cosf(rad);
    pOut->x = pV->x * scale;
    pOut->y = pV->y * scale;
    pOut->z = pV->z * scale;

    kmQuaternionNormalize(pOut, pOut);

    return pOut;
}

kmMat4* kmMat4RotationAxisAngle(kmMat4* pOut, const kmVec3* axis, kmScalar radians)
{
    kmScalar rcos = cosf(radians);
    kmScalar rsin = sinf(radians);

    kmVec3 normalizedAxis;
    kmVec3Normalize(&normalizedAxis, axis);

    pOut->mat[0] = rcos + normalizedAxis.x * normalizedAxis.x * (1 - rcos);
    pOut->mat[1] = normalizedAxis.z * rsin + normalizedAxis.y * normalizedAxis.x * (1 - rcos);
    pOut->mat[2] = -normalizedAxis.y * rsin + normalizedAxis.z * normalizedAxis.x * (1 - rcos);
    pOut->mat[3] = 0.0f;

    pOut->mat[4] = -normalizedAxis.z * rsin + normalizedAxis.x * normalizedAxis.y * (1 - rcos);
    pOut->mat[5] = rcos + normalizedAxis.y * normalizedAxis.y * (1 - rcos);
    pOut->mat[6] = normalizedAxis.x * rsin + normalizedAxis.z * normalizedAxis.y * (1 - rcos);
    pOut->mat[7] = 0.0f;

    pOut->mat[8] = normalizedAxis.y * rsin + normalizedAxis.x * normalizedAxis.z * (1 - rcos);
    pOut->mat[9] = -normalizedAxis.x * rsin + normalizedAxis.y * normalizedAxis.z * (1 - rcos);
    pOut->mat[10] = rcos + normalizedAxis.z * normalizedAxis.z * (1 - rcos);
    pOut->mat[11] = 0.0f;

    pOut->mat[12] = 0.0f;
    pOut->mat[13] = 0.0f;
    pOut->mat[14] = 0.0f;
    pOut->mat[15] = 1.0f;

    return pOut;
}

kmMat4* kmMat4RotationQuaternion(kmMat4* pOut, const kmQuaternion* pQ)
{
    double xx = pQ->x * pQ->x;
    double xy = pQ->x * pQ->y;
    double xz = pQ->x * pQ->z;
    double xw = pQ->x * pQ->w;

    double yy = pQ->y * pQ->y;
    double yz = pQ->y * pQ->z;
    double yw = pQ->y * pQ->w;

    double zz = pQ->z * pQ->z;
    double zw = pQ->z * pQ->w;

    pOut->mat[0] = 1 - 2 * (yy + zz);
    pOut->mat[1] = 2 * (xy - zw);
    pOut->mat[2] = 2 * (xz + yw);
    pOut->mat[3] = 0;

    pOut->mat[4] = 2 * (xy + zw);
    pOut->mat[5] = 1 - 2 * (xx + zz);
    pOut->mat[6] = 2 * (yz - xw);
    pOut->mat[7] = 0.0;

    pOut->mat[8] = 2 * (xz - yw);
    pOut->mat[9] = 2 * (yz + xw);
    pOut->mat[10] = 1 - 2 * (xx + yy);
    pOut->mat[11] = 0.0;

    pOut->mat[12] = 0.0;
    pOut->mat[13] = 0.0;
    pOut->mat[14] = 0.0;
    pOut->mat[15] = 1.0;

    return pOut;
}

```

# Answer
> 1 votes
Your problem is that you didn't implement `kmMat4RotationAxisAngle` like this:

```
kmMat4* kmMat4RotationAxisAngle(kmMat4* pOut, const kmVec3* axis, kmScalar radians)
{
  kmQuaternion quat;
  kmQuaternionRotationAxis(&quat, axis, radians);
  kmMat4RotationQuaternion(pOut, &quat);
  return pOut;
}

```

That sounds flippant, but the best way to make sure two pieces of code stay in sync is to implement one in terms of the other.

That being said, your main problem is that you transposed your quaternion to matrix logic. Here's the proper matrix for that; your version puts the rows in the columns.

Yet another reason to not reinvent the wheel and use someone else's matrix library.

---
Tags: quaternion
---


# Question
Title: Blender - baking normal map - weird colors
I have a metal drum mesh, and when I bake its normal map, I get the weird colors (see attached pic). I'm talking about the horizontal gradient shift of color. There's no deformation like that on my mesh, how come the colors are like that? I've tried various spaces (camera, world, etc) but it's still bad (though the horizonal gradient changes with each one). Also tangent space returns a blocky blue color all over.

Can someone please tell me how to get a good normal map out of my mesh?

=== UPDATE

Solved, thank you very much Luke B. There's still the question of scaling one of the two overlapping versions a bit (the low res one for example) in order to get really good results, but that's how it's supposed to be done.

=== UPDATE 2

After further following the advices of Luke B, I've used multiresolution modifier on my low-res mesh, and baked from there. It looks much better than before, the color artifacting are down to a minimum, really, with some corrections in GIMP it's quite usable:

# Answer
I am assuming your intention is to use this normal map in a game, as it was explained in other comments, you most likely don't want world space normals since they only work for a fixed world. Your problem with tangent normal baking is that you don't have a mesh with less detail to bake the map to. This is how you do it:

1 - Create a lower-res version of your cilinder:

2 - Align both meshs:

2a - Remember to uv unwrap your lower-res mesh and create a texture for it.

3 - Select both meshs and make sure the lower-res is the active one (the higher-res should be dark-orange), in the bake panel select the option "Selected to Active" and use Tangent as the normal space:

Is that the result you were expecting?
> 10 votes

# Answer
To sucessfuly bake a normal-map you need to make sure of 2 or 3 things.

* Make sure that your mesh is manifold. (E.g. that there are no double-sided faces.) You can check that in edit-mode by pressing Ctrl+Shift+Alt+M, this will select all non-manifold edges.
* Make sure to select "Tangent" for Normal Space in the Bake Panel. This is the method usually used in video-games. There are other Normal Spaces and normal maps in that spaces look different.
* Make sure that the normals face into the correct direction, for manifold meshes you can let them recalculate by pressing Ctrl+N. You can let the normals displayed in the "Mesh Display" panel in the properties thingy (which can be toggled by N). If Ctrl+N calculates wrong normals than there is something seriously broken in your mesh.
> 5 votes

---
Tags: blender, normal-mapping
---


title: Pixelated Normal Generation

text:
# Question
Title: Pixelated Normal Generation
I am generating normals for each vertex in a standard 512\*512 quad. Yet when I do using the following code:

```
public Vector3f[] normals(Vector3f[] surface){
Vector3f[] normals = new Vector3f[surface.length];
for(int i = 0; i<normals.length; i+=4){

    Vector3f n1 = surface[i];
    Vector3f n2 = surface[i+1];
    Vector3f n3 = surface[i+2];
    Vector3f n4 = surface[i+3];

    Vector3f p1 = n1.subtract(n2);
    Vector3f p2 = n3.subtract(n2);
    Vector3f p3 = n3.subtract(n4);
    Vector3f p4 = n1.subtract(n4);

    Vector3f norm1 = (p2.cross(p1)).normalize();
    Vector3f norm2 = (p4.cross(p3)).normalize();
    normals[i] = (norm1.add(norm2)).divide(2);
    normals[i+1] = norm1;
    normals[i+2] = (norm1.add(norm2)).divide(2);
    normals[i+3] = norm2;

    }
    return normals;
}

```

I get the following from this:

Any ideas what is causing this? Thanks in advance.

# Answer
It seems that you are calculating p4 incorrectly. Should it not be n2.subtract(n4)? Also it looks like you should swap the assignment for normals\[i\] and normals\[i+1\]

This is of course assuming that you have these vertices laid out in a triangle strip fashion and that the 2 triangles that are part of this quad are not necessarily coplanar.

The other thing that bothers me is that you are not taking into account the shared vertices for adjacent edges on the quads. Essentially you should be taking an average of the 4 normals for the 4 planar surfaces that surround each point(the inner points at least... edge points obviously have less surfaces surrounding them). That way after you do the lighting calculations the edges wont appear as sharp lines.
> 2 votes

---
Tags: vertex, normals, normal-generation
---


# Question
Title: Creating a frustum for culling in world-space glm matrices
I need to do frustum culling where the bounding boxes are in world-space to determine which entities get to be updated/drawn. I was trying to use the classic projection/view matrix plane extraction method but it doesn't seem to work with perspective matrices created by GLM. Is this method appropriate for world-space culling? It seems like it would be (takes the eye position into account and the projection matrix shapes the frustum).

I've only looked at the near/far planes extract so far and they're wrong for a frustum sitting at the origin (Both have a c component that's negative which means near and far are facing the same direction). Also, since the d components can't match the near/far clipping values with this method is it wrong for world-space culling?

# Answer
Figured out the problem - GLM's interface for accessing the matrix is backwards compared to the matrix used by the original frustum extraction paper for OpenGL.
> 1 votes

---
Tags: opengl, mathematics, culling, frustum
---


# Question
Title: How to use the box2d contact listener in android (java port)?
I don't have any idea about the box2d collision detection in android. I googled and got results that suggest to use the contact listener but I don't know how to use it in android java.

# Answer
If you're using JBox2D, you can use

```
org.jbox2d.dynamics.World.setContactListener(new ContactListener() {
    ...
});

```
> 3 votes

# Answer
OMG! that was the best help I've found! Thankyou Skyuzo. This code works for JBox2D (I haven't tried Android however, but Android would be using JBox2D instead of the C++ Box2D)

Inside the ContactListener, this code must be placed handling the contacts: *Note* This code should only be initialized once.

```
world.setContactListener(new ContactListener() {

            @Override
        public void beginContact(Contact contact) {
            System.out.println("Contact detected");
        }

        @Override
        public void endContact(Contact contact) {
            System.out.println("Contact removed");
        }

        @Override
        public void postSolve(Contact arg0, ContactImpulse arg1) {
            // TODO Auto-generated method stub
        }

        @Override
        public void preSolve(Contact arg0, Manifold arg1) {
            // TODO Auto-generated method stub
        }
    });

```
> 1 votes

---
Tags: android, java, box2d
---


title: Help on TileMapRenderer

text:
# Question
Title: Help on TileMapRenderer
In my project, I'm trying to render a map using TileMapRenderer. But it doesn't show anything when I render it. But when I use some other files from a tutorial they are rendered correctly.

When debugging my TileAtlas instance shows the size as 0.

I have used Texture Packer UI for packing the images. Comparing with the tutorial's files, I can see that the index starts from 1 in my file and 0 in the tutorial. But changing it to 0 wouldn't work also.

```
map.png
format: RGBA8888
filter: Nearest,Nearest
repeat: none
Map
  rotate: false
  xy: 0, 0
  size: 32, 32
  orig: 32, 32
  offset: 0, 0
  index: 1
Map
  rotate: false
  xy: 32, 0
  size: 32, 32
  orig: 32, 32
  offset: 0, 0
  index: 2
Map
  rotate: false
  xy: 64, 0
  size: 32, 32
  orig: 32, 32
  offset: 0, 0
  index: 3
Map
  rotate: false
  xy: 96, 0
  size: 32, 32
  orig: 32, 32
  offset: 0, 0
  index: 4
Map
  rotate: false
  xy: 128, 0
  size: 32, 32
  orig: 32, 32
  offset: 0, 0
  index: 5

```

Here is the begining of the tmx file.

```
<?xml version="1.0" encoding="UTF-8"?>
<map version="1.0" orientation="orthogonal" width="20" height="20" tilewidth="32" tileheight="32">
 <tileset firstgid="1" name="a" tilewidth="32" tileheight="32">
  <image source="map.png" width="256" height="32"/>
 </tileset>
 <layer name="Tile Layer 1" width="20" height="20">
  <data>
   <tile gid="2"/>
   <tile gid="2"/>

```

Apart from that the tutorial files and my files seems to be similar.

Can anyone help me here.

# Answer
> 1 votes
I think you need to use the **TiledMapPacker *(com.badlogic.gdx.tiledmappacker.TiledMapPacker from gdx-tiled-preprocessor.jar)***, and **NOT the Texture Packer GUI**.

Usage:

```
libgdx/dist$ java -classpath ./gdx.jar:
        ./extensions/gdx-tools/gdx-tools.jar:
        ./extensions/gdx-tiled-preprocessor/gdx-tiled-preprocessor.jar
    com.badlogic.gdx.tiledmappacker.TiledMapPacker
    ~/artifacts/input/
    ~/artifacts/output/
    --strip-unused

```

TiledMapPacker builds a **packfile** where as Texture Packer GUI builds a **.pack** file.

checkout this article that explains about packing (http://code.google.com/p/libgdx-users/wiki/Tiles#Packing). Make sure you have cross checked all the points he mentions, under the above section.

---
Tags: libgdx
---


# Question
Title: Trying to run sample AndEngine gles2 code in the simulator throws "java.lang.IllegalArgumentException: No EGLConfig found!", how can I fix this?
I tried to run a small sample game code in the emulator but it crashed. My LogCat is given here. Can you help me resolve the issue.

```
02-23 15:18:50.543: D/AndEngine(636): MainActivity.onCreate @(Thread: 'main')
02-23 15:18:50.633: D/dalvikvm(636): Trying to load lib /data/data/com.example.gamegles2demo/lib/libandengine.so 0x40513d70
02-23 15:18:50.633: D/dalvikvm(636): Added shared lib /data/data/com.example.gamegles2demo/lib/libandengine.so 0x40513d70
02-23 15:18:50.633: D/dalvikvm(636): No JNI_OnLoad found in /data/data/com.example.gamegles2demo/lib/libandengine.so 0x40513d70, skipping init
02-23 15:18:50.903: D/AndEngine(636): MainActivity.onResume @(Thread: 'main')
02-23 15:18:50.953: D/AndEngine(636): MainActivity.onPause @(Thread: 'main')
02-23 15:18:50.953: D/AndEngine(636): MainActivity.onDestroy @(Thread: 'main')
02-23 15:18:50.983: D/AndEngine(636): UpdateThread interrupted. Don't worry - this EngineDestroyedException is most likely expected!
02-23 15:18:50.983: D/AndEngine(636): org.andengine.engine.Engine$EngineDestroyedException
02-23 15:18:50.983: D/AndEngine(636):   at org.andengine.engine.Engine.throwOnDestroyed(Engine.java:574)
02-23 15:18:50.983: D/AndEngine(636):   at org.andengine.engine.Engine.onTickUpdate(Engine.java:560)
02-23 15:18:50.983: D/AndEngine(636):   at org.andengine.engine.Engine$UpdateThread.run(Engine.java:820)
02-23 15:18:50.983: D/AndEngine(636): MainActivity.onDestroyResources @(Thread: 'main')
02-23 15:18:50.994: D/AndEngine(636): MainActivity.onGameDestroyed @(Thread: 'main')
02-23 15:18:51.073: D/AndEngine(636): MainActivity.onCreate @(Thread: 'main')
02-23 15:18:51.093: D/AndEngine(636): MainActivity.onResume @(Thread: 'main')
02-23 15:18:51.643: D/libEGL(636): egl.cfg not found, using default config
02-23 15:18:51.653: D/libEGL(636): loaded /system/lib/egl/libGLES_android.so
02-23 15:18:51.803: W/dalvikvm(636): threadid=10: thread exiting with uncaught
exception (group=0x40015560)
02-23 15:18:51.803: E/AndroidRuntime(636): FATAL EXCEPTION: GLThread 13
02-23 15:18:51.803: E/AndroidRuntime(636): java.lang.IllegalArgumentException: No EGLConfig found!
02-23 15:18:51.803: E/AndroidRuntime(636):  at org.andengine.opengl.view.ConfigChooser.chooseConfig(ConfigChooser.java:183)
02-23 15:18:51.803: E/AndroidRuntime(636):  at org.andengine.opengl.view.ConfigChooser.chooseConfig(ConfigChooser.java:157)
02-23 15:18:51.803: E/AndroidRuntime(636):  at android.opengl.GLSurfaceView$EglHelper.start(GLSurfaceView.java:919)
02-23 15:18:51.803: E/AndroidRuntime(636):  at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1264)
02-23 15:18:51.803: E/AndroidRuntime(636):  at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1118)
02-23 15:18:52.294: D/AndEngine(636): MainActivity.onPause @(Thread: 'main')
02-23 15:18:54.404: D/AndEngine(636): MainActivity.onDestroy @(Thread: 'main')
02-23 15:18:54.464: D/AndEngine(636): UpdateThread interrupted. Don't worry - this EngineDestroyedException is most likely expected!
02-23 15:18:54.464: D/AndEngine(636): org.andengine.engine.Engine$EngineDestroyedException
02-23 15:18:54.464: D/AndEngine(636):   at org.andengine.engine.Engine.throwOnDestroyed(Engine.java:574)
02-23 15:18:54.464: D/AndEngine(636):   at org.andengine.engine.Engine.onTickUpdate(Engine.java:560)
02-23 15:18:54.464: D/AndEngine(636):   at org.andengine.engine.Engine$UpdateThread.run(Engine.java:820)
02-23 15:18:54.494: D/AndEngine(636): MainActivity.onDestroyResources @(Thread: 'main')
02-23 15:18:54.494: D/AndEngine(636): MainActivity.onGameDestroyed @(Thread: 'main')

```

# Answer
> 4 votes
It's not going to be easy. I don't know much about AndEngine, but I've developed some GLES 2 apps, and it is possible to run and test them inside an AVD (in the Android world, "Virtual Device", or AVD is the correct term, not "emulator").

Looking at the logcat, I can see that there is a first exception:

```
02-23 15:18:50.983: D/AndEngine(636): org.andengine.engine.Engine$EngineDestroyedException

```

However, not only the program seems to continue running, but also the previous line says

> UpdateThread interrupted. Don't worry - this EngineDestroyedException is most likely expected!

So the problem is not there. After a few lines you see the real error:

```
02-23 15:18:51.803: E/AndroidRuntime(636): java.lang.IllegalArgumentException: No EGLConfig found!

```

Searching google for this error led me here. The main problem is clearly stated in that thread:

> The emulator only allows GLES 1 as far as i know.

That is not strictly true, but for AndEngine it probably is.

The problem with GLES 2 and AVDs is that the programmable pipeline of GLES 2 requires a GPU, and the graphics acceleration support in AVDs is disabled by default, and support for it is at best experimental:

> Caution: As of SDK Tools Revision 17, the graphics acceleration feature for the emulator is experimental; be alert for incompatibilities and errors when using this feature.

So the first thing you can try is to create an AVD with the latest firmware you can find. Unfortunately, even though this *may* work, the game will probably be running reeeeally slow. The reason behind this is that the main platform for Android development is ARM, and with almost complete certainty, your development workstation is based on x86 or x86\_64, both of which are extremely different from ARM.

So what the AVD framework does is emulate an ARM CPU and some unknown GPU. Even my Core i7-3770 Ivy Bridge is not up to the task of doing that in real time.

But fear not! Android is by itself multiplatform. You can create an AVD using an x86 image (look for it in the SDK manager), and enable virtualization on your computer's CPU so the AVD runs on the actual CPU without the need for emulation. The key to enabling CPU virtualization for AVDs is called HAXM (look for it in the Android SDK manager, but make sure you install it manually. The SDK manager only downloads it for you, but you have to install it yourself)

The best thing about HAXM is that it also allows for GPU virtualization, which means that GLES 2 will run at full speed in your AVD, which greatly simplifies development and testing.

There are two limitations with x86 AVDs with HAXM though:

1. HAXM is a technology developed by Intel. This will most likely not work on AMD CPUs, but I haven't tested that myself.
2. Even though the Android OS is multiplatform by itself, and Java is meant to be multiplatform, code built with the NDK is meant to target a single platform. In general this means that if your code is in Java (or in Mono), you will have no problems making and running it in your accelerated x86 AVD.

However, if you use the NDK, you have to build your native code for x86 as well. Most library developers don't do that out of laziness, and because of that, their code won't run on any x86 devices like the x86 AVD, but also on the increasingly available x86 Android phones like those from Dell, Motorola and Lenovo.

The bad news is that AndEngine seems to use the NDK. I'm saying that because the logcat you provide shows the OS attempting to load a library called `libandengine.so`. The `.so` extension is almost exclusively used by NDK modules.

I peeked at the AndEngine code, and it seems that the native stuff they do is quite minimal, so it will likely cleanly build for x86. But unless x86 is a supported platform, the stock AndEngine will not run on HAXM.

---
Tags: opengl-es, andengine, opengl-es2
---


title: Rotate Body From Corner

text:
# Question
Title: Rotate Body From Corner
I want to ask that how to rotate body from corner?

```
movableBeam.getBeamBody().setTransform(movableBeam.getBeamBody().getPosition(), angle);

```

The above line of code rotate the beam from center that I want rotate from one of the conner. Any member please help me.

EDIT :

```
            float beamCenterX = movableBeam.getX() + movableBeam.getWidth()
                    / 2f;
            float beamCenterY = movableBeam.getY()
                    + movableBeam.getHeight() / 2f;

            float cornerOffsetX = movableBeam.getX() - beamCenterX;
            float cornerOffsetY = movableBeam.getY() - beamCenterY;

            float bodyAngle = (float) Math.atan2(cornerOffsetY,
                    cornerOffsetX);

            float newAngle = imageAngle + bodyAngle;
            float newCornerOffsetX = (float) Math.cos(Math
                    .toDegrees(newAngle));
            float newCornerOffsetY = (float) Math.sin(Math
                    .toDegrees(newAngle));

            cornerOffsetX = movableBeam.getX() - movableBeam.getWidth()
                    / 2f;
            cornerOffsetY = movableBeam.getY() - movableBeam.getHeight()
                    / 2f;

            Vector2 postion = new Vector2(
                    (newCornerOffsetX - cornerOffsetX + movableBeam.getX())
                            / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT,
                    (newCornerOffsetY - cornerOffsetY + movableBeam.getY())
                            / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT);

            movableBeam.getBeamBody().setTransform(postion, newAngle);

```

# Answer
When we rotate a object in 2d, each corner is a vector (x,y) away from the center. That vector has an angle.

Get the offset of the selected corner from the center:

```
cornerOffset.x =  corner.x - center.x;
cornerOffset.y =  corner.y - center.y;

```

To calculate this angle we do something like this in AS3 / Java

```
angle = Math.Atan2(corner.y - center.y, corner.x - center.x); //you can use the previously calculated values

```

It's length

```
length = Math.sqrt((corner.x - center.x)^2 + (corner.y - center.y)^2); //same

```

Sometime, if the object is rectangular, the corner will probably be at:

```
cornerOffset = center.x (+/-) width/2.0, corner.y (+/-) height

```

After rotating the object from the center by (B) degrees, the vector for the offset has been rotated as well.

So the new corner position will be:

```
newAngle = angle + B;
newCornerOffset.x = length * Math.cos(newAngle);
newCornerOffset.y = length * Math.sin(newAngle);

objectOffset.x = cornerOffset.x - newCornerOffset.x;
objectOffset.y = cornerOffset.y - newCornerOffset.y;

```

Now give the object sufficient speed to get it back to where you want it.

```
Speed = objectOffset / deltaTime ..

```

In your specific case the object is (168px wide, 14px tall) so the original offset would be `(84, 7)`

Each frame you need to check the current angle and know the next angle.

Then calculate :

```
cornerOffset.x = length * Math.cos(currentAngle);
cornerOffset.x = length * Math.sin(currentAngle);

newAngle = currentAngle + angleChange; //angle change for this frame
newCornerOffset.x = length * Math.cos(newAngle);
newCornerOffset.y = length * Math.sin(newAngle);

moveObject(currentCornerOffset.x - newCornerOffset.x, currentCornerOffset.y - newCornerOffset.y);

```
> 9 votes

# Answer
By default the body was rotated from center but you can change that point following way.

```
PolygonShape shape = new PolygonShape();
shape.setAsBox(width, height, new Vector2(0f, height / 2f), angle);

```

In this manner you can create body that rotate from the corner not the center.
> 0 votes

# Answer
you can rotate the body from corner by just making a body from where you want to rotate and set the density 1000 and above depends on body weight . and after that you can use body.setTransform(new Vector2(x,y), MathUtil.degToRad(Sprite.getRotation()).
> -1 votes

---
Tags: box2d, andengine
---


title: Slick2D ingoring aplha channel?

text:
# Question
Title: Slick2D ingoring aplha channel?
When I use the draw method inside a image, it completely ingores the alpha channel and fills it in with white. Is there a way I can draw it where the alpha is see through like it's suppost to be? I would look at their website but

# Answer
Have you tried

```
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);

```

If you are using OpenGL to draw the image then this enables alpha channel blending.

Sources: LWJGL Wiki and Trial and Error
> 1 votes

---
Tags: opengl, lwjgl, slick, alpha
---


# Question
Title: Why cant I use slick-util with image IO and bufferedImage
My problem is that I get errors when I use

```
texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("TEXTURE PATH HERE"));

```

it gives me these errors:

```
Exception in thread "main" java.lang.RuntimeException: No OpenGL context found in the current thread.
    at org.lwjgl.opengl.GLContext.getCapabilities(GLContext.java:124)
    at org.lwjgl.opengl.GL11.glGetError(GL11.java:1277)
    at org.newdawn.slick.opengl.InternalTextureLoader.getTexture(InternalTextureLoader.java:226)
    at org.newdawn.slick.opengl.InternalTextureLoader.getTexture(InternalTextureLoader.java:184)
    at org.newdawn.slick.opengl.TextureLoader.getTexture(TextureLoader.java:64)
    at org.newdawn.slick.opengl.TextureLoader.getTexture(TextureLoader.java:24)
    at game.Map.Init(Map.java:34)
    at game.Game.start(Game.java:17)
    at game.Game.main(Game.java:63)

```

My code uses ImageIO, Buffered Image and `image.getRGB();` But it also uses the Slick-Util library for loading textures to render.

The full code for the Map.java class is:

```
`
package game;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.Color;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;

public class Map {

    int mapSize=100;
    int[] Tiles = new int[mapSize+1];
    int Tile;

    public Texture texture;

    public void Init()
    {
        try {
            // load texture from PNG file
            texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/Tiles/Grass.png"));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

     public void LoadMap()
        {

            File file= new File("res/map.png");
              BufferedImage image = null;
            try {
                image = ImageIO.read(file);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            for(int Y = 0;Y<image.getHeight();Y++){
                for(int X = 0;X<image.getWidth();X++){

              int clr=  image.getRGB(X,Y);
              int  red   = (clr & 0x00ff0000) >> 16;
              int  green = (clr & 0x0000ff00) >> 8;
              int  blue  =  clr & 0x000000ff;
              if(red==0&&green==0&&blue==0){
                  Tiles[Tile]=0;
              }
              if(red==255&&green==0&&blue==0){
                  Tiles[Tile]=1;
              }
              if(red==0&&green==255&&blue==0){
                  Tiles[Tile]=2;
              }
              if(red==0&&green==0&&blue==255){
                  Tiles[Tile]=3;
              }
              Tile++;
            }
            }
            for(int i = 0;i<mapSize;i++)
            {
                System.out.println(Tiles[i]);
            }

        }
     public void RenderMap()
     {

     }

}
`

```

So all I want to know is how can I fix this error and draw the textures down in the

```
 void Render()
    {

    }

```

method.

Thanks, Griffin.

# Answer
I hope this clarifies it for you. I've noticed you're importing lwjgl, I take it you want more functionality than what Slick 2D is offering? I would need to see your lwjgl construction to comment further...

In a normal Slick 2D setup with BasicGame, you would do something similar to this:

```
import java.io.IOException;
import org.newdawn.slick.*;
import org.newdawn.slick.opengl.*;

public class TextureTest extends BasicGame
{
    private Texture texture;
    private Image grass;

    public TextureTest()
    {
        super("Texture Load Test");
    }

    @Override
    public void init(GameContainer container) throws SlickException
    {
        try
        {
            // load texture from PNG file
            texture = TextureLoader.getTexture("PNG", getClass().getResourceAsStream("grass.png"));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        grass = new Image(texture);
    }

    @Override
    public void update(GameContainer container, int delta)
            throws SlickException
    {
    }

    @Override
    public void render(GameContainer container, Graphics g)
            throws SlickException
    {
        grass.draw();
    }

    public static void main(String[] args) throws SlickException
    {
        TextureTest game = new TextureTest();
        AppGameContainer app = new AppGameContainer(game);
        app.setAlwaysRender(true);
        app.start();
    }
}

```
> 1 votes

# Answer
Are you trying to load images into OpenGL before you create an OpenGL context (as in, open the game window via Slick)? That's not going to work.
> 0 votes

---
Tags: java, lwjgl, image
---