# Question
Title: Fast 2D collision detection in an unbounded space
I'm trying to do collision detection on a large number of entities of greatly varying size in an unbounded space. The entities are circles, so it's relatively easy to check if two are colliding. However, with a large number of entities the simulations slows down a lot when I code it to check every entity against every other (for n entities, I believe it is n\*(n-1)/2 checks, way too many!) Here's my though process so far:

First, I considered using a grid of some sort, like described in steps 1-2 of the answer here: Fast, accurate 2d collision

There are, however, a few problems with this:

1) It is an unbounded space. Where do I start and end the grid? How do I determine the size of each square in the grid in a world where some objects are literally ***tens of millions*** times larger the other objects?

2) Even if I somehow manage to adjust the size of the grid every frame without using too much processing power, so that it adjust to fit the most distant objects, (unlikely that I could do this efficiently) this is still not a solution. If tons of objects are clustered in a 10,000x10,000 space, and one object goes shooting off into space 100 billion units of distance away, the grid would "zoom out", leaving all of the objects in the smaller 10,000x10,000 space in one square, which would defeat the purpose of making a grid in the first place.

For these reasons, I'm thinking that a simple grid is not the best idea...

I looked at BSP's, and I admit that I don't fully understand the concept, but it seems like it does not apply well to my situation (especially since I am using circles and BSP seems better suited to a more complicated polygonal world).

Quad trees seem promising (something like this perhaps: http://www.youtube.com/watch?v=qJJnzSLrC1E) but I foresee at least two potential issues:

1) I can calculate the "farthest away objects" each frame to give calculate GreatestXValue, LeastXValue, GreatestYValue, and LeastYValue, for each frame. From that I have a rectangle to work with that contains all entities. However, I will have to redo this each frame, which means that I have recreate the the entire quadtree each frame: no shortcuts on calculations done in previous frames. Is this a problem or do most game/simulation programmers have to completely recreate the quadtree each frame anyway?

2) (Probably the bigger problem) How do I handle a massive object in the vincinity of many small objects? Think about many circles with radius 5 being very close to, resting against, or colliding with a circle with radius 100,000. That massive object will be in many, many grid squares, and it seems to me that the situation would force the creation of a tree that is far too broad and deep.

Am I on the right track with my thought process? Where do I go from here? Thank you very much for your time and help!!

# Answer
Sorry it's been so long; I forgot to come back and answer the question. Fixed grid with hashtable was a really good explanation, and I really appreciate the time and help, but it doesn't work as well for a world where the bounds are changing. (keyword here is *fixed*, this is an unbounded space so it is incompatible unless if I misunderstood the concept).

I ended up going with quadtrees. To answer my concerns above:

1) You pretty much have to recalculate the whole tree anyway on each timestep.

2) A large object does NOT go into many small squares. Instead, it resides in the smallest higher node (i.e. bigger square) that it can completely fit into. You wouldn't want to have to create thousands of small nodes just because you have one massive object!

Once the tree is created, for collision, when you are looking at object X, you check X not only against other objects in it's node, but against all objects in all nodes "below" it (i.e. all objects in smaller squares that are contained by X's larger square). (You can also check up the tree instead of down of course, I just chose to check down rather than up)
> 1 votes

# Answer
You are on the right track, but you didn't reach your goal, well let me explain

## Spartial schemes

**Fixed grid with Hashtable**

The solution to your first problem is a spartial hashing scheme, you divide your world space into a grid *but* you save the content of the grid elements in a hashtable. The index for the hashtable is calculated from the address of the grid element.

For example

```
Index = xOffset + 5*yOffset

```

(note the prime, its important)

You also need to check non empty grid elements against their neightbors.

A way to reduce the calculation time for the collision detection phase is to check only against neightborcells in one direction, a image says more than thousand words:

unoptimized detection scheme:

```
 | C | C | C
 +---+---+---
 | C | X | C
 +---+---+---
 | C | C | C

```

Optimized detection scheme:

```
 |   |   |
 +---+---+---
 |   | X | C
 +---+---+---
 |   | C | C

```

X : grid element against which to check collisions with...

C : collision grid element

So you save more than half of the checks. This works also in 3 dimensions.

---

To use the **Fixed grid with Hashtable** scheme with very large/very small objects you basically do have two choices:

1. make the grid element size as large as the biggest object
2. use a space division scheme for the grid elements which are stored in the hashtable, i illustrate it with a picture:

```
|       |   |   |        |
|       +---+---+        |
|       |   |   |        |
+-------+---+---+--------+
|       |       |        |
|       |       |        |
|       |       |        |

```

the cells with large elements are not subdivided and the cells with small elements are subdivided.

This is actually a combination of the hashing scheme and the spartial subdivision scheme and combines the advantages (and disadvantages).

For more information of collision detection algorithms you can also check out these questions
> 1 votes

---
Tags: collision-detection
---


# Question
Title: Orbiting a camera around the Y axis whilst remaining up
I've been having difficulty with a problem which I thought was going to be a simple solution.

I have a camera facing downwards on a character. The can camera be lowered and when it's lowered it remains the same distance away from the character that it was (basically rotating around the X axis of the target). Now what I want it to be able to do is spin around the character on the Y axis as well, but to maintain the same distance and to remain upwards all the time. The problem I'm having is that if I do something similar to the way I did it on the X axis everything becomes a mess. First of all it doesn't remain facing up, as it spins the camera ends up upside down and i'm not really sure how to recalculate the up vector for it. But ontop of that it doesn't maintain the same distance from the character at all times.

This is what I have right now:

```
        cameraUp = new Vector3(0, 1, 0);
        cameraPosition = new Vector3(cameraOffset.X, cameraOffset.Y, cameraOffset.Z);
        cameraPosition = Vector3.Transform(cameraPosition - cameraTarget, Matrix.CreateFromAxisAngle(Vector3.UnitX, tippingAngle)) + cameraTarget;

//This is the part that I'm having difficulty with, the rest works fine.
        cameraPosition = Vector3.Transform(cameraPosition, Matrix.CreateFromAxisAngle(Vector3.UnitY, rotationAngle));

        view = Matrix.CreateLookAt(cameraPosition, cameraTarget, cameraUp);

```

EDIT:

Thank you to everyone, all of your comments helped. The biggest issue was that somehow I let it slip past that the cameraUp value was wrong, I think it happened as a typo when I was tidying the code up. Anyway, after fixing that the code above was exactly what I needed. I had tried that before but because the up vector was wrong I was getting really weird results so thanks to everyone. :)

# Answer
> //This is the part that I'm having difficulty with, the rest works fine. cameraPosition = Vector3.Transform(cameraPosition, Matrix.CreateFromAxisAngle(Vector3.UnitY, rotationAngle));

Yes, I can see the problem. On this line, you are orbiting the camera's position around the world origin instead of the center of your arc's sphere (which is your camera target). You need to translate the position/target system to the world origin, do the rotation, then translate them back like you did in the first rotation to set the pitch.

try this:

```
//This is the part that I used to have difficulty with, but now works fine.
        cameraPosition = Vector3.Transform(cameraPosition - cameraTarget, Matrix.CreateFromAxisAngle(Vector3.UnitY, rotationAngle)) + cameraTarget;

```

Edit: Additionally, you can combine the 2 rotations into one Vector3.Transform() like this:

```
Vector3 axisAngle = (Vector3.UnitX * tippingAngle) + (Vector3.UnitY * rotationAngle);
float angle = axisAngle.Length();
Vector3 axis = axisAngle / angle;//normalizes the axis
 cameraPosition = Vector3.Transform(cameraPosition - cameraTarget, Matrix.CreateFromAxisAngle(axis, angle)) + cameraTarget;

```
> 1 votes

---
Tags: xna, camera, rotation
---


title: Movement with box2d using libgdx

text:
# Question
Title: Movement with box2d using libgdx
I am pretty new to using physics engine and would like to know what is best practice for movement of playercharacters.

Currently I have a class called Hero that has a CircleShape and when the user presses left/right/up/down it gets an linear impulse in the appropiate direction. All this works fine. The problem happens when the player does not produce any input, the shape is going further in the last direction for a long time, but I would like it if the shape stops faster. The players sees the world top down, so the worlds gravity is set to (0;0).

Maybe the whole idea of using impulses to move the character around is flawed, I would just like to know what works.

# Answer
Newtons first law of motion, simply put:

> Every object in motion will stay in motion until acted upon by an outside force.

If you want to change the motion of an object, you need to add an additional force. In this case, a stopping force. This force is in the opposite direction of your velocity, with the sole purpose of arresting that velocity.

So, you have the following criteria.

* The force can't be strong enough to reverse the velocity.
* The force is only applied when the object is in motion (or when you want to stop).

There are a few "named" forces that fit here.

* Friction. The resisting force from two solid objects moving against each other.
* Drag. Essentially friction, but with respect to an object moving through a fluid/gas.

Box2D has support for friction built into its simulation. When defining a fixture, you simply set the friction value:

```
fixtureDef.friction = 0.3f;

```

See the Box2D manual for more information (unfortunately, their manual is not really *linkable* to specific sections, so just search for "Friction is used to make objects slide along each other realistically").

Some things you'll want to think about when implementing a stopping force.

* Friction will be the easiest to "turn on" and start using, however, you'll need to increase your movement forces to overcome friction.
* Implementing your own stopping force will allow you better control, but will mean you'll need to add more of your own code.

Basically, the way you're doing things now is fine, and the results are expected. You just need to add some additional functionality to get the results you want.
> 1 votes

---
Tags: java, box2d, libgdx
---


# Question
Title: An API independent way of managing video memory?
I'm developing a game. The game architecture is very modular. I have a "Graphics Engine", which uses either a Direct3D or OpenGL renderer. However the user does not have access to the renderers directly. Instead the "Graphics Engine" class is used, which uses a renderer interface.

I also have a resource management system. As for now, the renderers are respoinsible for allocating and releasing video memory. That couples my design in a bad way, since the "Graphics Engine" has undesirable logic for transferring resources between the RAM and the VideoRam through sending signals to the "Renderer". I want the resource management system to be responsible for allocating video memory.

**I want to decouple the "Renderer" and "Graphics Engine" classes as much as possible, and make the renderer only responsible for rendering. Is there a way to obtain a universal pointer to a Video RAM buffer, and use it to render with both renderers?**

My problem is basically that I can only obtain OpenGL or Direct3D handles, which can be used only from the relevant API. And the "Graphics Engine" should not know which renderer it uses.

# Answer
> 2 votes
This is just basic abstraction. Write an API-neutral interface for buffers, textures, and so on. Either use dynamic polymorphism (abstract interfaces with virtual functions) for these or compile-time static polymophism (a shared header with some ifdefs and then link different implementations whether you're compiling for a D3D-primary platforms or a GL-only platform). A simple, very incomplete draft of doing this would be:

```
// implement this interface for each graphics API you support
class IBuffer {
public:
  ~IBuffer() {}

  virtual size_t GetByteWidth() const = 0;
  virtual void UpdateData(const void* data, size_t width, size_t offset = 0) = 0;
  virtual void* Map() = 0;
  virtual void Unmap() = 0;
};

// implement this interface for each graphics API you support
class IGraphicsDevice {
public:
  virtual std::shared_ptr<IBuffer> CreateBuffer(size_t size) = 0;
};

// creates a device as appropriate
enum class EGraphicsType { Default, Direct3D, OpenGL, OpenGLES };
shared_ptr<IGraphicsDevice> GraphicsDeviceFactory(EGraphicsType type) {
  switch (type) {
  case EGraphicsType::Default:
#if defined(HAS_DIRECT3D)
  case EGraphicsType::Direct3D:
    return std::make_shared<GraphicsDeviceDirect3D>();
#endif
#if defined(HAS_OPENGL)
  case EGraphicsType::OpenGL:
    return std::make_shared<GraphicsDeviceOpenGL>();
#endif
#if defined(HAS_OPENGLES)
  case EGraphicsType::OpenGLES:
    return std::make_shared<GraphicsDeviceOpenGLES>();
#endif
  default:
    ASSERT(!"Unsupported graphics device");
    return nullptr;
  }
}

```

For static polymorphism, get rid of the virtual calls, directly embed the `ID3DWhatever*` values or `GLint` values wrapped in an `#if defined(USE_FOO)` to select which implementation to use, and make a variety of .cpp files for each platform and either only link the ones you need or wrap their contents in more macro conditionals. For some of the last-gen consoles the static polymorphism approach could have a substantial impact on performance as their CPUs weren't as good at efficiently handling virtual table indirections, though on the PC and likely the next-gen consoles this shouldn't be much of a problem. I don't have any information on mobile platforms regarding this.

---
Tags: opengl, architecture, directx, video, memory
---


# Question
Title: Tool to convert Textures to power of two?
I'm currently porting a game to a new platform, the problem being that the old platform accepted non power of two textures and this new platform doesn't.

To add to the headache, the new platform has much less memory so we want to use the tools provided by the vendor to compress them; which of course only takes power of two textures.

The current workflow is to convert the non power of tho textures to dds with 'texconv', then use the vendors compression tools in a batch.

So, does anyone know of a tool to convert textures to their nearest 'power of two' counterparts?

Thanks

# Answer
> 3 votes
So I checked out ImageMagick, it wasn't really for me, so I ended up using TheGimp's Script-Fu to first off write a batch procedure to convert all files in a folder to the nearest (bigger) power of two, and optionally scale the image down afterwards if it is too big. This is a simplified version (I can give anyone the batch if needed).

```
(define
    (script-fu-resize-upper-pot image drawable)
    (let*
        (
            ;; Store upper power of two for height and width of image
            (height (pow 2 (ceiling (/ (log (car (gimp-image-height image))) (log 2)))))
            (width (pow 2 (ceiling (/ (log (car (gimp-image-width image))) (log 2)))))
        )

        ;; Resize the Image
        (gimp-image-resize image width height 0 0)
    )
)

```

Of course the big problem with this is that the Script-Fu command `file-glob` only allows you to cycle through one folder, and you have to use a very ugly batch call for it to work :

```
"c:\Program Files\GIMP-2.0\bin\gimp-2.6.exe" -i -b "(script-fu-resize-upper-pot-batch \"C:\\ImageData\\*.png\" 0) (gimp-quit 0)"

```

So the next problem was to iterate through the folders to call the gimp script on all of them, after a bit of testing, I found this PowerShell script :

```
Clear-Host
$Directory = "C:\PuddleSqData\"
$Dirs = Get-ChildItem -path $Directory -recurse -include * | where {$_.PsIsContainer}

$Gimp = "gimp-console-2.6.exe"

foreach($Dir in $Dirs)
{
    $SourcePath = $Dir.FullName
    $GimpifiedSourcePath = $SourcePath -replace("\\", "\\")

    $GimpParams = @("-i", "-b", "`"(script-fu-resize-upper-pot-batch \`"$GimpifiedSourcePath\\*.png\`" 0)`"", "-b", "`"(gimp-quit 0)`"")

    Write "Calling $GIMP $GimpParams"
    $p = [diagnostics.process]::Start($Gimp, $GimpParams)
    $p.WaitForExit()
}

```

And everything is now working! I guess that maybe ImageMagick would have been a better solution, it's just a shame that TheGimp proposes a batching process that really isn't powerful enough.

Hope this helps someone!

# Answer
> 4 votes
You might check out this ImageMagick forum post where someone goes into detail on power of two rescaling via some extended features of ImageMagick.

# Answer
> 1 votes
I use Sprite Sheet Packer to put multiple textures into a single *power-of-two-texture*. This also generates either a text file or an xml file with information on the source rectangle of all the sprites in this *power-of-two-texture*.

# Answer
> 0 votes
I had some errors when running Jonathan's script so here's my modified version:

```
(define (script-fu-resize-upper-pot pattern)
(let* ((filelist (cadr (file-glob pattern 1))))
(while (not (null? filelist))
(let* ((filename (car filelist))
(image (car (gimp-file-load RUN-NONINTERACTIVE filename filename)))
(drawable (car (gimp-image-get-active-layer image))))
 (let*
        (
            ;; Store upper power of two for height and width of image
            (height (pow 2 (ceiling (/ (log (car (gimp-image-height image))) (log 2)))))
            (width (pow 2 (ceiling (/ (log (car (gimp-image-width image))) (log 2)))))
        )
(gimp-message filename)
(gimp-image-scale-full image width height INTERPOLATION-CUBIC))
(gimp-file-save RUN-NONINTERACTIVE image drawable filename filename)
(gimp-image-delete image))
(set! filelist (cdr filelist)))))

```

I am running Gimp 2.8 on Windows 8. Here are the steps to run it:

1. Save the code above to a script named: C:\Program Files\GIMP 2\share\gimp\2.0\scripts\script-fu-resize-upper-pot.scm
2. Run the following command substituting the Gimp version, path and extension to your image files as appropriate. Note: this script does not recursively process sub-folders.

C:\Users\Myself\>"c:\Program Files\GIMP 2\bin\gimp-2.8.exe" -i -b "(script-fu-resize-upper-pot \\"R:\\Dev\\unity\\UnityGame\\Assets\\Textures\\\\*.jpg\\" 0)"

---
Tags: textures, tools
---


# Question
Title: How would one draw many objects using the same VBO
I'm kind of stuck with this question for some time now, maybe because I don't know exactly what to search for, it might be a term I have not heard of yet as most tutorials ends after drawing one object to the screen using a VBO.

Being a newbie to OpenGL as well as GLSL I do know at least a few things, one being that you always want to send as little information as you can from CPU -\> GPU and by as few times as possible (better to send all data at once, instead of many small packages per frame). Knowing this tells me that there must be a better way to draw many of the same object, say a teapot, than looping over transformations then "glDrawArrays" and then repeating that step over and over.

It should be possible to send some kind of array containing the number of teapots you want to draw and all the positions/transformation-matrix you want for them.

I know I could possibly put multiple teapots into the same VBO with all the vertex data offset, but that would double the vertex-data and make it less flexible, seems like a bad solution to me.

So what is the right solution to drawing many of the same VBO at different transformations with a single or as few draw calls as possible?

# Answer
What you're looking for is instancing. You simply call `glDrawArraysInstanced` or `glDrawElementsInstanced`, passing the number of instances that you want. There are two ways to then determine per-instance data:

1. The `gl_InstanceID` vertex shader input tells you which instance is currently being processed. Your vertex shader can have an internal mechanism for getting the correct data corresponding to the current `gl_InstanceID`. For example, it could use it to index a table.
2. You can use instanced arrays, which causes a generic vertex attribute array to be indexed by instance, rather than by element index. For example, `glVertexAttribDivisor(attrib, 1)` tells OpenGL to increment the index to the vertex attribute `attrib` with every instance. `glVertexAttribDivisor(attrib, 2)` would increment the index with every second instance.
> 10 votes

---
Tags: c++, opengl, glsl, vbo
---


title: Xna tile map collision

text:
# Question
Title: Xna tile map collision
I finally found a tutorial on tile maps and loading them in from a file that I understand (http://circlessuck.blogspot.co.uk/2012/09/xna-tutorial-basic-tile-engine-part-2.html), however the tutorial doesn't show teach you how to do collision. I have vague idea in mind of what I might have to do from other tile map collisions I've seen, but I can't get it into code that will fit this style of loading tile maps. My tile map loadin:

```
private List<Texture2D> tiles;
    private int[,] tileMap;

    private const int tileWidth = 32;
    private const int tileHeight = 32;

    public TileMap(string name, ContentManager Content)
    {
        LoadTiles(Content);
        LoadMapData(name);
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        for (int y = 0; y < tileMap.GetLength(0); y++)
        {
            for (int x = 0; x < tileMap.GetLength(1); x++)
            {
                spriteBatch.Draw(
                   tiles[tileMap[y, x]], new Vector2(x * tileWidth, y * tileHeight),
                   Color.White);
            }
        }
    }

    private void LoadTiles(ContentManager Content)
    {
        tiles = new List<Texture2D>();
        tiles.Add(Content.Load<Texture2D>("sky"));
        tiles.Add(Content.Load<Texture2D>("grass"));
        tiles.Add(Content.Load<Texture2D>("dirt"));
    }

    private void LoadMapData(string name)
    {
        string path = "Maps/" + name + ".txt";

        int width = 0;
        int height = File.ReadLines(path).Count();

        StreamReader sReader = new StreamReader(path);
        string line = sReader.ReadLine();
        string[] tileNo = line.Split(',');

        width = tileNo.Count();
        tileMap = new int[height, width];
        sReader.Close();

        sReader = new StreamReader(path);

        for (int y = 0; y < height; y++)
        {
            line = sReader.ReadLine();
            tileNo = line.Split(',');

            for (int x = 0; x < width; x++)
            {
                tileMap[y, x] = Convert.ToInt32(tileNo[x]);
            }
        }

        sReader.Close();
    }

```

(I have a player class with basic physics that all work fine)

# Answer
> 0 votes
You will either need a another flag to decide if the tile is solid or not, or you will need to decide this based on the type of tile / texture. For the first option, you'll need to include a piece of data in the txt that tells you if the tile is solid or not. Just a second digit could work in this case. Other, decide based on the tile type. So, if you get grass, that may not be solid, if you get a rock, for example, that might be solid.

Another option could be to include another txt file that maps digit to digit with the map txt file, except you have 0 or 1 for each tile, indicating what is solid and what is not.

If you mean how do you actually implement collision, then look into the "Rectangle" class, and specifically the .Intersect method.

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


# Question
Title: How to move player based on existing Game state?
I'm trying to build a basic platforming game in C++ using SDL, and I've encountered this issue enough to know that there's something I'm missing.

What I'm working with, at the most basic level, is two classes, a `GameState` class that manages everything, and a `Player` class, that will move around.

The main `GameState` object will have a list of obstacles that the `Player` cannot move into, so I want my `Player` `move()` function to take a `GameState*` in order to move based on various components of it.

However, I'm hitting a problem I've seen a bunch of times -- a circular dependency issue. The problem is that the `GameState` object needs to have a `Player` member variable to update as the game runs (so I need to import the `Player` header to it), but I need to import the `GameState` header into the `Player` header in order to have my move function take a `GameState*` as a parameter.

This doesn't work. Normally I'd just settle and have the `Player`'s `move()` function just take a list of obstacles, but I'm kind of hitting this issue all over the place and there are multiple instances where I want to access other variables stored in the `GameState`. Is this kind of behavior even possible? I've been racking my brain for a solution but I don't really know what the best way to fix this is, so I thought I'd ask.

Thanks in advance!

Edit: a simple example in code of what I'm talking about:

```
//in GameState.h
class GameState{
public:
    // ...
    Player* plr;
};

//in Player.h
class Player{
public:
    // ...
    move(GameState* state);
};

```

# Answer
Have the player contain the data like position and a state block, and then have the game state move the player directly using that data. For any kind of state-driven, single player game this is more than sufficient.

In this scenario the game state should **really be called "character controller**" because it uses states internally but **what it's doing is controlling the character** based on user input.

This fixes your problem because the player knows nothing except that it holds some data blocks and the controller knows everything and your circular dependencies disappear.

This also works for enemy NPCs, except their different **controllers** don't take user input and rely on separate game states and paths or scripts to tell them where to move to.

Assuming that the player character is really just an NPC under the hood you can then pull tricks like taking over an NPC, having the player character controlled in a cinematic playback, etc... all by just changing controllers. You could even have a synchronized army of NPCs working under one controller.
> 2 votes

# Answer
Obviously, you can just rethink your design to avoid this error in this case, but that won't always be possible.

To get around circular dependency you can simply declare a class inside the other, without #include-ing. E.g.

```
//in GameState.h

#include "Player.h"
class GameState{
public:
    // ...
    Player* plr;
};

//in Player.h
class GameState;       // Note we declare GameState here, but will not
                       // have a definition until we link.
class Player{
public:
    // ...
    move(GameState* state);
};

```

This means we cannot see methods or members of the "GameState" class, but you will be able to have GameState\* and GameState&. I don't believe ( correct me if I'm wrong ) you will be able to put a GameState object on the stack. Now, you must #include "GameState.h" in "Player.cpp", and then you can use the GameState object as you like in that file.
> 2 votes

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


# Question
Title: How do I pause Andengine, but still get input?
In my game when I pause the game, I'd like to display three options (Resume, Restart and Menu) so I did this after calling `mEngine.stop()`:

```
Sprite resume = new Sprite(CAMERA_WIDTH/2, CAMERA_HEIGHT/2, RM.resume, vertex){
            @Override
            public boolean onAreaTouched(TouchEvent event, float pTouchAreaLocalX, float pTouchAreaLocalY) {
                if(event.isActionDown()){
                    this.setScale(1.1f);
                    Log.i("Click","Click");

                }

                return super.onAreaTouched(event, pTouchAreaLocalX, pTouchAreaLocalY);
            }
        };

```

But the Log "Click" never display. So I tried to do this with the Engine active and the Log displays correctly.

How can I stop my game (Modifier, Physics, Score) without using the `mEngine.stop()` method ?

# Answer
You can use `public void setIgnoreUpdate(final boolean pIgnoreUpdate);` method from the Entity class. The whole Scene is an entity and you attach all objects to it, so if you call `scene.setIgnoreUpdate(true)` all attached children will stop updating. Of course, you can selectively call this method only on Entities that you wish to pause. onTouch events should still work.
> 2 votes

---
Tags: android, andengine
---


# Question
Title: (Realtime-) Global Illumination starting point
What techniques should someone look at when getting into real time global illumination (for dynamic lighting scenarios)?

It's hard to get a real grip on the different mentioned techniques without knowing anything about the subject. If I wanted to incorporate GI into my graphics engine, where should I start reading as a baseline? Which algorithms are implementable in a reasonable timeframe by someone new (i.e. not a highly specialized algorithm that gains minor performance for months of work) and which are not completely outdated by now (i.e. straight up replaced by something simply prettier and faster)?

Photon mapping seems to come up a lot, and I've read about things like voxel cone tracing and more specific algorithms, e.g. this technique used in CryEngine 3. However, knowing next to nothing about the field it's hard to decide where to start.

What general techniques are worth looking into?

# Answer
> 6 votes
Why don't you look into my MSc thesis?

The result apparently blew too hard for SIGGRAPH to accept (they rejected my paper) and I didn't submit to any other conferences. But it still presents a good introduction to GI, written in typical bobobobo understandability (actually some sections go into a bit too much depth, but hey).

You'll want to look at section 2.4, which very quickly and with references runs through some of the newer real-time gi algorithms including

* real time ray tracing
* real time radiosity (enlighten/bf3)
* deferred shading and screen space methods (ssdo, ssao)
* precomputed radiance transfer and spherical harmonics

That's all I got in my survey. Disclaimer that I may have missed something.

Anyway, you really have no hope of implementing all of these in 3 months. I'd say pick **one** and work with it. Real-time ray tracing is by far the most exciting to *me*, because it's a true gi method. Unlike screen space methods, rtrt isn't a "hack" -- it doesn't suffer from weird effects that ssdo does:

---
Tags: global-illumination
---


title: Marching Cubes Terrain

text:
# Question
Title: Marching Cubes Terrain
For the past week I've been researching the Marching Cubes algorithm. I hope to use this for Terrain as it would allow the creation of destruction of terrain. After looking at source code and reading many articles I decided to try compiling some of it myself and playing around with it to attempt to make terrain. However, It's giving me a headache and I can't seem to find any good resources on how to do it.

https://i.stack.imgur.com/BbvJR.png

This is from the example found here - http://www.angelfire.com/linux/myp/MC/

The sourcecode relevant can be found on the website.

I added the source code to my project and converted all the code to be used with OpenGL 3.2. However, I don't want to be using this code in my final project. (This is just so I can understand it). I'm having trouble understanding the code. I feel I understand the algorithm now but I can't seem to understand how the object is actually formed.

How can I change this object to create terrain? Are there any better resources on the internet? Thanks in advance.

# Answer
> 5 votes
Marching cubes is an algorithm for polygonizing an implicit surface - i.e. one defined by an equation of the form f(x, y, z) = 0. You can evaluate any function f(x, y, z) you like, and the algorithm tries to make a polygonal model of the surface formed by the points where the function is zero.

I haven't looked at the source code, but from the screenshot, the test object looks like a metaball, which is a common application of marching cubes. You could perhaps sculpt your terrain out of metaballs.

Another approach, perhaps better suited for terrain, would be to use a noise function like Perlin noise. 3D noise by itself will just make 3D blobs, but to make it more terrain-like, you could use 2D noise and set f(x, y, z) = noise(x, y) - z.

You can combine noise-based terrain with metaballs, too, just by adding their functions together. Therefore you could use metaballs to add additional terrain, or negative-weight metaballs to hollow out caves or destroy terrain.

---
Tags: c++, opengl, terrain, voxels, marching-cubes
---


title: Collision Issues

text:
# Question
Title: Collision Issues
When I run the collision code, there are no errors, but when I shoot the enemy nothing happens..... Any problems that are blindingly obvious?

Class Level Variables

```
public Model model { get; protected set; }

```

Collision Code

```
        public bool CollidesWith(Model otherModel, Matrix otherWorld)
    {
        // Loop through each ModelMesh in both objects and compare
        // all bounding spheres for collisions
        foreach (ModelMesh myModelMeshes in model.Meshes)
        {
            foreach (ModelMesh hisModelMeshes in otherModel.Meshes)
            {
                if (myModelMeshes.BoundingSphere.Transform(
                    GetWorld()).Intersects(
                    hisModelMeshes.BoundingSphere.Transform(otherWorld)))
                    return true;
            }
        }
        return false;
    }

```

# Answer
> 3 votes
Seems to me that you are not applying the bone transforms.

If you are going to evaluate collisions this way, it would be much better to calculate the absolute bounding spheres in `world` coordinates. This way you avoid to repeat transformations.

```
 class MyModel {
       public Model Model;
       public Matrix MyWorld;
       public BoundingSphere[] Bounds;
       public Matrix[] MeshTransform;

       public void CalculateAbsoluteBounds() {
           Matrix[] transforms = new Matrix[Model.Bones.Count];
           Model.CopyAbsoluteBoneTransformsTo(transforms);

           for (int i=0; i<Model.Meshes.Count; i++)
           {
              // You can use MeshTransform to draw the model...
              Matrix.Multiply( ref transforms[Model.Meshes[i].ParentBone.Index],
                               ref MyWorld,
                               out MeshTransform[i]);
              // Transform bounding sphere now with MeshTransform
              Model.Meshes[i].BoundingSphere.Transform(
                   ref MeshTransform[i], out Bounds[i]);
           }
       }
 }

```

And it would be a great idea to draw `wireframe` spheres to debug them easily

---
Tags: xna, 3d, collision-detection, xna-4.0
---


# Question
Title: Building a visual scripting component (like Kismet)
I'd like to know how can one get started building a visual scripting component (or what is the more accurate term for this type of component?) such as UDK's and Unreal Engine's Kismet.

For those who are not familiar, the system allows connecting various pieces of logic visually, creating a possibly complex component out of smaller building blocks.

While the underlying data model may be (perhaps) something i can figure out for myself, it is the visual part that i am not sure of how to work out.

Are there any libraries that facilitate writing something like this? Where can i get started on thsi ?

# Answer
> 1 votes
This is not a gaming related question, it is more like general graphcis programming.

You need to implement some kind of GUI library yourself, and looks like you will need vector based graphics. You might want to use something like OpenVG or similar for that.

---
Tags: visualization, kismet
---


# Question
Title: How to rotate the camera to point to a specified location?
I have a quaternion based camera class (which controls a view matrix) and would like a function to rotate the camera to face a specified point. The best approach I can come up with is that I rotate the camera on the plane of the two vector by the angle between them.

Any advice?

# Answer
Any decent OpenGL math library should have a function called `lookAt`. It does exactly what you want with the exception that it produces a matrix and not a quaternion. This problem can be solved by converting the matrix back to a quaternion.

In case you aren't already using a math library, I recommend checking glm which basically tries to provide everything that GLSL has, just in C++.
> 3 votes

---
Tags: opengl, 3d, camera
---


# Question
Title: Loading tile maps from files on the fly in Crafty JS
I'm fairly new to Crafty and have been having problems loading large world maps.

So i have a world split up into multiple js files. They are represented by two arrays of tiles: one for background (which grass sprite to use) and one for detail (which cliff to use). When i start crafty I load the 3x3 surrounding files and render them like so:

```
for(var i = 0; i < Game.map_grid.map_entities.length; i ++){
    if(Game.map_grid.map_entities.hasOwnProperty(i))
      Game.map_grid.map_entities[i].keep = false;
}

//render background terrain
for (var i = 0; i < view_map["background"].length; i++) {

    var tile_object = view_map["background"][i];
    var tile = tile_object["type"];
    var x = tile_object["x"] - view_map["xoffset"];
    var y = tile_object["y"] - view_map["yoffset"];

    if(Game.map_grid.map_entities.length && (tile+"_"+x+"_"+y) in this.map_grid.map_entities)
    {
        tile_ent.keep = true;
        continue;
    }

    var tile_ent = Crafty.e("Actor", "spr_"+tile);
    tile_ent.at(x, y);
    tile_ent.z = 0;
    tile_ent.keep = true;
    this.map_grid.map_entities[tile+"_"+x+"_"+y] = tile_ent;
}

//render background terrain
for (var i = 0; i < view_map["detail"].length; i++) {

    var tile_object = view_map["detail"][i];
    var tile = tile_object["type"];
    var x = tile_object["x"] - view_map["xoffset"];
    var y = tile_object["y"] - view_map["yoffset"];

    if(Game.map_grid.map_entities.length &&
     (tile+"_"+x+"_"+y) in this.map_grid.map_entities)
    {
        tile_ent.keep = true;
        continue;
    }

    var tile_ent = Crafty.e("Actor", "Solid", "spr_"+tile);
    tile_ent.at(x, y);
    tile_ent.shift(tile_object["xoffset"], tile_object["yoffset"]);
    tile_ent.z = 1;
    tile_ent.keep = true;
    this.map_grid.map_entities[tile+"_"+x+"_"+y] = tile_ent;

}

for(var i = 0; i < Game.map_grid.map_entities.length; i ++){

    //Check if the entities need to be moved

    if(Game.map_grid.map_entities.hasOwnProperty(i) &&
       !Game.map_grid.map_entities[i].keep)
    {
        Game.map_grid.map_entities[i].destroy();
        delete Game.map_grid.map_entities[i];
    }
}

```

I also use the view port to track the player, showing only a portion of the map.

When the player reaches edge of the 3x3 loaded map, I need to request new maps and render them instead. What i have been using is the "Moved" event to check where the player is near the edge. Once that triggers, all of the original tile entities are .destroyed()'ed (i know i can destroy only the ones i need). The above code is ran again to draw the new map and the player is shifted to keep consistent with the new 3x3 coordinates.

The problem is: it looks like the maps are loaded and rendered, but the destroyed ones don't seem to be refreshed and i think are still there. But also the player isn't being redrawn properly, the Moved events are still triggered but the animation isn't updated

My main question is: Is there a better approach to this?

# Answer
I am not getting any response from the link that you provided. In any case, here is a blog post about dynamically loading tile maps using Crafty with an example.

Tile Maps of Unusual Size

It also shows recycling of tiles, which you should probably do instead of "destroy()" if you are worried about performance.

*more details as requested...*

Basically the large map is broken up into many small boxes with boundaries. Nine boxes should fit in the view area. Each box has a "isLoaded" flag. When the player moves, check if they have crossed a box boundary. If they have, clear all boxes three spaces from the new center box and load all boxes two or less spaces from the new center box.

When tiles are unloaded, do not "destroy()" them. Set their visibility to false and push them onto a tile cache (an array for that tile type). When a new tile of that type is needed, try popping it off the tile cache first before creating a new one.

With this method you should be able to support a more-or-less infinite map size. My blog entry contains example code and a link to an example application using CraftyJS.
> 1 votes

---
Tags: maps, crafty
---


title: How to handle Gameflow and Progression?

text:
# Question
Title: How to handle Gameflow and Progression?
I am building my own 2D engine and I try to handle the progression of my character.

For example, when the player has a special item an door opens or when he talks with someone and has an item, the person reacts in a different way.

I don't want to hardcode that. Is there an common way to handle such things? I thought about a FSM to handle that but it seemed too complex for it. (I want an easier way.)

At the moment I handle it with several `if` statements that check if the characters items array has item X then say this and if he has item Y then say that.

PS: I am writing my engine in JavaScript so if you post code, I can live with Java and AS 3, but not with C/C++.

# Answer
Most games which are more complex use a scripting language to script world interactions.

Certain situations in the game can trigger scripted events (interacting with NPCs, killing a certain enemy, stepping into a certain area, picking up an item...). When such an event is triggered, a function from a script file is executed, which in turn calls back some functions of the game ("script bindings") which makes changes to the world.

Which of these events triggers what script is usually not hard-coded, but defined in the map editor or item description files.

Such a scripting language can either be self-written, or you can use an existing scripting language. I would recommend the latter, because writing a fully-functional programming language is a really hard task, both in planning and in execution. Many popular scripting languages have libraries for integrating them into all kinds of popular "real" programming languages. This gives you a well-tested implementation of a well-designed language with a minimum amount of work.

Which scripting language to use is a matter of personal taste.
> 1 votes

---
Tags: fsm, progression
---


# Question
Title: Is there a better alternative to Timers to increment speed?
I'm making a chaser game in flash, where you would press an arrow key and the player would move in that direction then stop on another point on a grid, as the enemy does the same and chases the player. To make the movement smooth, I have a timer moving the player one pixel each repetition (50 times to stay on the grid points), having the delay get smaller every 30 frames to speed up. But after the delay gets to 0 and can't go any lower, the player can't get faster. What is a better alternative to use to continue going faster?

```
            var playerTimer:Timer=new Timer(40,50);
            playerTimer.addEventListener(TimerEvent.TIMER,playerMoveTrigger);
            var pStatus:String="";
            stage.addEventListener(KeyboardEvent.KEY_DOWN,playerMove);
            function playerMove(e:KeyboardEvent):void
                {
                if((player.x+15)%50==0&&(player.y+15)%50==0)//ensures player is on grid before moving
                {
                    switch(e.keyCode)
                        {
                            case Keyboard.DOWN:
                            pStatus="down";
                            break;

                            case Keyboard.UP:
                            pStatus="up";
                            break;

                            case Keyboard.LEFT:
                            pStatus="left";
                            break;

                            case Keyboard.RIGHT:
                            pStatus="right";
                            break;
                        }
                }
                playerTimer.start()
                }
                playerTimer.addEventListener(TimerEvent.TIMER_COMPLETE,resetTimerP);
                function resetTimerP(e:TimerEvent){playerTimer.reset();}

            function playerMoveTrigger(e:TimerEvent)
            {blockMove(player,pStatus);}
            var offSet:int=0;
            function blockMove(block:Shape,dir:String)
                {   offSet=(block.height==30)?15:10;
                    switch(dir)
                        {
                            case "down":
                            if(block.y+offSet<150){block.y+=1;}
                            break;

                            case "up":
                            if(block.y+offSet>50){block.y-=1;}
                            break;

                            case "left":
                            if(block.x+offSet>50){block.x-=1;}
                            break;

                            case "right":
                            if(block.x+offSet<150){block.x+=1;}
                            break;
                        }
                }

```

# Answer
Increase the distance the player moves per timer iteration

Change your += or -= 1 to a variable \[speed\]. Your speed starts out at 1 and increases as the game progresses
> 2 votes

---
Tags: flash, actionscript
---


# Question
Title: When to call GLBindTexture when using a spite-sheet?
Originally, I was using individual textures (ie, individual .png files) for my sprite's animation and recently altered my code so that I could put all my animation frames into 1 file (so it basically is like a mini sprite sheet - I say 'mini' because I'm using 1 file per sprite, I'm not using 1 file for *all* my sprites).

Anyway my question relates to **glBindTexture**. Originally, I was switching textures when I wanted to update the animation frame so was calling this in my sprite's draw method:

```
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texID);  //texID being the texture ID

```

However, now what happens is that I work out the texture offset and just point to part of the texture that I require. The texture itself does not change anymore, so do I still require this line every time I draw?

I tried removing the line from my draw() method and just calling it once when I loaded the texture initially, but the sprite doesn't draw with the correct texture, it uses a completely different, un-related texture. So what is the correct course of action in cases like this where a sprite-sheet is being used?

At the moment, I'm not sure why this would be any faster than using individual files and switching the texture every frame. In fact as I'm now having to work out the texture offset (whereas previously it was fixed), there is more overhead. So I'm guessing the advantage comes from not having to call this glBindTexture line every time I draw (as it's expensive). So how do I correctly choose the texture to assign to this sprite other than within the draw method?

Any help would be appreciate, if you need code please ask I didn't post my whole draw method as I didn't think it was necessary to explain the issue.

This is what I was doing previously

```
Bind texture 1 (Animation frame 1, textures 1-8 belong to this sprite)
Draw Sprite 1

Bind texture 9
Draw Sprite 2

```

Repeat binding texture 2, then 3 etc for sprite 1 to animate it

I am now using a single texture for sprite1 which contains all 8 animation frames

```
Bind texture 1 (all frames)
Draw Sprite 1 (pointing to frames 1, 2, 3 etc)

Bind texture 5
draw sprite 2

```

# Answer
You need to bind the texture you are using before any draw calls you want to use that texture with. I assume you have something like this:

* Sprite 1 using texture 1
* Sprite 2 using texture 2
* Sprite 3 using texture 3

Then you must draw them like this:

1. Bind texture 1
2. Draw sprite 1
3. Bind texture 2
4. Draw sprite 2
5. Bind texture 3
6. Draw sprite 3

Now you can improve the speed of rendering the sprites quite a bit. If you do not want to include ALL sprites in one texture, then you might do it like this:

* Sprite 1 using texture 1
* Sprite 2 using texture 2
* Sprite 3 using texture 1

And drawing:

1. Bind texture 1
2. Draw sprite 1
3. Draw sprite 3
4. Bind texture 2
5. Draw sprite 2

Now you see, there is reduced amount of the expensive texture binding calls. But you can still improve this by putting all sprites in one texture:

1. Bind large texture with all sprites
2. Draw sprite 1
3. Draw sprite 2
4. Draw sprite 3

This way you minimize the texture binding calls, which speeds up the rendering process a bit.
> 1 votes

---
Tags: android, opengl-es2, spritesheet, texture-atlas
---


# Question
Title: How to simulate timed attacks in browser-based games?
In my MMORTS browser-based game, I want that all attacks be performed 7 minutes later after the player does it.

So, when the player clicks on attack button, a countdown becomes visible to both the attacker and the defender.

Showing countdown and handling its events isn't my question. In fact, my Q is how can I implement this countdown in server side and database.

I haven't any idea about managing this situation. Any helps is highly appreciated...

# Answer
> 3 votes
That's actually not that much game related, as general programming related.

It all depends on your language and environment, but the theory relies in http://en.wikipedia.org/wiki/Background\_process and http://en.wikipedia.org/wiki/Asynchronous\_I/O.

There are multiple ways, some of them:

* Easiest, and most friendly, easy to set up would be AJAX \- you'd simply start a timeout, once it expires, call the AJAX, and on successful response act accordingly. (Though, it won't work if you need the attack to be performed even if the user is not online.)
* http://en.wikipedia.org/wiki/Cron (it's for \*NIX), Scheduled Tasks probably is the alternative for Windows.
* Message queues (probably, the best way), used as task/job schedulers:
* You could also (not the best way at all) upon request, start a background process that'd be given the task execution time, and task itself. The process would run in a continuous loop, once it's `current` time matches or exceeds the `given` time, call the task and kill the process.
* There is also the option to simply queue the actions by storing them inside database. Now, if the player quits, and he or anyone related to the action joins again, upon loading the game, you'd look if the entity has some actions that have happened. If so, you simulate them all at once, affecting any related entities too, then giving the player the simulated state from where he'd continue.

---

If you could provide the environment / language you are working with, the answer could be narrowed down and tailored more for your specific problem.

---
Tags: browser-based-games, mmorts
---


title: Using an FBO texture and write to it

text:
# Question
Title: Using an FBO texture and write to it
I wanted to know if it's possible to use a texture of an FBO for post-processing and using that texture again for writing or do I need at least two textures?

I hope you understand what I mean.

# Answer
You can write to or read from an FBO as many times as you like. What you can't do in general is both read from and write to the same FBO at once. So you can't do an "in-place" operation, using the same FBO as both a render target and a texture in the same draw. This means you may need at least two textures to "ping-pong" between when doing a sequence of image processing operations, such as a separable blur for example. For more information see this OpenGL wiki page.
> 4 votes

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


# Question
Title: How could I figure out the shortest way to turn, and whats the angle?
I'm creating some robots for my tank game. I want them to find each other and shoot each other down, so I'm trying to implement a way for them to turn towards each other, and turn the shortest way. For instance, if we where T1 (tank 1), how could I figure out if I where to turn right of left, and at what angle to turn if

* Tank1 (us) position is (8906,76), facing is 23 degrees.
* Tank2 (enemy) position is (888,61)

0/360 is straight up.

The way I've tried to do is to decide what quadrant the enemy is of myself. But that leaves out a 45 degree angle to fail. I know there is some archtan but I cant simply get a grip on them...

# Answer
TLDR, if the difference between the angle you're facing, and the angle of the direction of Tank2 is between 0 and 180 degrees, then you turn left, else turn right. (might be the opposite depending on the + and - signs of whatever library you happen to be using, but you get the idea)

So you need the angle you're facing and the angle of the direction to Tank2. You already have your angle, so you get the angle to Tank2 by doing the Arc Tangent of his position in relation to you. So you get the tangent of this angle, which is the delta of the Y coordinates divided by the X coordinates.

So tan = (y2 - y1) / (x2 - x1)

Then angleToTank2 = atan(tan)

delta = angleToTank2 - yourAngle

Finally, if delta is between 0 and 180 degrees, you turn left, else, turn right.

I cannot give you exact code without knowing which libraries you're using, maybe left and right needs to be inverted. Maybe it's radians instead of degrees (180 degrees is 1 PI radians). But that should be easy for you to adjust. You might also want to add an error margin for the tank to not turn if the delta is too small (almost in the right direction, so I don't need to turn).

Hope that helps.
> 2 votes

---
Tags: c#, 2d, game-mechanics
---


title: Side Menu using Libgdx

text:
# Question
Title: Side Menu using Libgdx
I want to make it so that when the player presses start, a side menu slides out and gives a player some option on one side of the screen, similar to Angry Birds or Pokemon. I'm not sure how to go about doing this but I think its somthing like putting an if statement in the render method?

```
render(){
     if(menuVisible){
     //draw menu?
     }
}

```

I'm fairly new to libgdx so I do not know how to use it to its fullest extent yet.

# Answer
> 1 votes
Your question is more about programming and not necessarily related to libGDX, you could implement it plenty of ways.

Using an if statement like this could definitively works but it might seems a bit ugly. Fortunately, libGDX provides a way to create code that fits UI creation and you should use it, it's called scene2d you can find the documentation here.

And you don't even need to create your actual menu from scratch since libGDX also provides out of the box actors to build user interfaces: https://code.google.com/p/libgdx/wiki/scene2dui

Your sliding menu could then be an `Actor` that you may translate in a direction or another on top of your game state to create the desired effect.

---
Tags: java, rendering, libgdx, menu
---


title: A simple flight simulator

text:
# Question
Title: A simple flight simulator
In a 3D flight simulator with a Crimson Skies level of realism (as in, arcade level rather than realistic), how do you determine the movement of an aircraft each game clock tick?

(Crimson Skies is an arcade-like flight simulator: http://youtu.be/OWmYt0LZDnU?t=3m )

I presume the game advances in fixed steps, and each step each moving object moves in a straight line with constant velocity from its current position to the next.

What basic parameters would you need to determine the mass, speed, throttle .etc. Also how would you combine them?

# Answer
To understand how to simulate aerodynamic flight, one first has to understand which forces affect the movement of an aircraft. The actual trajectory of an aircraft is the sum of all of these physical effects:

## Newton's first and second law of motion

1. An object moves at a constant velocity, unless acted upon by a force.
2. The acceleration of a body is directly proportional to, and in the same direction as, the net force acting on the body, and inversely proportional to its mass. Thus, F = ma, where F is the net force acting on the object, m is the mass of the object and a is the acceleration of the object.

## Engine Thrust

The thrust of the engine is a force which accelerates an aircraft forward and usually can be controlled by the player. The acceleration is the power of the engine divided by the mass of the aircraft.

## Gravity

Gravity constantly accerates an aircraft downwards with a speed of 9,81 m/s². In theory, gravity becomes less when you go higher, but at the height where normal aircrafts operate, this can be ignored.

## Aerodynamic drag

The faster an aircraft moves, the more does atmospheric friction slow it down. This is represented by a force accelerating in a direction against the current direction the craft is moving. The force increases quadratical with the speed (double speed = four times the drag force). But the higher the aircraft is flying, the thinner the atmosphere and the lower the drag-force. The maximum speed of an aircraft is where the forces generated by engine thrust and aerodynamic drag cancel each other out.

It might sound counter-intuitive, but having a stronger drag-constant will actually make your game easier to play (more arcade-like), because drag is the force which stops the plane from flying into the direction the player doesn't want to fly anymore (like when flying a curve). So more drag = slower and more maneuverable planes. You can further improve this by increasing the drag when there is a difference between the heading-direction and the movement-direction of the plane (this isn't even unrealistic - the aerodynamic profile of a plane is optimized for least air resistance when the plane is flying *straight*).

## Aerodynamic lift

This is the force which actually causes a plane to fly. It is generated by the wings. The larger the wing surface, the more lift is generated, and accelerates the plane upwards (relative to the wings, not the ground. When the plane rolls sideways, the lift is accelerating it sideways, too). Just like the atmospheric drag, the lift is relative to speed and atmospheric density.

## Control surfaces

A plane controls its direction with different control surfaces for pitch, yaw and roll. A control surface only works when the plane is moving. Its efficiency is proportional to the current speed and atmospheric density. Note that control surfaces only change the direction in which the plane is pointing, not the direction it is moving. This affects the direction of thrust and lift, and thus gradually the movement direction.
> 24 votes

---
Tags: physics, simulations
---


# Question
Title: SharpDX: best practice for multiple RenderForms?
I have an XNA app, but I really need to add multiple render windows, which XNA doesn't do. I'm looking at SharpDX (both for multi-window support and for DX11 / Metro / many other reasons). I decided to hack up the SharpDX DX11 MultiCubeTexture sample to see if I could make it work.

My changes are pretty trivial. The original sample had:

```
[STAThread]
private static void Main()
{
    var form = new RenderForm("SharpDX - MiniCubeTexture Direct3D11 Sample");
    ...

```

I changed this to:

```
        struct RenderFormWithActions
        {
            internal readonly RenderForm Form;
            // should just be Action but it's not in System namespace?!
            internal readonly Action RenderAction;
            internal readonly Action DisposeAction;
            internal RenderFormWithActions(RenderForm form, Action renderAction, Action disposeAction)
            {
                Form = form;
                RenderAction = renderAction;
                DisposeAction = disposeAction;
            }
        }

        [STAThread]
        private static void Main()
        {
            // hackity hack
            new Thread(new ThreadStart(() =>
            {
                RenderFormWithActions form1 = CreateRenderForm();
                RenderLoop.Run(form1.Form, () => form1.RenderAction(0));
                form1.DisposeAction(0);
            })).Start();
            new Thread(new ThreadStart(() =>
            {
                RenderFormWithActions form2 = CreateRenderForm();
                RenderLoop.Run(form2.Form, () => form2.RenderAction(0));
                form2.DisposeAction(0);
            })).Start();
        }

        private static RenderFormWithActions CreateRenderForm()
        {
            var form = new RenderForm("SharpDX - MiniCubeTexture Direct3D11 Sample");
            ...

```

Basically, I split out all the Main() code into a separate method which creates a RenderForm and two delegates (a render delegate, and a dispose delegate), and bundles them all together into a struct. I call this method twice, each time from a separate, new thread. Then I just have one RenderLoop on each new thread.

I was thinking this wouldn't work because of the \[STAThread\] declaration -- I thought I would need to create the RenderForm on the main (STA) thread, and run only a single RenderLoop on that thread. Fortunately, it seems I was wrong. This works quite well -- if you drag one of the forms around, it stops rendering while being dragged, but starts again when you drop it; and the other form keeps chugging away.

My questions are pretty basic:

1. Is this a reasonable approach, or is there some lurking threading issue that might make trouble?
2. My code simply duplicates *all* the setup code -- it makes a duplicate SwapChain, Device, Texture2D, vertex buffer, everything. I don't have a problem with this level of duplication -- my app is not intensive enough to suffer resource issues -- but nonetheless, is there a better practice? Is there any good reference for which DirectX structures can safely be shared, and which can't?
3. It appears that RenderLoop.Run calls the render delegate in a tight loop. Is there any standard way to limit the frame rate of RenderLoop.Run, if you don't want a 400FPS app eating 100% of your CPU? Should I just Thread.Sleep(30) in the render delegate?

(I asked on the sharpdx.org forums as well, but Alexandre is on vacation for two weeks, and my sister wants me to do a performance with my app at her wedding in three and a half weeks, so I'm mighty incented here! http://robjsoftware.org for details of what I'm building....)

# Answer
Okay, first of all, I would like you to consider forfeiting the notion of "best practice". *There are no such things* as "best practices". Some things work, some don't, and none do under all assumptions and scenarios, therefore being "best". Every time you use the words "best practice", God kills a kitten, so please think of the kittens.

Now, onto your problem. You certainly have given it a lot of thought, and most of your assumptions are correct. Let's start:

* A Direct3D device can't render to multiple windows at the same time. In general, you will only have one window per Direct3D device. However, as you already know, you can certainly have multiple Direct3D devices per process, and you certainly have one per thread, which leads us to.
* You *can* have multiple Direct3D devices in the same thread! Particularly, if my program wasn't very CPU intensive, I would create two Direct3D devices in the same thread, and render serially. For each iteration of your render loop, do everything you need to do for each Direct3D device. If, as you say, you can have 400+ fps, then you shouldn't have problem with two devices in the same thread. Keep everything in the same thread, and you won't have to care about synchronization at all.
* DirectX is generally not thread-safe. This is different from the thread-hostility of Windows Forms, in which objects are owned by a thread and you can't generally do anything with them from a different thread (apartment). DirectX (9, which is what I mostly know) doesn't really care which thread you call functions for, as long as you don't call two API functions at the same time from different threads. You can opt in/out of thread safety when you create your device, but in general, as long as you synchronize access to your device, you can certainly do things from multiple threads. This doesn't mean you *should* though.
* Windows Forms is not thread-friendly, so you certainly have to have all your windows in the same thread.
* If you *must* separate the logic and Direct3D devices into different threads, then I would have three threads: one for the COM stuff (windows forms), and one for each device. You must then use some kind of synchronization to pass messages or data between threads, so make sure you keep it as simple as possible, because that is likely to become one of the most complex parts of your program.
* There's nothing wrong with duplicating data for all devices. Video cards have humongous memory these days, and if you're reaching the limit with one device, there are other things you should worry about before adding a second device. However, you *can* share data between devices, and in fact, you can share data across processes, and even across different versions of Direct3D. That's a bit out of the scope of this question, but I have a more detailed answer, so check that one out as well.

In general, do what's best for your assumptions. I'd recommend you do what's easiest for you, and don't try to hunt for holy grails or "best practices". Do what's best *for you*, and go with that!
> 3 votes

# Answer
You can't do the rendering of multiple viewport in separated threads, D3D doesn't work this way, it's not thread safe (unless you use the deferred rendering feature of D3D11).

In multiple viewport case you have to adopt a structure that looks like this:

* A RenderingDevice class that takes care of all the D3DRendering device setup.
* A Viewport class that takes care of the Viewport related initialization (use RenderingDevice, create the SwapChain, rendering target, etc.). In case of 3D, the Viewport is attached to a Camera which is in a scene that can be shared among multiple Viewport.
* A Scene class, which contains all the 3D resources (Mesh, Texture, Camera, etc.)

Concerning the rendering loop, there's no a "best way" of doing this, in Winform, you can:

1) Use CompositionTarget.Rendering += OnRendering; And call the rendering loop of your viewports sequentially. This is ok if your scene render fast, if it takes more time than the frequency of CompositionTarget.Rendering you'll got some stuttering and bad interaction issues.

2) Use Application.Idle += ApplicationOnIdle; with a timer like : \_ticker = new Timer(); with an interval base on the frequency of rendering you aim (\_ticker.Interval = 1000/100; for 100hz). The timer only set a bool "DoRender = true" and the ApplicationOnIdle checks this bool for true to perform the render. This way works best if you rendering loop take a lots of time, but the fluidity of the overall animations/interaction my not be the best as OnIdle may not be called as much as it would be necessary.

3) Hooking the Windows Proc of you Winform control like Alexandre did in his sample. I can't comment this as I don't know it much, but I know this may not be the easiest way in your case.

By the way, use RenderControl and not RenderForm in case of multiple viewport scenario.

Try 1) it's a quick test, then 2) and see what works best for you.
> 0 votes

---
Tags: directx11, sharpdx
---


# Question
Title: Do I need licensing to use real city names in my game?
I want to allow people to go to real places (Seattle Washington, Portland, Maine, etc.) in my game. Will I need licensing to make those places and use their names?

# Answer
Public things like: country names, state names, county names, city names, street names, etc., are not trademarked or copyright protected. There are no licensing agreements required to use them.

See Public Domain
> 15 votes

---
Tags: legal, copyright, licensing
---


title: How does Simplex Noise work?

text:
# Question
Title: How does Simplex Noise work?
Are there any good resources and step by step tutorials on Simplex Noise? I have been Googling on it for a while now but I really can't find any good ones. I kinda understand the theory behind it but I have no clue how it works from A to Z and how to implement it.

(I am not looking for a library)

**Why this is not a duplicate of this question**

In this question I am asked how Simplex Noise works from A to Z, rather than how the coordinate system gets converted.

# Answer
> 1 votes
Stefan Gustavson's paper is still the best general reference to how simplex noise works from A to Z.

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


title: How to code a Game Grid in Java?

text:
# Question
Title: How to code a Game Grid in Java?
Suppose I wanted to code a game grid in java. Not an abstract text one but an actual grid with graphics and 'cells'. Would I have to draw line by line or is there a more efficient way? Also how would I go moving units (objects) around the grid, moving them and repainting their positions?

```
  public static int [] [] map = {{2,0,1,0,0}, // e.g. 2 is base
                                   {1,0,0,0,0},
                                   {0,0,0,0,0},  //1 is unit
                                   {0,0,0,0,0},
                                   {0,0,0,0,2}};

```

I still wonder if there is a resemblance between 2D arrays and actual game grids as I can just paint coordinates and lines. However I feel there is a better way and want to implement a structure like above (the code) to emulate a map like this:

# Answer
You should read about tiled maps, tiles and tilesets.

Your tiled map is a grid. It's simply a 2D array where each element of the array is a tile. Using a 2D array in this case seems perfect since you can easily access a tile at a given position by doing `mapArray[x][y]`.

Now you need to define a way to represent the tiles of your map. Here come the concept of *tileset*. A tileset is basically an image containing a collection of tiles, here is an example of a random tileset I picked on the internet:

Since you know that the tiles of your map will always have the same dimensions (16x16, 32x32 etc.), you can easily extract the tiles from the tileset and assign an id to each of them. The first tile in the tileset could have the id 0, the second one, the id 1 and so on. Then, why not do something like `tileset[id]` to get actual tile's image?

This way, your map could be a 2D array of integers representing tile's id. When creating your map, you will need to link your map array with the tileset(s) used to render it.

If you decide to use frameworks such as Slick2D or LibGDX, they often have build in facilities to manipulate tiled maps.

Plus, some tiled map editors exists:
> 2 votes

# Answer
A way you could do it is an array of images which would most likely require a library. I'm a C++ coder but say the library has an object called an Image. You could make an array of this a new Image object and set specific values of that array to different images. Like...

```
Image map[] = {{"something.png"},{"another.png"}} ...

```

And then maybe you could make another normal int array to actually set-up the map layout while using values of the int array to apply to the values of the Image array but you couldn't set them equal to each other since they're different types.
> 1 votes

---
Tags: java, graphics, grid
---


# Question
Title: Map handling - Indoors/Outdoors and loading large maps
I have two questions regarding the handling of maps.

**Question 1.** My map will consist of outdoor enviroments as well as dungeons, houses etc. How would I go on about connecting the outdoors with the indoors?

**My simple solution to 1.** Put everything in the same map file and when you, for example, walk through a door the player will be "teleported" to the indoor location. Let's say the outdoor location of the door is at the coordinates (10,10) and the indoor enviroment of the given house is at (1000,1000) the player's coordinates will be set to (1000,1000) when he walks through the door.

Is this optimal or is there a better way of doing this?

**Question 2.** My map will consist of a bunch of larger cities and paths connecting these cities. Obviously the map will be pretty big and I'm not sure if I can keep the whole map in memory. How would I go on about creating an effective map management system?

**My simple solution to 2.** Have the map consist of "chunks" with x\*x tiles where x is the number of tiles that will fit in the screen. I would then load the chunk the placer is currently in and also the surrounding chunks but nothing else. When the player moves to a new chunk the map will load new surrounding chunks etc.

Would this be a more effective way of handling the map than loading the entire map into memory? Advantages of this way is that I don't have to keep the entire map in the memory but it will take time to dynamically load each "chunk" when it's needed thus creating loading time.

Any improvements to my rudimentary solutions is gladly appreciated.

# Answer
Larger game engines typically have entirely different renderers for indoors vs outdoors, especially in FPS games, as the rendering techniques to efficiently handle one are quite different than the other.

A common technique to link the door is to use portals. These can either be polygon click region which simply transitions your avatar on a click, or it can be renderer-integrated and allow switching from indoor to outdoor scenes.

One particularly hard part is ensuring you have all the right resources loaded. In large outdoor scenes, this is often accomplished by loading all nearby "cells" which varying levels of detail based on distance. For indoor scenes there is generally a connectivity graph that can be used for similar purposes. If you have such a portal, use that during your "find nearby cells" logic. If the player is near a portal, preload whatever is on the other side. For click region support, this at least removes the need for loading screens or the like and makes the transition instant. It's outright required for renderer integration.
> 1 votes

---
Tags: java, 2d, lwjgl, tilemap
---


title: Problem with gluOrtho2D()

text:
# Question
Title: Problem with gluOrtho2D()
I was trying to understand the `gluOrtho2D` function. I have drawn 4 lines originating from the center reaching up to 4 corners of the screen.

You can follow the below code. `osize` is a variable which is used to set the parameters of `gluOrtho2D`. It will create a window of size `2*osize`.

If works fine when `osize` is 1. Lines reach the corners. But as I increase the value of `osize`, the length of the lines decreases (cross becomes smaller and does not cover the whole screen). But I think it should reach the corner.

```
void display()
{
    glClear( GL_COLOR_BUFFER_BIT );

    //glViewport(0, 0, 100, 100);

    glMatrixMode (GL_PROJECTION);
    float osize = 1.2;
    //glOrtho(-osize*1.0, osize*1.0, osize*1.0, -osize*1.0, -1.0, 1.0);
    gluOrtho2D(-osize*1.0, osize*1.0, osize*1.0, -osize*1.0);
    glMatrixMode (GL_MODELVIEW);

    glBegin(GL_LINES);
       glColor3f(0.0, 0.0, 1.0);
       glVertex2f(0.0, 0.0);
       glVertex2f(-osize*1.0, -osize*1.0);
       glVertex2f(0.0, 0.0);
       glVertex2f(-osize*1.0, osize*1.0);
       glVertex2f(0.0, 0.0);
       glVertex2f(osize*1.0, -osize*1.0);
       glVertex2f(0.0, 0.0);
       glVertex2f(osize*1.0, osize*1.0);
    glEnd();

    glutSwapBuffers();  //includes glFlush();
}

```

What is the problem?

# Answer
> -1 votes
Maybe you inverted bottom with top? Ortho matrix will scale Y by 2 / (top - bottom), in your case a negative number.

---
Tags: opengl
---


title: 24-Bit Colordepth not enough?

text:
# Question
Title: 24-Bit Colordepth not enough?
I noticed that in very soft gradients, the 24-Bit colordepth is not enough as you can see the transitions of the color. This pops out the most in dark scenes or night skies.

Why doesn't anybody change the colordepth to two bytes per channel? I know that would be alot of work and a lot of hardware would have to be repalced, but I find it a bit annoying. I really don't think that the technology of the hardware isn't mature enough.

So why is no one doing that?

Here's a picture of "The War Z" where you can see what I mean:

# Answer
> 19 votes
You more or less said it yourself: 'I know, that would be a lot of work and a lot of hardware would have to be replaced.' While the graphics-hardware end of things would actually be relatively straightforward (if expensive - doubling the size of all textures and frame buffers is far from trivial), the 'ecosystem' for higher color-depth imagery simply isn't in place to the kind of extent that makes this a worthwhile expenditure on anyone's behalf, as no LCD manufacturers are focusing on trying to get up to 16 bits per pixel (though there have been some experiments at 10BPP, which conveniently still fits an RGB signal into a 32-bit channel).

In short, it's simply too much work for what most people consider yet to be too little gain. It may well be 'a bit annoying', but that annoyance level is so slim that other improvements to image quality have been taking priority.

# Answer
> 43 votes
Yep, you're not the first person to notice this. :) With today's high contrast ratios, 8 bits per component is not enough to make a smooth gradient without visible banding - unless dithering is used.

Using more than 8 bits per channel on a display is called "deep color" by display manufacturers. It isn't very widespread because of a chicken-and-egg problem. A deep color display is useless without a video card that can output deep color, and a game engine that supports rendering to deep color. Likewise, there is no point in a game engine or a video card that supports deep color without the display. So there is not much incentive for hardware manufacturers and game developers to add support for this technology, as from either end, there is no market to justify the cost of development.

---

Also, there are other ways to fix banding due to the limited 8-bit precision. As I mentioned earlier, game engines can use dithering to hide the banding.

<sup>*(Picture of a cat with a 256-color palette, without and with dithering. Created by Wikipedia user Wapcaplet, used under the CC-By-SA 3.0 license.)*</sup>

Adding a slight dither of ±0.5/255 before writing out the pixel value to the framebuffer is extremely effective at hiding banding on smooth gradients, and essentially unnoticeable. If you're in an HDR engine, you do this during the tonemapping stage.

---

Finally, as others have noted, texture compression can be a bigger source of banding-like artifacts in the image than the 8-bit precision is. This may be what's going on with the sky in that picture, although it's difficult to tell - it's got so much JPEG compression on it that any artifacts due to DXT compression are pretty much swamped.

# Answer
> 13 votes
It's also worth noting that many LCD panels aren't even 8 bits per channel. The cheaper ones tend to use less bits and use various tricks to try to hide it. For example they might switch rapidly between two adjacent colours to represent the one in between. http://www.anandtech.com/show/1557/3

There's some details on how DXGI supports 10-bits per channel and brighter than white colours at http://msdn.microsoft.com/en-us/library/windows/desktop/jj635732%28v=vs.85%29.aspx

D3D has also supported more than 8-bits per channel for years. There's nothing stopping a developer doing some dithering down from 16-bits per channel to 8-bits if they think it's a good idea.

Of course that won't help so much if the source data (texture, etc) is only 8-bit (or more likely DXT1, which is effectively 5-6-5 bits per channel). I believe that's what's up with the sky in that screenshot (an 8-bpp gaussian blur makes it much smoother for me) but it's hard to be certain.

# Answer
> 10 votes
Steven Stadnicki's answer is correct -- games rarely use higher precision textures because it requires too much texture memory, and consequently too much memory bandwidth when sampling the texture in a pixel shader. However, there are solutions that don't require big textures. (I would post this as a comment, but it's too long.)

Homeworld solves this problem by encoding the sky image as vertex gradients. This technique works great for large, low-frequency images (i.e., smooth gradients) -- like skies -- where the texture covers a huge number of in-game pixels.

Another possible solution is to apply histogram normalization to your sky image. If the texture data lies within a narrow value range, like a dark night sky, most of the bits in each color channel are carrying no useful data. Instead, do this:

* Author the original texture in a 16-bit format, like a 16-bit TIFF.
* When you prepare your textures for the game engine, find the darkest pixel present in the image and keep track of this as an offset. Let's say this pixel value is 0.1 in a possible range of 0-1.
* Next, find the brightest pixel and subtract the darkest pixel to get the range of values in the image. So, if the brightest pixel is still pretty dark -- say 0.35 -- the range is only 0.35 - 0.1 = 0.25. Only 25% of the value range is present in the image.
* Generate your DXT/BC-compressed in-game texture. Subtract the darkest value from every pixel, and multiply to use the entire color range. In the example calculation we subtract our dark value of 0.1 and, because only 25% of the available value range is present, we multiply every pixel value by 4x to create the in-game texture. Make sure to do all this before you quantize your 16-bit source image down to the 8bpp input to the DXT compressor. The output image will now utilize the entire range of values supported by the in-game format. We are allocating all our bits to represent the values actually present in the image.
* Store the dark value offset (0.1) and range (0.25) in metadata somewhere. Pass these as inputs to your pixel shader.
* In pixel shader code, sample your shifted, expanded texture, convert it to a float value and then do a multiply/add to restore the original color value. In other words, multiply by 0.25 and add 0.1 to restore the value stored in the source image.

Make sure the shader code is gamma correct. If you do math (lighting & post-processing) on texture samples that are not converted from sRGB color space to linear space, you will see banding artifacts like the one you describe. Gamma correction was created to help alleviate this kind of problem by allocating more bits to dark values where your eyes are more sensitive to value changes. But you can easily break things if you don't account for gamma correction when calculating, for example, lighting, exposure, or post-processing FX. The Gamma FAQ is helpful.

# Answer
> 1 votes
24 bits is not quite enough, but it's much more common for problems like this to be caused by image compression algorithms, aliasing, or other digital artifacts. Also, don't overlook the role of the display technology - no matter what the digital inputs, the display may not produce the appropriate steps in actual brightness.

---
Tags: graphics
---


title: XNA Strange Lighting, Shader

text:
# Question
Title: XNA Strange Lighting, Shader
Hey guys, i have strange lighting problem. I've written my own "deferred lighting" shader and this happend:

1. Pic: Normal-Map
2. Pic: Light-Map

As long as i only use one big mesh everything seems okay, but this look pretty wrong.

Here is how i calculate the point light map (http://www.packtpub.com/article/advanced-lighting-3d-graphics-xna-game-studio-40):

```
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
  // Find the pixel coordinates of the input position in the depth
  // and normal textures
  float2 texCoord = postProjToScreen(input.LightPosition) + halfPixel();
  // Extract the depth for this pixel from the depth map
  float4 depth = tex2D(depthSampler, texCoord);

  // Recreate the position with the UV coordinates and depth value
  float4 position;
  position.x = texCoord.x * 2 - 1;
  position.y = (1 - texCoord.y) * 2 - 1;
  position.z = depth.r;
  position.w = 1.0f;

  // Transform position from screen space to world space
  position = mul(position, InvViewProjection);
  position.xyz /= position.w;
  position.w = 1;

  // Extract the normal from the normal map and move from
 // 0 to 1 range to -1 to 1 range
 float4 normal = (tex2D(normalSampler, texCoord) - .5) * 2;

 // Perform the lighting calculations for a point light
 float3 lightDirection = normalize(LightPosition - position);
 float lighting = clamp(dot(normal, lightDirection), 0, 1);

 // Attenuate the light to simulate a point light
 float d = distance(LightPosition, position);
 float att = 1 - pow(d / LightAttenuation, LightFalloff);

 // Calculate the specular Component
 float3 R = normalize(2 * max(0,dot(normal, lightDirection)) * normal - lightDirection);
 float4 specularComponent = pow(saturate(dot(R, normalize(CameraPosition - position.xyz))), LightShininess);

 return float4(LightColor * att * lighting  + LightColor * att * specularComponent, 1);
}

```

---

I don't really know why, but Blender is the root problem here; causing the exact same issue. I would appreciate any tip to solve that problem.

# Answer
It looks like your geometry may be made of unwelded boxes and you're using smoothed normals (soft edges). If my guess is correct, then the lighting looks off because the smoothed normals point outward from the corner of each box and therefore don't match the flat surface created when you place two boxes next to each other.

Try using unsmoothed normals (hard edges). You can look up in the Blender help files how to set this.
> 1 votes

---
Tags: xna, shaders, normals, lighting
---


title: SDL tiles rendering

text:
# Question
Title: SDL tiles rendering
I'm pretty new to SDL and wonder what is better if I have to draw tiled map on screen: to SDL\_RenderCopy each tile from texture(which presents tileset) and then SDL\_RenderPresent it every frame or to compose somehow map onto another texture which will be rendered every frame?

# Answer
It's probably better to just call SDL\_RenderCopy multiple times and copy to display buffer directly rather than composing and uploading an extra texture to GPU which in the end you copy to display buffer anyways.
> 0 votes

---
Tags: tiles, sdl
---


# Question
Title: Separating data from model and successfully visualizing it
This is a bit of a design question that I'm struggling with. I have a data model and an entity model. The data model is, of course, what is (de)serialized to represent my levels and entities within it, whereas the entity model is the run-time manifestation of the level actually being played.

In addition, I have a game editor that allows the levels to be edited and played all in the same UI. It has 2 modes, each with 2 views:

* Design-time Mode:
    + a top-down, interactive view of the level. This is where the actual editing of the level takes place.
    + an in-game preview of the level that updates as changes are made in the top-down view
* Run-time Mode:
    + a top-down view of the level that is non-interactive but live
    + an in-game, run-time view of the game that is interactive. ie. you can actually play the game.

The user switches between the modes by clicking play & stop buttons. Here's an example of my top-down view (this one is run-time):

Now, here is the problem: I want the design-time top-down view to mimic the run-time top-down view as much as possible, but certain information is unknown at design time, such as the texture dimensions and collision circle information. Therefore, I cannot render this information accurately.

I see these options for dealing with the situation:

1. don't try and mimic the run-time, top-down visualization. Instead, just render something that is as useful as I can make it given the limited information I have available.
2. hack my data model so that it also returns information that it really has no business knowing, such as the collision circles and texture dimensions. This would facilitate the visualization of that information, but at the cost of maintenance and code design.
3. since my design-time mode already has two views, one of which is a manifestation of my data model, and the other is a manifestation of my entity model, I could dynamically try to correlate that information for the purposes of my top-down visualizer. This seems like it should work, but also seems rather messy and error-prone.

This seems like it must be a fairly common problem when writing game editors, so I thought I'd try to gather some advice. Any input from the community would be much appreciated.

# Answer
In the end I changed my visualizer control so that it could pass some state through to the visualizers. For the design-time visualizer control, I passed through a simple context as the state. The context has this interface:

```
public interface IDesignTimeVisualizersContext
{
    Entity GetEntity(string id);
}

```

So now my design-time visualizers can look up and obtain the information they need from the run-time manifestation of the design-time data. I'm not certain this is the absolute best way, but it does work and now my design-time visualization 100% matches my run-time one.
> 1 votes

---
Tags: level-design, architecture, visualization
---


# Question
Title: Creating a game with in game programmable AI
I am looking to make a game where the player can access an in game terminal and then use this terminal to write AI logic in a programming language such as C++ or C#, then they can compile the code and apply the AI to NPC characters.

Of course if the code failed to compile error free then it would not be applied to the NPC. Mostly the code would be function calls with a few basic constructs available like int, float, bool etc.

My question is how could I achieve this in say Unity or another game engine. Would I need to use a scripting language such as LUA or Python to create the AI or could I be done in real time on a separate thread in Unity somehow?

# Answer
> 6 votes
That shouldn't be too much of a problem with an interpreted language like LUA or Python. I know about a LUA binding that's ready and available in the Unity Asset Store.

It seems there are other bindings available as well. Just search the Asset Store in the "Scripting/Integration" category. Here's one for python that I found.

# Answer
> 1 votes
You could embed a simple language such as forth or a minimal lisp, and run it's execution step by step like any other in-game activity. Cute idea, but somehow I can't imagine that your hacker/hero, frantically debugging while the monsters loom, would be very interesting game play.

It does remind me of some puzzle games, where you have to position agents in certain ways to automate the actions to a desired effect.

# Answer
> 1 votes
You can use CodeDom to compile C# code into assembly, and then run this assembly inside your code.

If this code would run in same thread as your game you have to make sure that the code that they write will not block your game code. You can use this by using yield, that will generate state machine on behind.

So you could have something like this:

```
public interface IAction {
  boolean IsFinished();
  void Update(GameTime gameTime);
}

public class Wait : IAciton {
  private TimeSpan waitingTime;
  public Wait(TimeSpan waitingTime) { this.waitingTime = waitingTime; }
  boolean IsFinished() { return this.waitingTime <= 0; }
  void Update(GameTime gameTime) { this.waitingTime - gameTime.ElaspedGameTime; }
}

```

and then users would have to write code like this:

```
public MyMonster : Brain {
  public IEnumerable<IAction> Think() {
     while (IsAlive) {
        yield Wait(TimeSpan.FromSeconds(10));
        yield Suicide();
     }
  }
}

```

Then you would process it like this:

```
public AISystem {
   public void Update() {
      foreach (Brain brain in Brains) {
          var enumerator = brain.Think().GetEnumerator();
          enumerator.Current.Update();
          if (enumerator.Current.IsFinished()) {
             enumerator.MoveNext();
          }
      }
   }
}

```

Now even if there is infinite loop, the code will not block your code. And users can write logic "sequentially".

As you can see this is essentially what unity does in its Behaviors

*(I wrote this from head so it has probably some errors in it)*

Or you can write your own CIL interpreter and interpret few instructions each frame :)

---
Tags: unity, ai, scripting
---


# Question
Title: How does one publish games on XBox One and PS4 if not in one of the allowed countries?
We want to publish our game on XBox One & PS4. According to Sony & Microsoft they plan to allow indie developers to self-publish games. Unfortunately this is their requirement:

Sony

> Located in US, Mexico, Central America, South America or Canada

Microsoft

> Located in Canada, Deutschland, Spain, France, Italy, UK, US or Japan.

Do you advise me to create a company in the United States just to publish games in my home in UAE?

How does one publish games on XBox One and PS4 when not in one of the countries listed in the requirements?

# Answer
> 3 votes
Ask Microsoft/Sony. It's not about what the law considers an US company, it's about their interpretation of what an US company is. They make their own rules here.

Sony says that you must be **physically** located in the Americas, so a post-box is unlikely to statisfy their requirements. Maybe you could get away with a staffed American publishing office which "outsources" the development to your location, but only they can tell.

---
Tags: publishing, xbox, playstation4
---


# Question
Title: Should I use a graphics engine or do the low level graphics myself?
Programming is more of a hobby for me right now as I'm still in highschool. When I get to college I plan to make it less of a hobby and more of a profession. But for now what would you guys suggest for making a 3D game in c++ (not c++11)? Should I learn and do the low level graphics myself or just use a graphics engine like Ogre while I learn the other aspects of making a game, or just use a full game engine?

My goal would be to learn. I want to learn how to do the lower level stuff such as graphics, physics, AI, ect. but I'm not sure if I should jump right into graphics or do the other stuff first.

I am currently taking the highest level math I can at my school (calculous) and might end up taking a c++ class at my local community college for a semester this year if that makes a difference.

# Answer
To provide you some advice nevertheless, I recommend to start with low level graphics programming.

There are a handful of great OpenGL beginner tutorials out there on the internet. It is not that hard to learn the basics yourself without having worked with third party engines before.

The math behind isn't that challenging, and you even took a high level course at school. Programming experience in C++ is a big plus. I would advice people who haven't worked in C++ before, to first learn the language and after that dive into graphics programming. Trying to handle both at the same time might be hard.

Depending on your interests, you could later on change to an engine like Unity which handles graphics for you, so that you can focus on your other fields of interest. That is not necessary if you're coding for learning and fun, since at that point you will already have built a working renderer system on your own. But if you consider releasing the project as a game, you could benefit from the increased graphics provided by such an engine.

By the way, what is wrong with C++11? It brings some really handy tools, like futures, lambdas, filesystem access, and more, which can increase productivity also in game development a lot.
> 0 votes

---
Tags: education
---