title: WinAPI SwapBuffers and Threads

text:
# Question
Title: WinAPI SwapBuffers and Threads
I'm trying to use a different Thread for the whole WinAPI-Message-Loop stuff, so the window always keeps being responsive. Of course I'm using the main thread as the "window thread", because I need a context before loading textures etc. and I can't just call Get/PeekMessage for a different thread.

Now there are a few things I'm wondering about though:

1. Can I use the OpenGL context handle from a different thread? I'm relatively sure I can since otherwise there would be no way to do multi-threaded rendering, but maybe there's more to it.
2. At some point I have to call SwapBuffers() from inside the render loop - that means in this case, from a different thread. Can I just use the HDC I usually use? Is this handle thread-safe? I'm not so sure about that, but I can't really find a definitive answer on the subject.

If the answer is no, what would be a good method to deal with the issue? Maybe I can send a message from the render-thread?

# Answer
> 1 votes
**No**, you generally cannot interact with your main window from not the main thread. Since the GL context is tied to the HWND, you cannot generally issue GL commands from threads that are not the main thread.

"Multithreaded rendering" is only about doing data processing and whatnot. You can do all kinds of math and processing on worker threads. But OpenGL commands should all be issued from the main thread.

Generally what you do to keep the main window responsive is have heavy work done on separate threads, and have them set some kind of flag when they are finished, which lets the main window move on to the next stage of the program.

Consider this:

```
// main thread
while( 1 )
{
    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
    {
        Translate/dispatchmessage
    }
    else
    {
        update();
        draw();
    }
}

```

Inside draw():

```
void draw()
{
    switch( programState )
    {
        case Title:
          //draw the title
          break;
        case InGame:
          // draw in game
          break;
    }
}

```

So the worker thread will (MUTEX LOCK AND) change the value of `programState` when it is done loading the level, for example.

# Answer
> 1 votes
I just had to create the HGLRC in a different thread and everything worked fine. The HWND is thread-safe in this case.

---
Tags: opengl, multithreading, winapi
---


# Question
Title: Game Designer or Game Programmer, please help me choose!
I know this question is asked a lot but I am still so confused and overwhelmed by the different opinion and comments everybody has on the internet, that I wanted to ask my questions in a single thread and get the answered by you. I would really appreciate it if you could spend a couple of minutes reading this as I don't have anybody near me to talk to about this.

I'm about to finish High School (I have one year left) and until last year what I wanted to do with my life was pursue a degree in fields such as Accounting/Finance or Medicine since those are the "most competitive" ones and where most of the $$ are made. I was all about the money and recently I finally understood the importance of studying and doing what I really care and dream about and that such competitive fields would wipe out people like me who are not really "dedicated". Anyways, as the title says, I'm into games, but I'm not that average type of guy who is interested in this just because he has played lots of games in his childhood and thinks that would do great at this.

The thing is that even though I want to immerse myself in the gaming industry, I still don't know what specific jobs consist of, mainly the Game Designer and the Game Programmer (this is the same as a Game Developer right?). To give you an idea of what I can do, I am great at math, photoshop, I'm creative, curious and following my "leader instincts" I want to just not be "the tool" of someone while working (while I do acknowledge that I will have a boss who will be above me, the company's owner for example), but I do not want to be the person who will be with a group of other people who do the same thing. What I'm trying to say is that I want to come up with the idea of the game, sketch it, bring it to life and even decide what the world, characters and story will look like, but I don't want to just design the characters or the world of the game because someone else came up with it and now I'm just bringing to life their project. I don't want to be just the "drawer" or the Game's Art designer. I want to be independent and even give rules (yeah, I know, not right away most probably), but I want to be the one to give life to my own project.

On the other hand, I haven't tried programming but I do have solid math skills as I said and I don't want to just "toss" them. I haven't tried coding but from what I've been reading, some people say C++ is a nightmare. Is it really so "cut with knife" and already defined, that you can either go full artistic and be the visual dude, or the game designer, or go fully scientific and be the one to deal with the system of the game and be the programmer? Because as I said I really lean towards the designing part more, but I would like to code and not be totally ignorant on that part. I do want to code, but I would totally HATE to be the guy who deals with the numbers only. Yeah I want to do some of that, but designing, choosing the characters' sprites, costumes, gameplay, effects, storyline, etc. etc. seems much more interesting to me.

Another thing that bothers me the most is what I will study in University? I wont study in the US, although it's a dream of mine, but I can't afford it as an international student, so it would be a bit different for you who are from there and try to answer this, but I've seen most people recommend Computer Science, who say that a programmer can always become a designer in the future, but a designer can't do the programming part if he doesn't have any knowledge in that area. I've already read and "studied" the mythology, am educated in literature am thinking of taking psychology classes in my last High School year, but really, what do you suggest? I've seen universities offer classes for Digital Media or even Game Designing, but from what I've read this is a pretty new field and it wont help if I choose this major in university? Should I really go for a Computer Science degree? To make it clear to you, I HATE physics, I hope I wont be dealing with that. If I choose this route, how will I learn certain aspects of designing, such as animation, etc.?

I'm sorry for the huge text but I'm really confused and I feel like this is a really important part of my life, and being close to university I really need to make a decision fast, so that I can prepare myself as soon as I can.

Thank you very much.

# Answer
> 5 votes
**You need to be a programmer and an artist...**

...but lean heavily towards one side.

Game design is both of these things.

Programming is not hard. Programming is one of the easiest aspects of game development. Learning C++ is hard. Using C++ is the opposite of hard. The same goes for most programming languages.

A cabinet maker can design all the cabinets he wants, but unless he has knowledge of woodworking, the cabinets will never get built.

You don't need to be a good programmer. There are tons of development suites that take care of the heavy lifting. Take a look at Unity. Unity is widely considered to be incredibly easy to use, but you still need to know how to program to use it.

It all depends on the tools you use. If you use Unity, you should be an "artist with knowledge of programming". If you create an engine in C++, you should be a "programmer with knowledge of art". It is senseless to limit yourself to one or the other.

**Find a friend.**

If you want to focus on the artistic side of things, find a programmer to help manifest your ideas. Similarly, if you decide to be a programmer, you should find an artist to create all of the visuals.

It is a bad idea to try to have equal skill of programming and art. Take a look at any indie game created by one person. If that person is a programmer, the game looks bad. If that person is an artist, the game is technically impaired. If the person is "both", the game is simply bad. (Although there is the occasional demigod who needs no help.)

---
Tags: graphics, animation
---


# Question
Title: How to scale a sprite with its center as origin?
I'm trying to zoom-in a sprite gradually from 0% to 100% (a sprite called SelectionBox), so it zooms from the middle of the sprite, not from the upper-left corner. I'm almost there, but I'm having problems with the sprite origin - it's not positioning it in the spot I told it to.

What's wrong with this code?

```
SpritePosition_FirstBox = New Vector2(15, 50)
MiddleOrigin = New Vector2(CSng(Texture_SelectionBox.Width / 2), CSng(Texture_SelectionBox.Height / 2))

spriteBatch.Draw(Texture_SelectionBox, SpritePosition_FirstBox, Nothing, Color.White, 0, MiddleOrigin, ScaleValue, SpriteEffects.None, 0.94)

```

# Answer
> 1 votes
I found out what was missing:

Instead of

```
SpritePosition_FirstBox = New Vector2(15, 50)

```

It should be

```
SpritePosition_FirstBox = New Vector2(CSng(15 + (Texture_SelectionBox.Width / 2)), CSng(50 + (Texture_SelectionBox.Height / 2)))

```

# Answer
> 4 votes
It has to do with where you're placing the origin relative to the scale factor. Take this for example:

```
SpriteBatch.Draw(myTexture, // Texture
    new Vector2(0, 0),      // Position
    Nothing,                // Source rectangle
    Color.White,            // Color
    0,                      // Rotation
    new Vector2(5, 5),      // Origin
    new Vector2(0.5, 0.5),  // Scale
    SpriteEffects.None,     // Mirroring effect
    0.94);                  // Depth

```

Here we're drawing at position `0,0` from origin point `5,5` with a scale factor of `0.5, 0.5`, right? And in the following:

```
SpriteBatch.Draw(myTexture, // Texture
    new Vector2(0, 0),      // Position
    Nothing,                // Source rectangle
    Color.White,            // Color
    0,                      // Rotation
    new Vector2(5, 5),      // Origin
    new Vector2(1, 1),      // Scale
    SpriteEffects.None,     // Mirroring effect
    0.94);                  // Depth

```

We're now drawing at a scale factor of `1,1` *but we're still drawing from the same origin.* So instead, you should try something like this:

```
Vector2 scaleFactor = new Vector2(0.5, 0.5);
Vector2 origin = new Vector2(myTexture.Width / 2 * scaleFactor.X, myTexture.Height / 2 * scaleFactor.Y);
SpriteBatch.Draw(myTexture, // Texture
    new Vector2(0, 0),      // Position
    Nothing,                // Source rectangle
    Color.White,            // Color
    0,                      // Rotation
    origin,                 // Origin
    scaleFactor,            // Scale
    SpriteEffects.None,     // Mirroring effect
    0.94);                  // Depth

```

That way you're expanding from the center of the texture relative to it's current size.

---
Tags: xna, sprites, scale
---


# Question
Title: Is OpenCTM sill under active development?
After struggling with `*.3ds` files, which I could not export as I wanted, and `*.obj` files for which I haven't found an available library, I continue the search for a file format for my little game engine.

I heard about OpenCTM which sounds like a promising solution to me. It's just for storing vertices but I could totally live with that. And I like the API which is quite similar to the OpenGL api. It also comes with a viewer and importer/exporter.

But of course I wouldn't like to rely on a dead file format. According to what I've seen on Github, the last change was at the beginning of 2010. So my question is if OpenCTM is sill under active development and I could therefore use it without doubt in my game engine.

# Answer
Indeed, it seems that OpenCTM development has stopped. Looking on their Sourceforge, Github repo and around the internet in general, it seems to have ceased. That said, there are still some people using it, as there was recently a Javascript port, and you could continue developing your own version of it (it doesn't look too complicated at first sight).
> 0 votes

---
Tags: file-format
---


# Question
Title: Is there a material format for OpenCTM files?
I consider using OpenCTM files for my game. Since the format only claims to store raw mesh data, my question is if there is a associated file format for material data and paths to texture maps.

For example material of `.obj` meshes are stored in `.mtl` files. Is there such a format for OpenCTM, too?

# Answer
To quote directly from the link you provided:

For instance, OpenCTM ***does not handle*** multiple meshes, transformation matrices, ***materials***, light sources, physical properties, etc.

So, the answer is it does not have built in material support. However, it also says 'Supports storage of per-vertex normals, ***UV coordinates*** and custom vertex attributes.' This means that you can provide a texture separately, and also light/bump maps. All you'll have to do is put a bit of extra work in. To be honest, you could use a .mtl file and just repurpose it.
> 3 votes

---
Tags: file-format, materials
---


title: Jittery effects with collisions

text:
# Question
Title: Jittery effects with collisions
I have been having some problems with my coding lately. I am trying to create a platform-based game and I have been having some troubles.

A friend of mine said that some update functions are out of order, so my collision is causing a jittery effect. It looks kind of weird so I am hoping that you guys could help me.

Here is the code for the update in game1.cs and player.cs

game1.cs -

```
protected override void Update(GameTime gameTime)
{
    // Allows the game to exit
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
        this.Exit();
    player.update(gameTime);
    if (f.rectangle.Intersects(player.rectangle))
    {
        player.isOnSurface = true;
        player.position.Y = f.rectangle.Top - player.texture.Height;
    }
    else player.isOnSurface = false;
    f.update(gameTime);
    base.Update(gameTime);
}

```

player.cs -

```
public void update(GameTime gameTime)
{
    position = position + velocity;
    // walking
    if (Keyboard.GetState().IsKeyDown(Keys.A) | Keyboard.GetState().IsKeyDown(Keys.Left)) velocity.X = -4f;
    else if (Keyboard.GetState().IsKeyDown(Keys.D) | Keyboard.GetState().IsKeyDown(Keys.Right)) velocity.X = 4f;
    else velocity.X = 0;
    // jumping

    if (Keyboard.GetState().IsKeyDown(Keys.W) | Keyboard.GetState().IsKeyDown(Keys.Up) | Keyboard.GetState().IsKeyDown(Keys.Space) && isOnSurface == true)
    {
        isOnSurface = false;
        position.Y -= 10;
        velocity.Y = -5;
    }
    // gravity
    rectangle = new Rectangle((int)position.X, (int)position.Y, texture.Width, texture.Height);
    if (!isOnSurface)
    {
        float i = 1;
        velocity.Y += 0.15f * i;

    }
    else
    {
        velocity.Y = 0f;
    }
}

```

I would just like to know if my functions are in order, or how to get rid of the jittery effect (and therefore a good method for collision).

# Answer
> 1 votes
I'm not 100% sure on this but it seems that the problem may be in the fact that in each frame for gravity you are adding 0.15 to Y velocity, but then casting it back down to an integer when you do your rectangles. So if technically you've adjusted your position by a fraction of a pixel, then when you do collision checks it will say you are not colliding (because you are casting that 0.15 down to 0) and then (I assume) drawing the sprite to the fractional pixels. You can try casting the positions in your draw method to integers before you draw it. This could prevent the jittery between-pixel drawing.

# Answer
> 0 votes
There seems to be a slight chance that after you detect collision with the object f, that the players velocity is not zero. The next time player.Update is called you adjust the players position by the velocity, then later do the check on isOnSurface and set the velocity to zero. This can cause a jitter effect like you are seeing.

---
Tags: xna, c#, collision-detection
---


# Question
Title: How can I handle a bunch of achievements in a game?
Take for example Team Fortress 2. There are a huge load of achievements, and I'm wondering how the manages all of them. And since there's a lot of achievements, I'd also like to know how it "knows" you've achieved one.

Basically, how can the game handle a huge achievement system? Is there some special process? Are there hundreds and hundreds of boolean variables all over the code, waiting for certain conditions to be met, then ,*Bam*, achievement?

If there are several approaches, what are they?

# Answer
> 6 votes
I think one method to implement something like this could be **event-driven**. This means, you will have points in your code where specific events are called. It must be somewhat extended to allow to **pass parameters**, but I think it’s not uncommon that event-systems can handle parameters.

First you will have to **define some events in your code** that can happen. This is the position where you thought of all the `if`-conditions. E.g. when a player kills somebody, an event for killing somebody will be raised.

I do not know Team Fortress 2, but it’s a shooter, so I choose some shooter examples. In the code examples the first parameters always is the event name and the later ones are an indefinite list of parameters (this event takes).

* player kills another player (`callEvent('kills-player', curPlayer)`)
* player just disarmed a bomb (`callEvent('disarms-bomb', curPlayer)`)
* player reached point X (`callEvent('reaches-point', curPlayer, somePointOnMap)`)
* player saved another players live (`callEvent('saved-player', curPlayer, rescuedPlayer)`)

So it’s not boolean variables throughout your code, but specific events that will be called.

It’s now up to a totally different programmer at a totally different position in the code to either **use or not use these events** (called *listening* to them). You might also save events in a database to be able to count them (and give awards when something occured 10 times). This will also be done by the programmer who catches the events with a method like the following. It takes:

* the event-name as first parameter
* a lambda-function to handle the event as the second parameter. The lambda-function can catch all arguments we passed to the event handler before.

Code example:

```
listenToEvent('kills-player', function(player) {
    database.incrementKillPlayerCount(player);

    if (database.killPlayerCount(player) == 10) {
        player.awardWithAchievement("You killed 10 enemies!");
    }
});

```

So this little function can now cope with events that were raised in a totally different place of th code. And it will award a player with the correct achievement if needed.

## Addition

As it sounds like TF2's system was very flexible: You might also implement the event-system in a manner that it watches for several situations to occur within the same time or within a timespan. Of course you had to change it a little to maintain a small buffer or similar for several seconds or milliseconds and then map calls like `listenToEvent(array('kills-player', 'disarms-bomb') function() {})` to the buffer.

---
Tags: game-design, achievements
---


title: multiplayer game in openGL

text:
# Question
Title: multiplayer game in openGL
what is the easiest way how to make network communication in openGL/glut? Does anybody know any good tutorial for beginners? thanks

(or is there any simpler way then openGL?)

# Answer
> 3 votes
you are looking into the wrong things i'm afraid. OpenGL is a graphics library and has nothing to do with network communications.

You best bet would be to look up tutorials on network communication examples for the programming language you are using to write your program in

---
Tags: c++, opengl, multiplayer, glut
---


# Question
Title: XNA 4.0, FBX and Texture Loading Failures
I've been going through several tutorials on how to use XNA and understand a lot thus far. I've got a screen, I've got 2D sprites working, got a shader system operational, so far so good. Now I've hit a wall.

I'm attempting to load a 3D model (FBX Format) I've exported from 3DS. My issue, is the texture system. First, I'm trying to avoid embedding the textures directly into the FBX as I'll be reusing a lot of the textures for different things, no need to load multiple copies of the same texture. I know my texture, even though not embedded, is making it to my XNA classes because I can see it inside the FBX (when saved as ASCII) and get a compiler error if I attempt to move the texture out of its original location. I can also see it compiling the image during a rebuild.

However, if I attempt to render the object, no texture. Loading code:

```
protected override void LoadContent()
{
    objModel = LoadModel("Models/OriginModel");
}

```

objModel is defined as a *Model* higher up in the cs file.

My display code:

```
foreach (ModelMesh mesh in objModel.Meshes)
{
    foreach (Effect currentEffect in mesh.Effects)
    {
        currentEffect.CurrentTechnique = currentEffect.Techniques["TextureNormalMap"];
        currentEffect.Parameters["World"].SetValue(objTransforms[mesh.ParentBone.Index] * worldMatrix);
        currentEffect.Parameters["View"].SetValue(viewMatrix);
        currentEffect.Parameters["Projection"].SetValue(projectionMatrix);
    }
}

```

I've stripped out the matrix transforms and such as they're not causing the issue. *TextureNormalMap* is my shader I've written that displays a texture with a normal map. This generates a black model. If I however add...

```
metalTex = Content.Load<Texture2D>("Textures/brushedmetaltexture");

```

and

```
currentEffect.Parameters["ColorMap"].SetValue(metalTex);

```

where needed, I get the texture to display. This is of course, the problem. I have to include the texture in my Content system, causing the image to be compiled twice (which generates a warning..compiled once from the FBX, compiled once from Content). More importantly, I would have to hand-texture all the models again inside the XNA system in order to get them to display, which is what I'm trying to avoid. I've already textured them once in 3DS, do I really need to specify, inside XNA during object load, all the textures again?

So, any ideas on what I'm doing wrong here? What magical step am I skipping? Am I supposed to, somehow, figure out what the texture name is from the FBX file itself and get a pointer to the extracted image to feed into my Texture2D? Is there a different object I should use that includes the texture from the FBX? Do I need to bite the bullet and just go with embedding (which still doesn't work with the above code btw)?

I've been going off of tutorials as I mentioned, but this step seems to be missing, or am I just being daft? I apologize if this seems trivial, but I just can't solve it. Is there some step in the object loading process I'm missing?

# Answer
> 1 votes
I think the name of the texture in the FBX file is what gets assigned to the effect parameter. So if it's not set to "ColorMap", it won't work.

I personally use a custom content processor that allows me to change the texture, effect file, and whatever else right in the Visual Studio properties window. Check this function to see how I set the texture. "DiffuseTexture" is the name of my effect parameter.

If you poke around the code there's a lot of other support for my cobbled-together Blender-\>FBX-\>XNA pipeline. It even supports multiple animation takes imported from a single FBX file. I don't recommend it to anyone, but if you've already made the mistake of going down that road, it might be useful.

---
Tags: xna-4.0, textures, fbx
---


# Question
Title: Adjusting a skeleton to a Specific Stance
Imagine having a climbing wall and you take 4 adjacent handholds and footholds where together they create a stance. Is there any algorithm or technique with which it would give you a realistic human pose? Currently im adjusting the skeleton by firstly finding the center of the 4 holds where then i construct the chest shoulder and pelvis accordingly. And by the use of IK i give position to the remaining limbs being which the arms and legs. Is there any other more elegant/better technique how to do such positioning of a skeleton ? As how i am adjusting the skeleton isnt so much of a realistic pose.All is done in 2D

# Answer
> 2 votes
To find a good algorithm for such a stance will take quite some time, observation and testing, I don't think you will find a "one-fits-all" solution on the internet.

There is a lot you have to consider for skeletons climbing obstacles and I assume you don't only want it to take a certain stance, but to move from one to another in a realistic way.

"Specific Stance" is a little to abstract, a specific stance could be:

* *looking like the skeleton has tight grip on the wall*

in this case the arms and legs will almost be equally stretched, the body will be closer to the wall

* *looking like the skeleton is about to move up*

depening on the distance the skeleton can have really bent legs to make it look like he is about to make a big leap upwards, or stretched legs if he tries to climb and pull himself up.

These are just simple examples, there are many more things and actions to be taken into consideration for a correct stance.

You can start by defining which stances you want, and which transitions from which stances you want. Then analyse some rock climbing videos on youtube (or yourself if you're a climber) for the look and feel of your stance and/or transition.

The easiest way will probably be to only implement the skeletons back and pelvis position (or movements for transitions) relative to the center of the 4 handholds/footholds, depending on the stance you want (centered, or lowered for a leap..). Then place the hands and feet on the hand/footholds.

The rest is adjusting your min/max angles for the knees and elbows, which will require some testing until you find something that looks good for you.

---
Tags: animation, skeletal-animation, rigid-body-dynamics
---


title: Camera in Flash

text:
# Question
Title: Camera in Flash
Im having a hard time trying to work out how to implement a smooth camera in flash.

In something like openGL i would use a transformation matrix to move the camera around the scene.

However with flash my current solution is to put everything into one movie clip and then move that clip around the scene which doesnt seem like the most elegant solution Since my level is rather large.

What other solutions are the to creating a 2D camera in flash (I have also tried the Vcam but that also seems rather over the top and also lagged out way more than my current solution).

# Answer
> 2 votes
You can try playing with the scrollRect property. Here's a minimal example:

```
package  {

    import flash.display.Sprite;
    import flash.display.DisplayObject;
    import flash.events.Event;
    import flash.display.Shape;
    import flash.geom.Rectangle;

    public class CamTest extends Sprite {

        private var world:Sprite;
        private var view:Rectangle = new Rectangle(0,0,300,300);//only display a portion
        private var ease:Number = .075;

        public function CamTest() {
            addEventListener(Event.ADDED_TO_STAGE,init);
        }
        private function init(e:Event):void{
            world = addChild(new Sprite) as Sprite;//add a container
            for(var i:int = 0 ; i < 100; i++) world.addChild(getRandomShape());//populate it with random shapes
            stage.addEventListener(Event.ENTER_FRAME,update);//loop
        }

        private function update(e:Event):void{
            view.x += (mouseX-view.x) * ease;//ease the pan positions
            view.y += (mouseY-view.y) * ease;//might want to map mouse coords
            world.scrollRect = view;//re-apply the scrollRect
        }
        //dummy shapes, not important
        private function getRandomShape():Shape{
            var s:Shape = new Shape();
            var np:int = (int)(3+Math.random()*9);//random points
            var ai:Number = Math.PI / (np * .5);//angle increment
            s.graphics.lineStyle(1+Math.random() * 7);
            for(var i:int = 0 ; i <= np; i++) {
                var a:Number = ai*i;
                var r:Number = 20+Math.random() * 10 - Math.random() * 10;
                var x:Number = Math.cos(a) * r;
                var y:Number = Math.sin(a) * r;
                if(i == 0) s.graphics.moveTo(x,y);
                s.graphics.lineTo(x,y);
            }
            s.x = Math.random() * 1000;
            s.y = Math.random() * 1000;
            return s;
        }
    }

}

```

If your world is dense you might want to consider using bitmap sprites/blitting. Here's a minimal example using BitmapData's copyPixels() method:

```
package  {

    import flash.display.MovieClip;
    import flash.display.BitmapData;
    import flash.display.Bitmap;
    import flash.display.BitmapDataChannel;
    import flash.geom.Point;
    import flash.events.Event;
    import flash.geom.Rectangle;

    public class CamTest2 extends MovieClip {

        private var world:BitmapData = new BitmapData(1000,1000,false,0xFFFFFF);
        private var render:BitmapData = new BitmapData(300,300,false,0xFFFFFF);
        private var view:Rectangle = new Rectangle(0,0,render.width,render.height);//only display a portion
        private var zero:Point = new Point();
        private var ease:Number = .075;

        public function CamTest2() {
            init();
        }
        private function init() {
            world.perlinNoise(200, 180, 6,(int)(Math.random() * 10), false, true, BitmapDataChannel.RED, false, null);//random world
            addChild(new Bitmap(render));
            addEventListener(Event.ENTER_FRAME,update);
        }
        private function update(e:Event):void{
            //update pan
            view.x += (mouseX-view.x) * ease;//ease the pan positions
            view.y += (mouseY-view.y) * ease;//might want to map mouse coords
            //render based on updated view rect
            render.lock();
            render.copyPixels(world,view,zero);
            render.unlock();
        }
    }

}

```

You should also look into actionscript game engines that already implement cameras like Flixel or Starling

---
Tags: flash, actionscript-3, camera
---


# Question
Title: How To Correctly Extend the Sprite Class in LibGDX
I am currently pursuing game development as a hobby, and have run into what seems to be a conflict in my mind regarding how to properly (using best practices) extend the `Sprite` class in LibGDX (or for the sake of this question, any Sprite class).

## What I Would Like To Do

I would like to to create a class, `Ship.java`, with the constructor as follows:

```
// Note the lack of a Texture object in the constructor here
public Ship(float startingX, float startingY){

    super(new Texture(Gdx.files.internal("data/ship_texture.png")), 0, 0);

    this.startingX = startingX;
    this.startingY = startingY;

}

```

## Why I Can't Do This

First, this implementation forces me to forfeit having a reference to the `Texture` that I am passing into the super constructor. This means that I cannot properly `dispose()` it later, which would lead to memory leaks later in the code.

## The Problem

Since the constructor of the `Sprite` class forces you to specify a `Texture`, and I would want a `Ship` to *always* have the same `Texture` (thus would not want to specify it in the constructor of a `Ship`), I am limited to hacking together some factory method to construct the `Ship`.

## My Current Solution

As specified above, I currently have a factory method that creates the `Ship` instead of using the constructor.

## The Code

Below I have detailed the code I am currently using to get the `Ship` class instantiated. Please feel free to critique it:

```
// Private constructor because I do not want this method to be called ever
private Ship(Texture texture, int row, int column) {

    // Calls the super constructor (for the Sprite class)
    super(texture, row, column);
}

// Instead, this create method returns a new instance of Ship
public static Ship create(int row, int column){

    // Create the new texture
    Texture texture = new Texture(Gdx.files.internal("data/ship.png"));

    // Set the LINEAR filter (might switch to NEAREST later)
    texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);

    // Return a new instance of the Ship
    return new Ship(texture, row, column);
}

```

## Why I Don't Like This Solution

I feel as though this is a very "hacky" fix, as it defeats the purpose of a constructor, and although static factory methods are good practice, I don't think it should be necessary to implement a new factory method for each object I plan to draw on the `Screen`.

---

## My Question

What is the best way to extend the `Sprite` class (thus keeping all the helper methods that it provides), and still define the `Texture` that will be displayed on the object within the constructor of the `Ship`?

Is the current approach I am using appropriate?

# Answer
> 5 votes
In the game I'm developing I'm using a centralized AssetManager, which will hold the references and automatically dispose them. I just need to load the pack file and get the TextureAtlas from it. (or the texture if you are using single images instead of packs)

```
TextureAtlas atlas = game.assets.get("filename.pack", TextureAtlas.class);
jewelSprite = new JewelSprite(jewelType, atlas.findRegion("textureName")), game);
// use `AtlasRegion` instead of `Texture`

```

Check the first link for a nice overview of the AssetManager. You don't need to pack the textures but it is recommended for performance.

---
Tags: java, libgdx
---


# Question
Title: AndEngine; Box2D - high speed body overlapping, prismatic joints
I'm trying to make good suspension for my car game, but I'm getting nervous of some problems with it.

At the beginning, I've tried to make it out of one prismatic joint/revolute joint per one wheel only, but surprisingly prismatic joint that should only move in Y asix moves also in X axis, if car travels very fast, or even on low speeds if there's setContinuousPhysics = true. This causes wheels to "shift back", moving them away from axle.

Now I've tried to add some bodies that will keep it in place:

Suspension helper collides with spring only, wheel doesn't collide with spring&helper&vehicle body

This is how I create those elements:

```
rect = new Rectangle(1100, 1350, 200, 50, getVertexBufferObjectManager());
        rect.setColor(Color.RED);
        scene.attachChild(rect);
        //rect.setRotation(90);
        Rectangle miniRect1 = new Rectangle(1102, 1355, 30, 50, getVertexBufferObjectManager());
        miniRect1.setColor(0, 0, 1, 0.5f);
        miniRect1.setVisible(true);
        scene.attachChild(miniRect1);

        Rectangle miniRect2 = new Rectangle(1268, 1355, 30, 50, getVertexBufferObjectManager());
        miniRect2.setColor(0, 0, 1, 0.5f);
        miniRect1.setVisible(true);
        scene.attachChild(miniRect2);

        rectBody = PhysicsFactory.createBoxBody(
                physicsWorld, rect, BodyDef.BodyType.DynamicBody, PhysicsFactory.createFixtureDef(10.0f, 0.01f, 10.0f));
        rectBody.setUserData("car");

        Body miniRect1Body = PhysicsFactory.createBoxBody(
                physicsWorld, miniRect1, BodyDef.BodyType.DynamicBody, PhysicsFactory.createFixtureDef(10.0f, 0.01f, 10.0f));
        miniRect1Body.setUserData("suspension");

        Body miniRect2Body = PhysicsFactory.createBoxBody(
                physicsWorld, miniRect2, BodyDef.BodyType.DynamicBody, PhysicsFactory.createFixtureDef(10.0f, 0.01f, 10.0f));
        miniRect2Body.setUserData("suspension");

        physicsWorld.registerPhysicsConnector(new PhysicsConnector(rect, rectBody, true, true));
        physicsWorld.registerPhysicsConnector(new PhysicsConnector(miniRect1, miniRect1Body, true, true));
        physicsWorld.registerPhysicsConnector(new PhysicsConnector(miniRect2, miniRect2Body, true, true));

        PrismaticJointDef miniRect1JointDef = new PrismaticJointDef();
        miniRect1JointDef.initialize(rectBody, miniRect1Body,
                miniRect1Body.getWorldCenter(),
                new Vector2(0.0f, 0.3f));
        miniRect1JointDef.collideConnected = false;
        miniRect1JointDef.enableMotor= true;

        miniRect1JointDef.maxMotorForce = 15;
        miniRect1JointDef.motorSpeed = 5;
        miniRect1JointDef.enableLimit = true;
        physicsWorld.createJoint(miniRect1JointDef);

        PrismaticJointDef miniRect2JointDef = new PrismaticJointDef();
        miniRect2JointDef.initialize(rectBody, miniRect2Body,
                miniRect2Body.getWorldCenter(),
                new Vector2(0.0f, 0.3f));
        miniRect2JointDef.collideConnected = false;
        miniRect2JointDef.enableMotor= true;
        miniRect2JointDef.maxMotorForce = 15;
        miniRect2JointDef.motorSpeed = 5;
        miniRect2JointDef.enableLimit = true;
        physicsWorld.createJoint(miniRect2JointDef);

        scene.attachChild(karoseriaSprite);

        Rectangle r1 = new Rectangle(1050, 1300, 52, 150, getVertexBufferObjectManager());
        r1.setColor(0, 1, 0, 0.5f);
        r1.setVisible(true);
        scene.attachChild(r1);
        Body r1body = PhysicsFactory.createBoxBody(physicsWorld, r1, BodyDef.BodyType.DynamicBody, PhysicsFactory.createFixtureDef(10.0f, 0.001f, 0.01f));
        r1body.setUserData("suspensionHelper");
        physicsWorld.registerPhysicsConnector(new PhysicsConnector(r1, r1body, true, true));
        WeldJointDef r1jointDef = new WeldJointDef();
        r1jointDef.initialize(r1body, rectBody, r1body.getWorldCenter());
        physicsWorld.createJoint(r1jointDef);

        Rectangle r2 = new Rectangle(1132, 1300, 136, 150, getVertexBufferObjectManager());
        r2.setColor(0, 1, 0, 0.5f);
        r2.setVisible(true);
        scene.attachChild(r2);
        Body r2body = PhysicsFactory.createBoxBody(physicsWorld, r2, BodyDef.BodyType.DynamicBody, PhysicsFactory.createFixtureDef(10.0f, 0.001f, 0.01f));
        r2body.setUserData("suspensionHelper");
        physicsWorld.registerPhysicsConnector(new PhysicsConnector(r2, r2body, true, true));
        WeldJointDef r2jointDef = new WeldJointDef();
        r2jointDef.initialize(r2body, rectBody, r2body.getWorldCenter());
        physicsWorld.createJoint(r2jointDef);

        Rectangle r3 = new Rectangle(1298, 1300, 50, 150, getVertexBufferObjectManager());
        r3.setColor(0, 1, 0, 0.5f);
        r3.setVisible(true);
        scene.attachChild(r3);
        Body r3body = PhysicsFactory.createBoxBody(physicsWorld, r3, BodyDef.BodyType.DynamicBody, PhysicsFactory.createFixtureDef(1f, 0.01f, 0.01f));
        r3body.setUserData("suspensionHelper");
        physicsWorld.registerPhysicsConnector(new PhysicsConnector(r3, r3body, true, true));
        WeldJointDef r3jointDef = new WeldJointDef();
        r3jointDef.initialize(r3body, rectBody, r3body.getWorldCenter());
        physicsWorld.createJoint(r3jointDef);
        MouseJointDef md = new MouseJointDef();

        Sprite wheel1 = new Sprite(
                miniRect1.getX()+miniRect1.getWidth()/2-wheelTexture.getWidth()/2,
                miniRect1.getY()+miniRect1.getHeight()-wheelTexture.getHeight()/2,
                wheelTexture, engine.getVertexBufferObjectManager());
        scene.attachChild(wheel1);

        Body wheel1body = PhysicsFactory.createCircleBody(
                physicsWorld, wheel1, BodyDef.BodyType.DynamicBody, PhysicsFactory.createFixtureDef(10.0f, 0.01f, 5.0f));
        wheel1body.setUserData("wheel");
        Shape wheel1shape = wheel1body.getFixtureList().get(0).getShape();
        wheel1shape.setRadius(wheel1shape.getRadius()*(3.0f/4.0f));
        physicsWorld.registerPhysicsConnector(new PhysicsConnector(wheel1, wheel1body, true, true));

        Sprite wheel2 = new Sprite(
                miniRect2.getX()+miniRect2.getWidth()/2-wheelTexture.getWidth()/2,
                miniRect2.getY()+miniRect2.getHeight()-wheelTexture.getHeight()/2,
                wheelTexture, engine.getVertexBufferObjectManager());
        scene.attachChild(wheel2);

        Body wheel2body = PhysicsFactory.createCircleBody(
                physicsWorld, wheel2, BodyDef.BodyType.DynamicBody, PhysicsFactory.createFixtureDef(10.0f, 0.01f, 5.0f));
        wheel2body.setUserData("wheel");
        Shape wheel2shape = wheel2body.getFixtureList().get(0).getShape();
        wheel2shape.setRadius(wheel2shape.getRadius()*(3.0f/4.0f));
        physicsWorld.registerPhysicsConnector(new PhysicsConnector(wheel2, wheel2body, true, true));

        RevoluteJointDef frontWheelRevoluteJointDef = new RevoluteJointDef();
        frontWheelRevoluteJointDef.initialize(wheel1body, miniRect1Body, wheel1body.getWorldCenter());
        frontWheelRevoluteJointDef.collideConnected = false;

        RevoluteJointDef rearWheelRevoluteJointDef = new RevoluteJointDef();
        rearWheelRevoluteJointDef.initialize(wheel2body, miniRect2Body, wheel2body.getWorldCenter());
        rearWheelRevoluteJointDef.collideConnected = false;
        rearWheelRevoluteJointDef.motorSpeed = 2050;
        rearWheelRevoluteJointDef.maxMotorTorque= 3580;
        physicsWorld.createJoint(frontWheelRevoluteJointDef);
        Joint j = physicsWorld.createJoint(rearWheelRevoluteJointDef);

        rearWheelRevoluteJoint = (RevoluteJoint)j;

        r1body.setBullet(true);
        r2body.setBullet(true);
        r3body.setBullet(true);
        miniRect1Body.setBullet(true);
        miniRect2Body.setBullet(true);
        rectBody.setBullet(true);

```

at low speeds, it's OK, but on high speed vehicle can even flip around on flat ground..

Is there a way to make this work better?

# Answer
> 1 votes
Simulation of joint in AndEngine is so much poor as per my experience also. You have to use wheel joint for designing any vehicle. I know your next question. you found wheel joint implementation in RealMayo's Box2d Extension

So you have to simulate single joint only so all over performance become good. Also you can apply suspension and all other attribute to you vehicle using wheel joint.

You have to implement following two steps also for better physics implementation.

1. Use FixedStepPhysiscsWorld with allow sleep attribute value set to false. Render world with 60 fps.
2. Use FixedStepEngine instead of normal engine. Render engine also with 60 fps.

Above all suggestions are important as per my review. I hope work for you also.

---
Tags: box2d, andengine
---


# Question
Title: Point Sprites vs Textured Quads in Open GLES 2.0
I'm wondering what would perform better, point sprites (GL\_POINTS) or regular sprites (GL\_TRIANGLES). Here's the scenario:

I am developing a simple particle system to allow me to produce various effects like fire (in a very simple way). Each particle will be rendered using a texture, but the rub is I want different textures depending on the "age" of the particle (imagine a fire particle transitioning from a "burning" style texture to a "smoke" style texture).

As I understand it if I use point sprites I would have to bind different textures during the lifetime of the particle set based on the age of the various particles still alive. That is, as many texture bind operations as there are "stages" for a particle (at most).

Conversely if I use regular sprites I can do a single bind of an atlas then just render away.

I'd also "like" to be able to rotate the particles, but that's probably not a deal breaker if the performance gain for point sprites is significant. I would definitely want to scale, but I'm assuming I can do that by changing the point size... not sure what the max is for that.

My sense is that a few additional texture bind operations is going to have less of a performance impact than drawing 4 times the number of vertices (4 verts per sprite vs 1 per point). Of course there'd also be an additional sort operation in the point sprite approach so I can batch up the particles with the same texture, but again that shouldn't be too heavy if there are only 3-4 states per particle.

I'm developing for mobile (Android/iOS) so chipset will vary (not sure how much impact that will have on the decision).

Now the "right" thing to do would be to implement both and test, but that sounds like way too much hard work ;)

Would I be correct in assuming point sprites are still the better approach?

# Answer
> 1 votes
With point sprites you have to obey the max point size supported by your implementation, which may be a lot smaller than you'd like - this will become particularly noticeable if particles ever need to get close to the viewpoint.

The attenuation formula used, while logical, may not give you good results either.

On the other hand there is the tradeoff of a much smaller vertex submission.

That's not the full story though, as those texture changes are going to impact performance quite badly. Not from the changes themselves, but from reducing your batch size. You'll find that the number of draw calls used will hugely increase, which is exactly the kind of thing no GPU likes.

So there is no perfect solution and either approach involves accepting some overhead thst doesnt exist in the other.

If it were me I'd do the textured quads and see how much of an impact those extra vertices *really* have. I suspect that they may be the more acceptable tradeoff.

# Answer
> 2 votes
The downside with point sprites - I recently learned \- is that they are viewport clipped by their centres. Yet I've been using them for fire particle effects etc for a long time and it I had *never* noticed! So how big a downside is up to you.

I've asked similar questions before and have since got a system going that I'm happy with. Here's my thoughts and recipe:

The problem with opengl-es - presumably a constrained environment - is the cost of uploading new data every frame. And quads are a lot more data. You may have `gl_VertexID` and `glVertexAttribDivisor` to mitigate this but I've never had an environment with them.

The key way to minimise data transfer is to do as much procedurally as possible. For example, I have a fire system that uses a random number generator so the state is actually passed in as just a handful of uniforms! I create a single buffer of random numbers, from one to max-particles. I *reuse* this same buffer for all particle systems. I then have a single random seed per individual particle system, and I combine this with the per-point random number to give each particle in each system its own state - from speed and size to position and direction and so on. I then just have to pass in the time as a float...

Now to talk about the textures:

When you draw the fragment itself in the fragment shader you get any per-vertex info your vertex shader has passed in a `varying` as well as the point's `gl_PointCoord`. So you can easily incorporate rotation of a texture into the fragment shader.

And you should put all the various animation frames or font glyths or icons or whatever into the same texture - a *texture atlas* \- and simply pick the sub-part of the texture to draw in the fragment shader based on values passed from attribute via varying.

For example, imagine you want to write some text. So you have a big texture with the letters alphabet on. Then you have a vertex attribute of the position (`vec2`) on the screen, and the character to draw. If you arrange your font glyths in a 2D array, say 16\*16 slots, it'd be trivial to pass the character to draw as a byte! If you have more code-points (unicode etc), or want to do tighter packing, and so on, it might be easier to actually pass in the sub-rect in the texture to use as a `vec4`. So you can write text on the screen using just a handful of bytes per character and point sprites.

---
Tags: sprites, opengl-es
---


# Question
Title: Difference between Decision Trees & Behavior Trees for Game AI
What are some differences between Decision Trees and Behavior Trees for AI Game Development? For what applications would you use one over the other?

# Answer
> 96 votes
The two are pretty different. The real indicator is in the names. Decision trees are just for making decisions. Behavior trees are for controlling behavior. Allow me to explain. A major difference in the two is the way they are traversed, likewise the way they're laid out and the node 'types' are different.

**Decision trees** are evaluated from root to leaf, every time. For a decision tree to work properly, the child nodes of each parent must represent all possible decisions for that node. If a node can be answered "Yes, No, Maybe", there must be three children, Yes node, No node and Maybe node. This means there's always some lower node to traverse, until reaching an end node. The traversal is always down. Graphical form:

Pretty simple. We start at the root, and based on some evaluation, choose 1, 2 or 3. We choose 3. Then we do some other evaluation and choose B or B... Well I reused the graphic from below, sorry. Pretend the B on the left is magic B.

**Behavior trees** have a different evaluation. The first time they are evaluated (or they're reset) they start from the root (parent nodes act like selectors) and each child is evaluated from left to right. The child nodes are ordered based on their **priority**. If all of a child node's conditions are met, its behavior is started. When a node starts a behavior, that node is set to 'running', and it returns the behavior. The next time the tree is evaluated, it again checks the highest priority nodes, then when it comes to a 'running' node, it knows to pick up where it left off. The node can have a sequence of actions and conditions before reaching an end state. If any condition fails, the traversal returns to the parent. The parent selector then moves on to the next priority child. I'll attempt a graphical form here:

The traversal starts at the root, goes to child 1, checks the child condition (something like "any enemies near by?"). The condition fails, and the traversal moves back up the tree to move on to node two. Node 2 has an action that's performed (maybe something like finding a path). Then a behavior (something like following the path). The following path is set to running and the tree returns its state as running. The nodes that failed or completed are returned to 'Ready'. Then the next time we check, we start again with the highest priority node. It fails again, so we proceed to node two. There we find we have a behavior running. We also find the behavior has completed, so we mark it completed and return that. The tree is then reset and ready to go again.

As you can see the behavior trees are more complex. Behavior trees are more powerful and allow for more complex behavior. Decision trees are easy to understand and simple to implement. So, you'd use behavior trees when you want more complex behavior, or more control over the behavior. Decision trees can be used as part of a behavior tree, or used alone for simple AI.

Some good understanding of how behavior trees are parsed can be found here.

---
Tags: architecture, ai, behavior-tree
---


title: Can "dumbphones" play JavaScript games?

text:
# Question
Title: Can "dumbphones" play JavaScript games?
Are JavaScript games exclusive to modern smartphones, or are older phone models also able to play games written in JavaScript?

# Answer
> 4 votes
If the cellphone has a JavaScript interpreter or web browser built in, it is possible but not likely. Most non-smartphones don't come with necessary software especially not the phones of yesteryear.

It's more common for older models to come with Java, which will allow you to run applications based on that platform.

All in all, you can definitely find "dumbphones" that will run JavaScript today so I wouldn't say they're exclusive to smartphones.

# Answer
> 2 votes
Definitely it just depends on what version of html your game is written in and what your phones browser/interpreter will support

# Answer
> 1 votes
I have only tested on my own Samsung B2700, which is a relatively new dumb-phone, other phones may provide different results.

### The issue:

Basically almost any reasonably new phone, even a cheap one, is a pretty decent computer, it can run a browser, it can draw 2D graphics in real time, and do a lot of other stuff. Thus there is no doubt that the hardware is capable of running games, if such phones are incapable of running JavaScript games it must be because the phone has a poor or lacking JavaScript implementation. There are two issues that seem likely to arise:

1. The browser doesn't run JavaScript at all.
2. The JavaScript implementation lack a proper routing of keyboard input.

### Testing my own phone:

My phone seems capable of basic dom manipulation (and thus it does run JavaScript), and it generates standard events when the 12 keys on the numeric keypad are pressed. It also seems reasonably responsive on my simple test page, but I don't know how good the performance is. In any case the graphics quality is heavily limited by small low-res screen.

While it is hard to judge the viability from my simple test I have no doubt that a simple Tetris clone or similar is at least possible, and it would probably play reasonably well.

I made the following page to test keyboard input, it is blank when loaded, but should fill basic information about keyboard events on the screen as the keys are pressed: http://ebusiness.hopto.org/phonetest.htm

---
Tags: javascript, mobile, compatibility
---


# Question
Title: Are commercial javascript games sensible?
So I love javascript as a language and how it is able to be run anywhere. I'm gonna enumerate my concerns:

Does it make sense to make money from javascript? I mean, the second I publish my game online, people can download it, and post it on their own site and put their own ads into the game. There are rumors that Facebook is working on an HTML5 platform. Still, even if you require the use of secret keys with your online part of the game, people can still just download the source code and implement their own online version. It's a little inconvenient, but the game itself didn't lose any value. They just need to build their own community now - which should be easy with a great game. I don't have a smartphone, can someone explain if it's possible to view the source if I publish my game as a javascript application? (maybe it's wrapped into native code by the marketplace, I would appreciate the information)

I know Flash is somewhat similar, but it's my understanding that good obfuscators can effectively make the source code so ugly that it would be a mountain of work to modify. Native games can be cracked too of course, but that doesn't mean they have the source code. They'll still rely on my online part and my updates to the game.

Tell me I'm not paranoid :) How can someone justify spending resources on a javascript game?

# Answer
> 10 votes
**Does it make sense to make money from JavaScript?**

Yes.

If you can write a game (or nifty tool, etc.) using the programming language that you prefer, and it becomes popular enough that you can get users to pay for subscriptions and/or click on banner ads (or be financially beneficial to you in some other way such as by selling licenses to re-use your source code), then you'll have succeeded.

Perhaps the question you might want to ask though is "Is it possible?" which is where the "popular enough" aspect comes into play. It really boils down to what your potential customer base likes (in this case, the people playing your game), and if they really like your game then you have one of the more important elements to make it possible to turn it into a success (other elements would be the offset of operational costs such as server hardware and bandwidth, or hosting costs, support staff costs {if you end up needing support staff}, etc.).

**Technological challenges**

One of the problems with JavaScript programming is that each web browser implements it a little bit differently (and then there's one, which I shall not name, which implements it so differently that developers regularly have to code special work-arounds that are used conditionally based on whether the user is using that web browser).

Although most of these work-arounds are very well-known, they do come with the burden of needing more development resources (such as more time for testing with all the major web browsers). *Note: I'm not trying to discourage you, I just want to make sure you are aware of this common problem before your start.*

Of course, each language has its challenges, so you may benefit from spending a bit of time researching the "pros and cons" of the various languages available before making your decision.

**Source code obfuscation**

Although obfuscation may seem to be a popular move, if you really are worried about this then perhaps JavaScript isn't the right language to use -- you may need to evaluate other options where the source code gets compiled into some form (such as Java's byte codes or a native executable for the target Operating Systems you're interested in).

Also, when it comes to source code obfuscators, there are also de-obfuscators which can aid significantly in the reverse-engineering process, so you may find that obfuscation doesn't actually provide as much protection as you're hoping for (and it could very well be a wasted effort for the most part). What obfuscators can sometimes provide is a bit of optimization in that variable names are shortened (so the JavaScript interpreter has a few less characters to sift through), but on the client-side this may not be very noticeable.

One aspect to consider as well is that if you are constantly updating your JavaScript code, copying could prove to be a lot of work for a third party because they'd always be having to keep their copied system up-to-date, especially when major changes are introduced.

If your server is making all the decisions, then only the client-side of your source code would be available to the general public, so it might not really matter since it's the server that would be running the majority of the really important code anyway.

**Flash vs. JavaScript**

Flash and JavaScript are generally focused in different directions, although either one can often be used for many of the same tasks. Of course, when it comes to the need for fast graphics, Flash is usually the more suitable choice between these two; if your game doesn't require the type of fast graphics that Flash is well-suited for, then I certainly don't see why you couldn't use JavaScript without much trouble.

Take a look at http://maps.google.com/ for one example of JavaScript being used in a graphics-heavy client-side application -- it uses JavaScript (and more specifically AJAX) to essentially download tiles that are pieces of photographs of the Earth that previously came from orbiting Satellites, and lets the user use the arrow keys *and* the mouse to navigate in various ways. If this kind of performance will suit your game design needs, then it may make JavaScript a more viable choice for you.

**Paranoia**

You're not paranoid. There, you've been told what you wanted to be told. =)

**Justify spending resources**

Open source isn't the only consideration...

When it comes to spending money, a business plan can be very helpful -- understanding your market (potential customer base, competitors, etc.), your budget (costs for equipment, services, marketing, sales projections, etc.), your eventual staffing requirements (developers, artists, technical support, accountants, etc.), etc., can be very helpful, especially if you're serious about making a business out of this.

For every investment, there's always a risk somewhere (although the risks aren't always apparent, so investors may identify different risks). The bottom line is that investors expect a profitable return on their investments, and so they'll want \[at least some\] assurance that you can overcome the risks.

# Answer
> 3 votes
You are paranoid.

There is such a thing as copyright, which means that people stealing your application are eligible for being sued. It's not really different from other programs.

# Answer
> 2 votes
It is definitely feasible to develop and monetize a product built on JavaScript. It is a widely used and supported language which makes it easy to scale and cost effective.

Also do note that JavaScript can be run server side, so your logic does not have to be exposed. Consider Node.js

---
Tags: javascript, commercial
---


# Question
Title: How can I log key presses in Game Maker?
I'm trying to create a log of a players actions as they play a game of Spelunky. The easiest I've found to do this is to log what keys are pressed at each frame. What I don't know how to do is how to integrate this with the Game Maker source code of Spelunky.

Is there a specific way to create a script that is checked every frame/tick (don't know the right term) and a command to find what buttons are pressed?

# Answer
I would store the keys and times as two ds\_lists.

Create an object and call it keyLogger (or whatever). In the create event, create two lists:

```
keyCodes = ds_list_create();
keyTimes = ds_list_create();
frame = 0;

```

Then, in the step event, you can log the keys and advance time.

```
if(keyboard_check_pressed(vk_anykey))
{
    ds_list_add(keyCodes, keyboard_key);
    ds_list_add(keyTimes, frame);
}
frame += 1;

```

You can then draw all the keys in the draw event.

```
var i, s;
for(i = 0; i < ds_list_size(keyCodes); i += 1)
{
    s = "At frame ";
    s += string(ds_list_find_value(keyTimes, i));
    s += " you pressed key ";
    s += chr(ds_list_find_value(keyCodes, i));
    s += " (Code: ";
    s += string(ds_list_find_value(keyCodes, i));
    s += ")."
    draw_text(4, 4+i*20, s);
}

```

All you need to do is put this object in any room that you want to log keys in.

It should give an output that looks like this:

> At frame 159 you pressed key F (Code: 14).
>
> At frame 232 you pressed key 7 (Code: 95).
> 6 votes

# Answer
What might Be even simple but it could go bad, is if you logged the x and y of the character and stored then in a 2d array \[frame,x or y Boolean value\] then just repeat the sequence
> 0 votes

---
Tags: game-maker
---


# Question
Title: Behavior Trees :: Actions That Take Longer Than One Tick
From what I understand on Behavior Trees, each Behavior should be a short goal oriented Action that could be done in a few iterations.

**So for example, below is an image of a Behavior Tree:**

Now let us assume that the **Drive To Enemy** behavior takes more than a few iterations in the tree. So on each pass **Drive To Enemy** is called because it is now in the *running* state.

The problem is I want to call **Evade Enemy** if an Enemy is nearby. And considering that **Drive To Enemy** is always called I never get a chance to call **Evade Enemy** (*Should probably be called Avoid Enemy*).

* Should I traverse the Tree *EACH* pass no matter what Action is currently running?
* Am I going about this the right way?
* What is the proper way of handling such a behavior?

---

*Originally asked on Stackoverflow. Thought here would be a more appropriate place to ask this question.*

# Answer
See the image I provided in my previous answer:

If you imagine that node 1 is 'Evade Enemy' and node 2 is 'Chase Enemy', you'll see that even though in the second iteration (when everything is green except for '2' and 'B' is when the second iteration starts), 'Evade Enemy' still gets checked first. Only when 'Evade Enemy' fails, because there are no enemies near by, is 'Chase Enemy' activated again. When 'Chase Enemy' is visited again, it notices that it's in the 'running' state and skips directly to 'B'.

This means that every time the tree is checked, it will always traverse left to right. Even when a node is marked as running, the higher priority nodes are still checked first.

I'm not sure if you're meaning to process your nodes from right to left, but that's how you appear to have them arranged (i.e. under evade enemy, locate enemy is on the right of drive in opposite direction). If you need further explanation, you should ask in chat or in one of your existing questions on the topic.
> 17 votes

---
Tags: ai, game-loop, behavior, behavior-tree
---


# Question
Title: How to rotate one object around another moving object in 3-d?
i was wondering if anyone could give me some advice on how to rotate one object around another moving object. After a bit of googling i found some code on another website that worked perfectly but it would only work on staitionary objects. The code that i used:

```
Vector3 temp = objectPosition - objectToRotateAboutPosition;
temp = Vector3.Transform(temp, Matrix.CreateRotationX(angle));
objectPosition = objectToRotateAboutPosition + temp;

```

It works perfectly on the staitionary object but on a moving object it seems to object that is orbiting the main object seems to distance itself a great distance before it returns to the original position. I was wondering if anyone knew a way that i could tweak this code blocka and make it work, or maybe a different way to rotate one object around a moving object.

# Answer
> 0 votes
That is good code for doing the orbit. It can be shortened to the following line but probably wont have a perf increase:

```
objectPosition = Vector3.Transform(ObjectPosition - objectToRotateAboutPosition, Matrix.CreateRotationX(angle)) + objectToRotateAboutPosition;

```

Now about the dynamic of the orbit center being in motion. After completing your code snippet there, simply move the orbiting object the same as the orbit center is has moved.

```
//after your snippet
orbitCenterChange = thisFrameObjectToRotateAboutPosition - lastFrameObjectToRotateAboutPosition;
objectPosition += orbitCenterChange;

```

Or, if you don't keep track of last frame's position but you have a velocity vector for the object you are orbiting around:

```
//after your snippet
objectPosition += orbitCenterVelocity * dt;

```

# Answer
> 0 votes
Translate the "other" object to the origin. Do the rotation. then Translate back.

---
Tags: 3d, rotation, linear-algebra
---


# Question
Title: GLSL Motion blur on mobile.. possible at acceptable framerates?
I have been struggling to implement a simple linear motion blur effect on mobile (Android, OpenGLES 2.0) but it just seems to destroy my framerate.

I'm rendering to texture (FBO) then applying a fragment shader with a blur function that looks like this (with just some hard coded values for testing):

```
vec4 motionBlur(sampler2D color, vec2 uv, float intensity)
{
    vec2 speed = vec2(0.05, 0.0);
    vec2 offset = intensity * speed;
    vec3 c = vec3(0.);
    float inc = 0.1;
    float weight = 0.;
    for (float i = 0.; i <= 1.; i += inc)
    {
        c += texture2D(color, uv + i * offset).rgb;
        weight += 1.;
    }
    c /= weight;
    return vec4(c, 1.);
}

```

Called with (for example):

```
gl_FragColor = motionBlur(u_Texture, v_TexCoordinate.xy, 0.2);

```

This sends my frame rate from 60fps to 5fps.

Is this even plausible on a mobile device? I have a 2012 Galaxy Nexus (PowerVR SGX540 GPU).

I'm wondering if it's just too much for a little mobile, or whether I'm doing something stupidly wrong in the shader.

Any ideas? Anyone successfully implemented a motion blur on mobile?

# Answer
So it looks like the cause of this is simply a limitation in the PowerVR GPU used by this, (and many other) devices.

From the "POWERVR Post Processing Effects Development Recommendations"

> It is important that the texture coordinates, which are required for the texture lookups in the pixel shader, have to be calculated in the vertex shader or have to be passed as uniform shader variables in order to avoid dependant texture reads. Although these are supported, they incur a substantial performance hit. Doing no dependent texture reads means that the texture sampling hardware can fetch the texels sooner and hide the latency of accessing memory.

So it looks like the texture coordinates for the blur need to be pre-calculated in the vertex shader and passed to the fragment shader. Not sure exactly how to do this, but I'll give it a go.
> 2 votes

# Answer
That shader you have is pretty simple so I would be surprised if the framerate tanked that hard, maybe its the use of a FBO that is problematic. What happens to your FPS when you let this motion blur shader just output the input color?

A good tip to speed up your motion blur is to use the GPU to generate a mipmap chain of the texture to sample from a lower resolution version of the texture (aka FBO). This gives your really inexpensive blurring. You can keep some high level details by blending this with the original value of that texel before motion blur.
> 0 votes

---
Tags: android, opengl-es, glsl, blur
---


# Question
Title: Problem reseting device when using render target
How can I reset the device when I am rendering to a surface, and then stretching that surface to the back buffer. If i don't change the render target everything goes well, but when i change the render target(only once when the game starts), i get `D3DERR_INVALIDCALL`. What do i have to do to stop getting this error. I've tried to set the render target back to the backbuffer, and then after resetting the device back to the surface but it didn't work.

EDIT:

```
HRESULT result;

initD3Dpp();
sprite->OnLostDevice();

device3d->SetRenderTarget(0, oldSurface);

if(oldSurface) oldSurface->release();
SAFE_RELEASE(surface);

result = device3d->Reset(&d3dpp);

device3d->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
device3d->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
device3d->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);

device3d->CreateRenderTarget(GAME_WIDTH, GAME_HEIGHT, d3dpp.BackBufferFormat, d3dpp.MultiSampleType, d3dpp.MultiSampleQuality, false, &surface, NULL);
device3d->GetRenderTarget(0, &oldSurface);
device3d->SetRenderTarget(0, surface);

sprite->OnResetDevice();

return result;

```

# Answer
> 0 votes
From the D3D documentation for SetRenderTarget:

> If NULL, the color buffer for the corresponding RenderTargetIndex is disabled. Devices always must be associated with a color buffer.

You don't have a colour buffer associated with your device when you're calling Reset, in other words, so Bad Things may happen.

In general your management of this seems a little screwed. You're also not saving out the original render target here; something like this seems more appropriate:

```
// when creating and after reset; this stores a copy of the original
// colour buffer so that we can restore it properly when we need to
device->GetRenderTarget (0, &savedrendertarget);
device->SetRenderTarget (0, &newrendertarget);

// when destroying and before reset; restores the original render target;
// note that we Release the saved copy *after* resetting it otherwise we'll
// leak it; assumes that we also want to Release the new one as part of
// normal operation
device->SetRenderTarget (0, &savedrendertarget);
savedrendertarget->Release ();
newrendertarget->Release ();

```

# Answer
> 0 votes
You've probably forgotten to call IUnknown::Release on the render targets. This includes your new rendertarget and the copy you've taken to restore.

Before you call reset, you are required to release all D3DPOOL\_DEFAULT resources (which includes rendertargets), so release them!

You can find all the details on msdn

You can avoid this by using a IDirect3DDevice9Ex device, but then you can't run on XP (which is probably fine these days)

---
Tags: c++, graphics-programming, directx9
---


# Question
Title: Enhancing ambient occlusion via vert colors on vertex lit scene
We have a deformable terrain surface. Initially ambient occlusion was baked, but since the terrain can deform in real time, this approach isn't practical anymore. Therefore we used vertex paint to imitate occlusion based on the angle of the surrounding terrain vertices. We will then multiply the vertex color with the terrain texture and get a relatively cheap ambient occlusion.

Below are two examples of our terrain. The second has applied occlusion based on surrounding vertices, as mentioned before. But unfortunately it seems like the lower a set of vertices is in relation to the surrounding vertices (or the tighter the crease), the darker the vertex will be.

Vertex lighting in general works, but the results aren't as good as I expect. I wonder there is any document about a similar implementation out there.

That's our terrain without additional shading.

That's our terrain with vertex color applied to simulate ambient occlusion.

# Answer
> 3 votes
Interesting question! What you're trying to do sounds a lot like SSAO, but per-vertex rather than per-pixel. The same basic approach should work - calculating the AO factor for each vertex using a formula involving the positions and normals of the neighboring vertices.

One of the more popular ways to do SSAO is Volumetric Obscurance. Geometrically, the idea is to think of a sphere centered on each vertex, and calculate the AO based on what fraction of the sphere's volume is buried under the ground. On flat ground 50% of the sphere will be buried, so there should be no AO in that case, but if greater than 50% of the sphere is buried then there should be some proportional darkening.

The neighboring vertices can be used to estimate the buried fraction by treating each one as a line sample parallel to the central vertex's normal. You can calculate the buried portion of the line sample with a little vector math, then average this over all the neighbor vertices, weighted by how long each line sample is. Something like (untested pseudocode):

```
float heightTotal = 0.0;
float heightMaxTotal = 0.0;
float radius = 1.0;  // Radius of AO sphere; tune to taste

for each neighborPos:
    float3 neighborOffset = neighborPos - vertexPos;
    float height = dot(neighborOffset, vertexNormal);
    float3 tangentProj = neighborOffset - vertexNormal * height;
    float distSqr = dot(tangentProj, tangentProj);

    float heightMax = sqrt(max(0, radius * radius - distSqr));
    height = clamp(height, -heightMax, heightMax);

    heightTotal += height;
    heightMaxTotal += heightMax;

AO = 1.0 - max(0, heightTotal / heightMaxTotal);

```

---
Tags: terrain, shading
---


# Question
Title: Dictionary of common names for code objects
I'm looking for a common dictionary of terms (much like design patterns have a common language for how things interact) that are specific to games.

For instance, if I'm making a game of pong with a high level of complexity, I want to name things accordingly.

I've seen some visual objects that a user can interact with called a **widget**, some non-interactive ones called a **doodad** (back when I played with starcraft map editor anyway). Is there a proper name for the frame rate clock? Is there a proper name for the game clock (the clock that is about the movement of objects in the world but not the visual drawing)?

I just want a dictionary so I can speak the same language and not make up things as I go. I'm concerned I'm going to create things named doodads, whosits, whatsists, and flim-flams... and I don't want to do that.

# Answer
These names vary by region, company and developer. Most of them *are* made up and are often just synonyms for "thing".

Create names that describe the purpose of the code. A frame rate clock is called a frame rate clock. There's no dictionary for these things. You can't have a dictionary if the objects you're describing don't have a firm definition. The objects used in game development change from game to game. It depends on the game being developed for what functionality needs to be implemented. The objects being created are frequently specific to that game. Just call them what makes sense.
> 17 votes

# Answer
I guess what you're asking about is a glossary for the programming side of game development. I don't think one exists, which is certainly a shame.

Incidentally, a widget is a term that has come over from GUI development. I've never heard the term doodad before in a technical context.
> 4 votes

# Answer
GPwiki had a small, non exhaustive list.
> 3 votes

# Answer
Literature might be your best source of info if you want to find the usually-accepted terms for the *things* of game development. A good reference for that might be IntroGameDev.com, this isn't a dictionary but it should give you a starting point.
> 2 votes

# Answer
For strictly UI purposes (interactive items), both Control and Widget are very common. Component is also getting popular, though that by itself is confusing for today's frequently component-based game object systems. Using classes like UIControl, or using namespaces, is a good idea to clearly identify what you mean.

For items in the game, the most general term is Game Object. These are often all Entity in code, but GameObject or even GO aren't uncommon. Game engines that are strictly 2D sometimes just call all game objects Sprite, which is a little inaccurate, but works.

Where possible, name objects based on what they are or do, not some clever short synonym. In the worst case, if you pick a bad name and are using a large-project-friendly language, it's trivial to just rename your classes and instances if you decide a name is too confusing.

Really, internal consistency in your own project is more important. So long as you use naming styles and conventions consistently, and document what the purpose of everything is, you'll be fine. It doesn't matter if you call every game object a PeaPod (obviously a dumb name) so long as you clearly document in your Getting Started manual and supporting references what a PeaPod is. So long as the name isn't outright misleading (don't call your renderable mesh object a PhysicalBody for instance as that implies physics rather than graphics).
> 1 votes

---
Tags: architecture, design-patterns
---


title: Determining which line to collide with

text:
# Question
Title: Determining which line to collide with
I am making a platformer, where my player is represented as a circle and the ground is represented as lines. The actual collision detection and resolving works, it's just an edge case I can't find a solution for.

I check on which line the hero is by using the normal, and if the hero's center is between these normals I know he is on that line. That works except for the case in the image above. When he get's in the 'Problematic Area' the algorithm will not detect any collision.

So how do I know which line to pick for the collision when the hero get's in this area?

Here is some code that shows how I test collisions (which again works, but does not consider the problem I actually have).

```
playerPointer:Vector2D = New Vector2D(position.x - line.x1, position.y - line.y1)
lineNormal:Vector2D = line.vector.Copy()
lineNormal.LeftHandNormal()
playerOnNormal:Float = playerPointer.ProjectionOn(lineNormal)
playerOnLine:Float = playerPointer.ProjectionOn(line.vector)

#Do we have a collision between the circle and the infinite line
If Abs(playerOnNormal) <= radius

  #Get the direction vector of the line
  Local directionVector:= New Vector2D(line.x2 - line.x1, line.y2 - line.y1)

  #Is the player inside the normals boundaries
  If (playerOnLine <= directionVector.Length) And (playerOnLine >= 0)

```

# Answer
> 4 votes
A circle may be a bad choice. A rectangle (AABB) allows you to more easily use SAT here, which will in this case detect the bottom edge of the AABB as the normal.

Another option is to recognize that you don't just want line collision but also vertex collision. Using Voronoi Regions, the circle is in the region belonging to the vertex joining the lines. Using the normal between a vertex and a circle will give you the vector pointing from the vertex to the circle (or vice versa) which is exactly what you want. One way to handle this is to calulcate distance to any candidate vertex, then calculate distance to lines. When doing the line distance algorithm, you generally must clamp a t value to \[0,1\]; just ignore the line if the value is outside that range. Take the shortest found distance.

Yet another option I've never seen used but might work is to see that the circle collides with both lines, take both normals, and average them together. I don't think that's the best solution, but maybe it's the easiest option for you.

# Answer
> 3 votes
Circle/line segment collision is the same as point/pill collision. A pill can be simplified as a box and two circles on the end points. Using your existing code you are only half way there. If you add point/circle collision to the line segment endpoints (and simply resolve your collision with whatever hits first) your problem goes away (as both line segments will have identical circles at that point), and you gain proper end point normals from the circle collision.

Here's a rough diagram showing what I mean. The gray lines are your original lines and the gray circle is your player's bounding circle. The collision resolution of that is equal to the black point of the circle and the black lines and circles that are extruded from the line segments that make up the box.

There's more detail in this question: A ball hits the corner, where will it deflect?

---
Tags: collision-detection
---


# Question
Title: How can tell if a player has performed some action in UDK?
For simplicity, let's say that I want bots to kill me when I enter a room without greeting them. So in this case I would need to store, somewhere, the variable `didGreet`, which should be changed when I send the message "Hello." Then, when any pawn sees me, he will check the `didGreet` variable and if this was false he would start firing at me.

I've heard that this should be done using the `GameInfo` class, but unfortunately I don't know how to create, access and change variables there. How can I accomplish this?

# Answer
> 2 votes
Is your game only going to be single-player, or are you planning to have multiple players? Since the attribute you are wanting to record is 'per player' (eg; one player greeting the bots does not mean *all* players have greeted the bots) - then this kind of variable should be stored in your `playercontroller` class. In a singleplayer game, it is quite acceptable to store such variables in your `gameinfo` class instead.

If you need to know how to do this, I recommend going through some unrealscript tutorials, there are quite a few out there! Good luck.

---
Tags: udk, kismet
---


# Question
Title: Camera frustum calculation coming out wrong
I'm trying to calculate a view/projection/bounding frustum for the 6 directions of a point light and I'm having trouble with the views pointing along the Y axis. Our game uses a right-handed, Y-up system. For the other 4 directions I create the LookAt matrix using (0, 1, 0) as the up vector. Obviously that doesn't work when looking along the Y axis so for those I use an up vector of (-1, 0, 0) for -Y and (1, 0, 0) for +Y. The view matrix seems to come out correctly (and the projection matrix always stays the same), but the bounding frustum is definitely wrong. Can anyone see what I'm doing wrong?

This is the code I'm using:

```
camera.Projection = Matrix.PerspectiveFovRH((float)Math.PI / 2, ShadowMapSize / (float)ShadowMapSize, 1, 5);

for(var i = 0; i < 6; i++)
{
    var renderTargetView = shadowMap.GetRenderTargetView((TextureCubeFace)i);
    var up = DetermineLightUp((TextureCubeFace) i);
    var forward = DirectionToVector((TextureCubeFace) i);

    camera.View = Matrix.LookAtRH(this.Position, this.Position + forward, up);
    camera.BoundingFrustum = new BoundingFrustum(camera.View * camera.Projection);
}

private static Vector3 DirectionToVector(TextureCubeFace direction)
{
    switch (direction)
    {
        case TextureCubeFace.NegativeX:
            return -Vector3.UnitX;
        case TextureCubeFace.NegativeY:
            return -Vector3.UnitY;
        case TextureCubeFace.NegativeZ:
            return -Vector3.UnitZ;
        case TextureCubeFace.PositiveX:
            return Vector3.UnitX;
        case TextureCubeFace.PositiveY:
            return Vector3.UnitY;
        case TextureCubeFace.PositiveZ:
            return Vector3.UnitZ;
        default:
            throw new ArgumentOutOfRangeException("direction");
    }
}

private static Vector3 DetermineLightUp(TextureCubeFace direction)
{
    switch (direction)
    {
        case TextureCubeFace.NegativeY:
            return -Vector3.UnitX;
        case TextureCubeFace.PositiveY:
            return Vector3.UnitX;
        default:
            return Vector3.UnitY;
    }
}

```

Edit: Here's what the values are coming out to for the PositiveX and PositiveY directions:

**Constants:**

```
Position = {X:0 Y:360 Z:0}
camera.Projection =
    [M11:0.9999999 M12:0 M13:0 M14:0]
    [M21:0 M22:0.9999999 M23:0 M24:0]
    [M31:0 M32:0 M33:-1.25 M34:-1]
    [M41:0 M42:0 M43:-1.25 M44:0]

```

**PositiveX:**

```
up = {X:0 Y:1 Z:0}
target = {X:1 Y:360 Z:0}
camera.View =
    [M11:0 M12:0 M13:-1 M14:0]
    [M21:0 M22:1 M23:0 M24:0]
    [M31:1 M32:0 M33:0 M34:0]
    [M41:0 M42:-360 M43:0 M44:1]

camera.BoundingFrustum:
    Matrix =
    [M11:0 M12:0 M13:1.25 M14:1]
    [M21:0 M22:0.9999999 M23:0 M24:0]
    [M31:0.9999999 M32:0 M33:0 M34:0]
    [M41:0 M42:-360 M43:-1.25 M44:0]

    Top = {A:0.7071068 B:-0.7071068 C:0 D:254.5584}
    Bottom = {A:0.7071068 B:0.7071068 C:0 D:-254.5584}
    Left = {A:0.7071068 B:0 C:0.7071068 D:0}
    Right = {A:0.7071068 B:0 C:-0.7071068 D:0}
    Near = {A:1 B:0 C:0 D:-1}
    Far = {A:-1 B:0 C:0 D:5}

```

**PositiveY:**

```
up = {X:0 Y:0 Z:-1}
target = {X:0 Y:361 Z:0}
camera.View =
    [M11:-1 M12:0 M13:0 M14:0]
    [M21:0 M22:0 M23:-1 M24:0]
    [M31:0 M32:-1 M33:0 M34:0]
    [M41:0 M42:0 M43:360 M44:1]

camera.BoundingFrustum:
    Matrix =
    [M11:-0.9999999 M12:0 M13:0 M14:0]
    [M21:0 M22:0 M23:1.25 M24:1]
    [M31:0 M32:-0.9999999 M33:0 M34:0]
    [M41:0 M42:0 M43:-451.25 M44:-360]

    Top = {A:0 B:0.7071068 C:0.7071068 D:-254.5585}
    Bottom = {A:0 B:0.7071068 C:-0.7071068 D:-254.5585}
    Left = {A:-0.7071068 B:0.7071068 C:0 D:-254.5585}
    Right = {A:0.7071068 B:0.7071068 C:0 D:-254.5585}
    Near = {A:0 B:1 C:0 D:-361}
    Far = {A:0 B:-1 C:0 D:365}

```

When I use the resulting BoundingFrustum to cull regions outside of it, this is the result:

```
Pass PositiveX: Drew 3 regions
Pass NegativeX: Drew 6 regions
Pass PositiveY: Drew 400 regions
Pass NegativeY: Drew 36 regions
Pass PositiveZ: Drew 3 regions
Pass NegativeZ: Drew 6 regions

```

There are only 400 regions to draw and the light is in the center of them. As you can see, the PositiveY direction is drawing every single region. With the near/far planes of the perspective matrix set as small as they are, there's no way a single frustum could contain every single region.

# Answer
This is not a direct answer to your question, but may be a possible alternative with some added benefits.

You seem to be trying to generate a frustum bounding box so you can do some frustum culling before generating each face of a cubic shadow map. If you were to switch to using dual-paraboloid shadow maps you will get a performance gain by only using 2 render calls to generate the shadow map rather than 6.

The other benefit, which relates more to the question, is that culling is now a process of detecting whether an object is at the back, at the front or intersecting the plane which divides the two hemispheres of your dual-paraboloid shadow maps.
> 1 votes

# Answer
According to the MSDN documentation, the BoundingFrustum constructor only takes Left-Handed projection matrices:

http://msdn.microsoft.com/en-us/library/windows/desktop/hh855905(v=vs.85).aspx
> 0 votes

---
Tags: directx, camera, sharpdx, frustum
---


# Question
Title: Do I have to ask for permission to use real company logos for advertising props in the world in my sports game?
I'm making a simple turn-based Android ball flicking soccer game and I was thinking of creating a theme in a sports game, like soccer for example, usually had advertisement banner on walls and a bit realistic but cartoony. It is usually encountered in most sports-based game in any gaming platform. I have a question regarding this topic. Is it required to ask a permission to used some recognized ad banner designed walls (e.g. *Adidas*, *Samsung*, *McDonalds*, etc.) to be used as props for the game field like this one for example?

# Answer
> 6 votes
Yes, you do require permission. Logos of corporations are usually trademarked, which means that they must not be used without explicit permission. Copyrights on the design of the logos also apply.

You might wonder "Why would they sue me - I am making free advertising for them". Unfortunately advertising works two-sided. When you endorse another company by advertising for them, it also implies that they endorse you. That's a marketing statement they don't necessarily want to make.

When it's just about the atmosphere, you could substitute fantasy brands or parodies of corporate logos.

Also, why would you put in corporate logos for free, when you could make some money doing so? Companies pay a lot for product placement. And when you have an elegant way to put non-obstructive advertising in you game which doesn't break but even improves immersion, why not?

# Answer
> 2 votes
As an alternative, why not use one of the android ad companies, and build their ad into the company sponsorship slots on the game fields of choice (ie banner ads incorporated into the baseball field advertisements). You could change how the field is displayed so that the ad is still at the top or bottom of the screen

---
Tags: marketing, copyright, business, trademark
---


# Question
Title: How can I control the frame update rate of a thread?
I'm building a small game for a college project. It's quite a simple game. There are a number of dots on the screen and the player has to select them in a specific order. It's kind of a "join the dots" thing, it's for my 4 year old son to play with.

So we've been pointed towards a few game tutorials by the college, I've been studying one of them, and I'm currently at this point:

http://www.javacodegeeks.com/2011/07/android-game-development-game-loop.html

However, I'm a little stuck here as this is where my app deviates from the tutorial. There is nothing moving on my screen, just pictures of dots that change colour when they are touched. At the moment I'm updating the status of each dot based on the position of the users finger relative to the dots using a switch statement in the onTouchEVent() method in my SurfaceView Class.

it looks like this:

NOTE: the method .checkCurrentStatus() updates the image on the point based on whether the point has been touched or not.

public boolean onTouchEvent(MotionEvent event){

```
Log.i(TAG, "Event: " + event.getActionMasked());

switch(event.getAction()){

case MotionEvent.ACTION_DOWN:
    sounds.play(soundDrip, 1.0f, 1.0f, 0, 0, 1.5f);
    image.handleActionDown((int) event.getX(), (int) event.getY());

    for(LetterPoint p : capitalA){

        p.handleActionDown((int) event.getX(), (int) event.getY());
        Log.i(TAG, "Set state of point " + p + " 'isTouched()' to " + p.isTouched());
    }

    if(event.getY() > getHeight() - 50){
        gameThread.setRunning(false);
        Activity activity = (Activity) getContext();
        activity.finish();

    }else{
        Log.i(TAG, "Co-ordinates: x= " + event.getX() + " y= " + event.getY());

    }
    break;

case MotionEvent.ACTION_MOVE:

    for(int i = 0; i < capitalA.length; i++){
        capitalA[i].handleActionDown((int) event.getX(), (int) event.getY());
        Log.i(TAG, "Set state of point " + i + " 'isTouched()' to " + capitalA[i].isTouched());
        capitalA[i].checkCurrentStatus();

        if(i != 0){

            if(capitalA[i-1].getCurrentState() == LetterPoint.status.green){

                capitalA[i].setCurrentState(LetterPoint.status.orange);
                capitalA[i].checkCurrentStatus();
                Log.i(TAG, "Set state of point " + i + " to " + capitalA[i].getCurrentState().toString());
            }
        }

        if(capitalA[i].getCurrentState() == LetterPoint.status.orange && capitalA[i].isTouched()){
            capitalA[i].setCurrentState(LetterPoint.status.green);
            capitalA[i].checkCurrentStatus();
            if(!capitalA[i].isCorrectPlayed()){
                sounds.play(soundCorrect, 1.0f, 1.0f, 0, 0, 1.5f);
                capitalA[i].setCorrectPlayed(true);

            }
            Log.i(TAG, "Set state of point " + i + " to " + capitalA[i].getCurrentState().toString());
        }
    }
    break;

case MotionEvent.ACTION_UP:

    int count = 0;
    for(LetterPoint p : capitalA){
        if(p.getCurrentState() == LetterPoint.status.green) count++ ;
        Log.i(TAG, "Green count is: " + count);
    }

    if(count == capitalA.length){
        sounds.play(soundWin, 1.0f, 1.0f, 0, 0, 1.5f);

    }else{
        sounds.play(soundLoose, 1.0f, 1.0f, 0, 0, 1.5f);
        for(int i = 0; i < capitalA.length; i++){

            if(i < 1){
                capitalA[i].setCurrentState(LetterPoint.status.orange);
            }else{
                capitalA[i].setCurrentState(LetterPoint.status.red);
            }
            capitalA[i].setTouched(false);
            capitalA[i].checkCurrentStatus();
        }

    }

    break;
}

```

So given that all my updating is handled in the onTouchEvent() method how can I best control the frame rate of the thread? Should I just store the variables for each touch point in the SurfaceView class on every touch event then update the SurfaceView periodically from a separate update method called by the Thread? EDIT: Also, where should I call the sound effects from? the Switch statement above? the update method? the thread when I'm drawing?

# Answer
> 0 votes
If you don't have any animations that run on their own and the game is controled by finger touch alone then you don't need a thread but just update the Canvas of the SurfaceView on every touch event by calling a method:

```
  //draw screen without a thread
  public void drawScreen(){
    if (holderUI == null) return;
        try{
            cm = holderUI.lockCanvas();
            synchronized (holderUI) {
                onDraw(cm);
            }
        } finally {
            if (cm != null) {
                holderUI.unlockCanvasAndPost(cm);
            }
        }
}

```

# Answer
> -1 votes
it might help if somewhere you use Thread.Sleep(no of milliseconds). This will cause the code to stop for n amount of time. You can still run other classes while sleep is... sleeping.

---
Tags: android, animation, multithreading
---


# Question
Title: How to obtain a pointer to the compiled shader in D3D11
My shader creation code looks like this.

```
std::shared_ptr<IRenderUtility::IVertexShader> D3D11RenderUtility::CreateVertexShader(IShader::INIT_DESC & desc) const
{
    HRESULT result;
    ID3D10Blob * errorMessage;
    ID3D10Blob * vertexShaderBuffer;
    ID3D11VertexShader * vertShader;
    D3D11VertexShader::INIT_DESC vertShaderDesc;
    char errorMsg[255];

    result = D3DX11CompileFromFileA(desc.fileName.c_str(), NULL, NULL, desc.entryPoint.c_str(), "vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBuffer, &errorMessage, NULL);
    if(FAILED(result))
    {
        if(errorMessage)
        {
            OutputErrorBlob(errorMessage, desc.fileName.c_str());
        }

        sprintf_s(errorMsg, "D3D11_Renderer | D3D11RenderUtility::CreateVertexShader \n\tfailed to compile shader file %s %i", desc.fileName, __LINE__);
        throw std::exception(errorMsg);
    }

    result = m_Device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &vertShader);
    if(FAILED(result))
    {
        sprintf_s(errorMsg, "D3D11_Renderer | D3D11RenderUtility::CreateVertexShader \n\tfailed to create the vertex shader %i", __LINE__);
        throw std::exception(errorMsg);
    }

    vertexShaderBuffer->Release();
    vertexShaderBuffer = 0;

    vertShaderDesc.shader = vertShader;

    return std::shared_ptr<IVertexShader>(new D3D11VertexShader(vertShaderDesc));
}

```

IRenderUtility, D3D11RenderUtility, IVertexShader, D3D11VertexShader, and IShader are my stuff. My question only pertains to the Shader creation code. At a later point, after the shader is made, i would like to create an input layout, but without the blob to get a pointer to the compiled shader, i cannot. Is there any way to obtain a pointer to the compiled shader from ID3D11VertexShader after it is created, or should i keep the blob around, storing it in my VertexShader object? How big is it?

# Answer
> 2 votes
In general, and because vertex shaders and input layouts are so tightly coupled, I prefer to create both at the same time, i.e. something like this (not the exact code, just for illustration):

```
HRESULT CreateVertexShaderAndInputLayout (ID3D11VertexShader **vs, ID3D11InputLayout **il, otherParams...)

```

This ensures that your layout is valid for the shader and that you have no blobs left hanging around that you may forget to Release. It comes at the expense of potentially having multiple duplicate input layouts, of course, but I don't consider it that big a deal.

Another option is to use shader reflection to get at the vertex shader input, but that of course won't get you the per-instance attributes of the layout, if you use them, so I don't consider it viable.

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