# Question
Title: How to: create a 3rd person view, multiple layer 3d world
Imagine a game world like in Dungeon Keeper or Sim City with an (possibly rotatable) 3rd person view, where the game world can be accessed in all dimensions (in discrete steps). For example digging into the ground and accessing a whole new layer, but with the possibility of visible connections between the layers, like an underground dome that exposes a cross-section of several z-layers.

I imagine such a world rather hard to visualize so that it stays as easy and intuitive for the player to navigate as a game world limited to 2 dimensions or from first person. Problems I could see include obstructed areas, differentiating between z-levels, placing stuff in the wrong place, navigating back and forth between places of player interest, clicking the wrong stuff because of perspective issues.

I would be willing to go to great lengths to make navigation in such a world as non-hassling as possible, and I would rather abandon the concept instead of making a frustrating interface.

Do you know any solutions to this problem, maybe even examples where it has been solved in an actual game, or at least in a concept?

(Also, I propose the "perspective" tag, can't add it yet)

# Answer
Unless I'm misunderstanding you, this sounds like the presentation that Dwarf Fortress gives, at least from a top down perspective. Or, if you're looking for isometric, people have created visualizers for Dwarf Fortress that give that effect.

For example:

As you can see the image shows multiple layers. The user is then able to "slice" down into the land. More images and information can be found on the Bay12 forums here.

Additionally you can see a video I made for my game, where I've implemented a slice feature to cut into the terrain (at 1:26). This allows the user to cut away layers of terrain to let them see inside and select terrain that would otherwise be obstructed.

Hope that helps!
> 3 votes

# Answer
I would imagine a vertically oriented coverflow approach would be pleasing.

By this I mean showing the layers as a vertically-stacked rolodex that can be flipped through, showing the underside of layers above the current level with the layers hinged together at the far z.

It would also be suited to direct manipulation with touch screens, if wanted.
> 1 votes

# Answer
I can think of two good examples of the sort of discreet cross section of z-layers that you're talking about. The first is the various *The Sims* games. Each floor of a house is a different z-layer, and movement between them is done via icons on the interface, and (I believe) shortcut keys. In *The Sims*, the only points where movement between levels was possible was stairs, which were visible if you were "above" (on the second floor) or "below" (on the first floor) them. The stairs can problems if you're trying to click on something behind them, but it's possible to rotate the camera to solve that issue. The only real source of confusion in this case would have been if a Sim was on the second floor, and you/the camera was on the first floor. The Sim would effectively disappear from view. However, this is solved by allowing the player to double click on a Sim's portrait in the interface to zoom right to them. For the first *Sims* game, you only had access to 2 floors, so it was generally pretty easy for people to keep track of the 8 maximum people in a 2 story household.

The other example is Simutrans, a freeware transportation simulator. In some ways, the game is similar to *Rollercoaster Tycoon*, in that you can cut through the landscape at will, and go underground with the push of a button. The only different is that each z-layer can be "sliced", so that you only see what's on that layer (and maybe a minimal bit of the terrain above), you can see a bit of this here. Overall, this prevents confusion in terms of selecting objects and building underground, but it can be confusing for newer players, and it's harder to get an overview of everything that is going on. However, a game like *Simutrans* doesn't require as much micromanagement as *The Sims*, so it's generally fine to miss out on a bit of the overview. Again, moving between levels is simply a matter of using the keyboard/interface, and due to being able to rotate the camera, most other problems are solved as well.

Overall, the exact solution is going to depend on the game. The *Sim City* series (except the first one) had various underground views to build pipes and subways, effectively separating the views from each other. Most games take this route, sometimes providing a simplistic version of the aboveground, so you generally know where you are, but it's still fairly well hidden. Others, like *Rollercoaster Tycoon* simply hide the terrain and let you build underground with everything else in full (transparent) sight. It can easily get confusing, though this can be helped with a "currently building here" tile highlighted. My own game uses the "slice" technique, showing only the current floor to the user, while allowing them to see the walls of everything below the current floor. Exactly how to handle the floors above them, I'm still trying to figure out, though I have a few different ideas.
> 1 votes

---
Tags: 3d, interface, perspective
---


# Question
Title: How to resolve collisions of compound shapes using SAT?
SAT is a decent way to determine collisions between arbitrary convex polygons. You'll even get the vector that is needed to resolve a collision.

To resolve collisions between complex (non-convex) shapes, I was thinking about some sort of compound-shape which consists of several convex polygons. If a collision occurs in the broad-phase (eg. circle vs. circle or AABB vs AABB), the collision would be resolved by checking each polygon in the compound shape vs. each polygon in the other compound shape.

I wonder what's the best way to actually separate the objects though? A naive approach would be to just take the vector with the highest magnitude and use that for separation. In the following picture, this would be **V2**

However if the separating vectors point into different directions, the collision cannot be resolved right away and might require several iterations. So in the next picture we would separate using **V1** and in another iteration by **V2** (or something close to V2, as the shape would have moved by the amount of V1).

This approach will fail with separating vectors that point into the opposite direction of each other or in a case like shown in the following picture:

Here we would iterate endlessly between the state on the left and the state on the right.

So to ask an actual question here: What's a reasonable approach to this problem? I guess using compound polygons for complex shapes is a reasonable idea but I really wonder how collisions should be resolved in that case? How do I detect a dead-end as shown in the third image?

# Answer
> 7 votes
I think you may be trying to fit a square key into a round hole by applying SAT in the way you are, here. Obviously, it's not designed for concave-concave collisions, and though I commend your effort to adapt it for that purpose, there are considerations that make this unlikely to work.

**Realism**

Angular impulse and it's knock-on effects are the name of the game here.

The order of contact points is important for realistic collision resolution. In the real world, one of those points is always going to strike before another. And it's only in emulating that contact order and the results of each "subcollision" represented by that, that you can expect to get a realistic result in simulation. This is one of the very reasons why you are breaking down your concave into convex, in the first place -- it allows piecewise detection of which part has struck first. Of course, this can also be emulated as per my comment under the "Less realism" heading.

Your convex fixtures combine to give the object both it's outline and its centroid (and of course in more complex simulations, each fixture can affect the density differently, as well). The reason I mention this is that in resolving collisions realistically, you are going to have to calculate not only linear but also angular impulse, following each "sub collision" of your contact points. It is not as simple as the basic "push apart" you apply with SAT.

This then completely changes the nature of your problem, because as you can see, it is pointless getting and trying to *use* 2 or more contact points, because really it is only the first one that matters. Once you have then resolved the first in terms of linear and angular impulse, you will need to recalculate for further collisions, because the orientations of each object will have changed. Further to that, detecting each individual contact in the step then may *or may not* need to be done within that same step -- depending on the timing between contacts as the objects' first contact point touches, subsequent linear and angular impulse is applied, second contact point touches, and so on.

**Less realism**

Of course, assuming you are not at all interested in resolving for angular impulse, then the best you can do with SAT becomes essentially exactly what you would do if you wrapped these polygons as convex using something like Graham's Scan: Pushing apart by the single separating vector. In other words, it makes little sense to be trying to resolve three vectors in tandem, as you've demonstrated. It's the biggest in the bunch that counts.

**EDIT in response to your question**

What you need to do if you want a simplistic approach is as follows:

* Determine the correct *direction* of displacement. This is most easily done by convex hulling each, and determining the normals to the separating axis.
* Now you need to determine the displacement *magnitude*. Why can't we just use the magnitude as given by SAT? Because if you think about it, the interpenetration depths are going to be potentially greater for convex hulls, than they will be for their matched concave hulls -- think of two E's with their teeth in each other! As you've done above, find all contact points for a given step, but find them *parallel* to the axis normals, because this is the correct direction of displacement. Now determine which one of these parallel overlap vectors is longest. Displace by that one, discard the rest and proceed to next physics step.

---
Tags: collision-detection, computational-geometry, collision-avoidance, separating-axis-theorem
---


title: Collision detection problem

text:
# Question
Title: Collision detection problem
I am a novice in android. It's my first game, so I am trying to make a frogger clone. I am getting a problem in collision detection. In logcat, even though the frog is not moving and not colliding anywhere, I still get a "collision detected" message. Also, if the frog collides, it is not responding.

Please help me find the problem.

Here is an excerpt of my code:

```
Game class

    private Frog frog;
    private FrogControl fg;
    private FrogControlY fg1;
    private MainThread thread;

    ImageView imgview = (ImageView) findViewById(R.id.imageview);
    ImageView imageArr[] = new ImageView[20];
    int id[] = { R.drawable.audi_r8, R.drawable.bike, R.drawable.bus,
            R.drawable.car, R.drawable.chrysler, R.drawable.cruise_bike };

    ArrayList<Vehicle> vh = new ArrayList<Vehicle>();
    ArrayList<VehicleReverse> vhs = new ArrayList<VehicleReverse>();

    public Game(Context context) {
        super(context);
        getHolder().addCallback(this);
        frog = new Frog(BitmapFactory.decodeResource(getResources(),
                R.drawable.frog), 100, 400);
        fg = new FrogControl(BitmapFactory.decodeResource(getResources(),
                R.drawable.arrow), 250, 400);
        fg1 = new FrogControlY(BitmapFactory.decodeResource(getResources(),
                R.drawable.arrow), 0, 400);
        int noOfCar = (int) Math.random() * 5;
        int totalCar = 3 + noOfCar;
        for (int j = 0; j < totalCar; j++) {
            int y = (int) (Math.random() * 3);
            int[] LaneSelection = { 50, 150, 250 };
            int yValue = LaneSelection[y];
            int x = 0;
            int frogX = frog.getX();
            int frogY = frog.getY();
            int frogW = fg.getX();
            int frogH = fg.getY();
            vh.add(new Vehicle(BitmapFactory.decodeResource(getResources(),
                    id[y]), x, yValue, frogX, frogY, frogW, frogH));
        }

        for (int k = totalCar - 1; k > 0; k--) {
            int y = (int) (Math.random() * 3);
            int[] LaneSelection = { 100, 200, 300 };
            int yValue = LaneSelection[y];
            int x = 300;
            vhs.add(new VehicleReverse(BitmapFactory.decodeResource(
                    getResources(), id[y]), x, yValue));
        }
        thread = new MainThread(getHolder(), this);
        setFocusable(true);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        // TODO Nothing
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        thread.setRunning(true);
        thread.start();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        boolean retry = true;
        thread.setRunning(false);
        while (retry) {
            try {
                thread.join();
                retry = false;
            } catch (Exception e) {

            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            // vh.carmove();
            fg.handleAction((int) event.getX(), (int) event.getY());
            fg1.handleActionY((int) event.getX(), (int) event.getY());
            if (fg.isTouched()) {
                // fg1.setTouchedY(false);
                if ((int) event.getX() < (250 + (fg.getX() / 2))
                        && (frog.getX() > 0)) {
                    frog.frogShiftLeft();
                    // fg1.setTouchedY(true);
                }
                if ((int) event.getX() >= (250 + (fg.getX() / 2))
                        && (frog.getX() < 300)) {
                    frog.frogShiftRight();
                }
            }
            if (fg1.isTouched()) {
                // fg.setTouched(false);
                if ((int) event.getY() < (380 + (fg1.getY() / 2))
                        && (frog.getY() > 0) && ((int) event.getX() < 100)) {
                    frog.frogShiftUp();
                    // fg.setTouched(true);
                }
                if ((int) event.getY() >= (380 + (fg1.getY() / 2))
                        && (frog.getY() < 400) && ((int) event.getX() < 100)) {
                    frog.frogShiftDown();
                }
            }
        }

        if (event.getAction() == MotionEvent.ACTION_MOVE) {
        }

        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (frog.isTouched()) {
                frog.setTouched(false);
            }
        }
        return true;
    }

    public void render(Canvas canvas) {
        canvas.drawColor(Color.BLACK);
        fg.draw(canvas);
        fg1.draw(canvas);
        frog.draw(canvas);
        for (int j = 0; j < vh.size(); j++) {
            Vehicle o = vh.get(j);
            o.draw(canvas);
            o.collision();
            /*
             * if(o.collision()){ //Frog f = new
             * Frog(Bitmap.createBitmap(null)); //frog.remove(); /*Intent intent
             * = new Intent(); startActivity(intent);
             */
            // }
        }

        for (int k = vhs.size() - 1; k > 0; k--) {
            VehicleReverse v = vhs.get(k);
            v.draw(canvas);
        }
    }
}

vehicle class:
package com.froggergame;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.util.Log;

public class Vehicle extends Thread implements Runnable{

    private static final String TAG = null;
    public Bitmap bmp;
    public int x;
    public int y;
    Frog frog;
    FrogControl froggy;
    Vehicle vehicle;
    int frogX,frogY;
    int frogW, frogH;

    public Vehicle(Bitmap bitmap,int x,int y,int frogX,int frogY, int frogW, int frogH){
        this.bmp=bitmap;
        this.x=x;
        this.y=y;
        this.frogX=frogX;
        this.frogY=frogY;
        this.frogH = frogH;
        this.frogW = frogW;
    }

    public Bitmap getBmp() {
        return bmp;
    }

    public void setBmp(Bitmap bmp) {
        this.bmp = bmp;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public int getW(){
        return bmp.getWidth();
    }

    public int getH() {
        return bmp.getHeight();
    }

    public void setY(int y) {
        this.y = y;
    }

    public void carmove(){
        try {
            System.out.println("carmove");
            x = x + 5;
            if(x>=300){
                x=0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        setX(x);
    }

    public boolean collision(){
        System.out.println(getW());
        System.out.println(getX());
        System.out.println(getH());
        System.out.println(getY());
        System.out.println("Froggy x pos"+frogX);
        System.out.println("Froggy width"+frogW);
        System.out.println("Froggy y pos"+frogY);
        System.out.println("Froggy height"+frogH);

        if((getX()+getW()>=frogX)&&(getX()<frogX+frogW) && (getY()+getH()<=frogY)&&(getY()<frogY+frogH))
        {

            //frog = new Frog(Bitmap.createBitmap(null));
            Log.v(TAG, "Collision Detected");
             return true;
        }else {
            //Log.v(TAG, "Not collided");
            return false;
        }
    }

    public void draw(Canvas canvas){
        canvas.drawBitmap(bmp, x, y,null);
        carmove();
        //collision();
    }
}

```

# Answer
> 1 votes
You're not doing anything in response to what's returned by Vehicle.collision().

In render():

```
o.collision();
/*
* if(o.collision()){ //Frog f = new
* Frog(Bitmap.createBitmap(null)); //frog.remove(); /*Intent intent
* = new Intent(); startActivity(intent);
*/
// }

```

---
Tags: android, collision-detection
---


# Question
Title: Non-destructive way to edit alpha channel in Photoshop/Gimp image
Looking to make textures for Unity3d, and I'm stuck at what seems to be a simple stage. My goal is to create an RGBA image, with color information for every pixel, and a separate alpha channel. These two components get fed into Unity as base color and reflection strength, respectively. (Using "Reflective/Bumped Diffuse" material.)

If I use masking tools in Photoshop, I can erase parts of the output image (transparency). However, I would like to keep the original RBG color information when output, and not just have "blank" areas. Also, it would be nice if I could do it non-destructively, ie. the final alpha channel is dependent on a standard layer, or built from a path object, etc.

I have the same problem with The Gimp.

Any help on this would be greatly appreciated.

(If Photoshop/Gimp are not the tools for the job, can someone please recommend a better one?)

# Answer
**Photoshop Solution**

Deleting a section of the image is only affecting that layer. What you want to do is create a separate channel which stores your Alpha information.

1. In the **Tool Panel** with *Layers/Channels/Paths*, choose the **Channels Tab**. Here you will see RGB, Red, Green, and Blue.
2. Create a new channel using the button at the bottom of the panel, this is your Alpha Channel. This is an 8-bit greyscale channel giving you 256 levels of transparency.
3. You can use the little "eye" icons to toggle this channel on/off.
4. Draw or copy/paste your information into the channel.

*Note:* When saving you need to be careful about file formats. Things like .Tiff & .TGA save the full alpha channel independent of color information. However Photoshop doesn't allow this with PNG, much to many developers annoyance. It will not properly save Alpha Channel images and tends to strip out color information for fully transparent areas to compress file size.
> 4 votes

# Answer
I find the best way to do this in The GIMP is to use a layer mask (right click on a layer and create mask).

The layer will then have two "images" associated with it - the RGBA image and a grayscale layer mask which acts as an extra (multiplicative) alpha channel. You can click either of these images to select which one will be edited.

If you hold CTRL and click the layer mask, you will see just the RGBA image (this disables the mask). If you hold down ALT and click the layer mask, you will see just the layer mask.

**When you export an image with an active layer mask, the exported image will retain the colour information even from areas that the mask makes fully transparent.**

For your purposes, you may find it effective to compose your alpha channel on a separate (RGBA) layer - then when you are done you can just copy this layer into the layer mask of the original layer.
> 5 votes

# Answer
In the GIMP, one way would be to split the image into layers for each channel. Select "Colors-\>Components-\>Decompose" and choose RGBA or whatever channels you want to break into layers. Then edit your individual alpha and color channels as you see fit (they should be greyscale), then go "Colors-\>Components-\>Compose" choose your desired channel layout and choose your layers to use for each channel.

Also, you can use the "Channels" dialogue. It should be a part of the default toolbox things, but if not you can select "Windows-\>Dockable Dialogues-\>Channels". You can toggle visibility of each color channel, and by clicking and highlighting the channel names you can choose which ones to edit individually (it looks like it preserves color with alpha, although I don't see a way to "hide" the alpha while editing without hiding the entire image...).
> 2 votes

# Answer
To write your own content processor (as suggested by @Andrew Russell) specific to Unity3D, place this script in your `Assets/Editor` folder will combine any image `*-Base.*` with a similarly-named `*-Alpha.*` file and modify the original texture:

```
class AlphaCombinerPostprocessor extends AssetPostprocessor {
    function OnPostprocessTexture(texture : Texture2D)
    {
        if (assetPath.Contains("-Base.")) {
            var fn = assetPath.Replace("-Base.","-Alpha.");
            var alpha = AssetDatabase.LoadAssetAtPath(fn,Texture2D);
            if (alpha) {
                Debug.Log("Adding alpha from "+fn);
                var c : Color[] = texture.GetPixels();
                var a : Color[] = alpha.GetPixels();
                if (c.Length != a.Length) {
                    Debug.LogError(fn+" is different size to "+assetPath);
                    return;
                }
                for (var i=0; i<c.Length; i++)
                    c[i].a = a[i].a;
                texture.SetPixels(c);
                texture.Apply(true);
            }
        }
    }
}

```

Adapt to your own asset file naming conventions.
> 2 votes

# Answer
One alternative is to write your own content processor to perform the operation you want. That way you could simply give your "reflectivity" layer (or even multiple reflectivity layers) a special name, and have the content processor put that data in the alpha channel for you. (Or indeed implement any kind of process that you like.)

If you were using XNA and The GIMP (this is what I use and am familiar with), then it would be very easy for you to add this XCF importer to your content pipeline and make the necessary modifications to process specially named layers.

As you are using Unity, not XNA, I am not familiar with what content pipeline options you have available. But perhaps you can adapt the linked code so that it works within your content process.
> 0 votes

---
Tags: graphics, tools, unity, textures
---


title: Graphical Interface Design

text:
# Question
Title: Graphical Interface Design
I have the following problem: Although I know some of color theory, and the interface design ideals (about how it must be usable, and etc...), my interfaces are REALLY ugly. fugly, eye bleed material, etc...

I am not finding anywhere, information on how to create the graphical part of a interface, how to choose the layout, objects, colours, cursor, etc...

I am doing now most by copying other games, or by "feeling", something that does not always work correctly...

So, what I need to know about it? Where I find it? How I do it?

# Answer
Unfortunately, there are no real interface design standards in the game industry, which makes it difficult to find accurate information this topic. If game interface design is something you're seriously interested in, I would take the following steps:

* **Learn as much as you can about interaction design patterns** \- A lot of the research done on design patterns doesn't directly relate to video games or software for that matter, but if you look hard enough, you'll find that there are a lot of parallels.
* **Learn general computer UI theory** \- When is a text box better than a drop-down/combo-box? What are the strengths and weaknesses of each?
* **Learn from the successes and failures of others** \- Look at, and dissect as many UIs as you can (and don't limit yourself just to games!). Go through each UI element, analyzing how and why the component behaves that way. For example:
    + In an FPS, why does the reticle expand when the player shoots? Why does it contract when you crouch or prone?
    + In a fighting game, when a player takes damage, why does their health bar deplete immediately, instead of fading over time?
    + In a RTS, what is the purpose of the minimap?
    + In any game, how do you know if you're winning/losing?
    + What steps does the player have to go through to start a new game, load a saved game, change the options, exit the game, etc.? Could this process be simplified?
* **Practice, practice, practice!** \- Once you feel like you have a good understanding of what UIs are out there, and how they're composed, try your hand at creating UIs again. Remember to always analyze your work, in addition to having others critique it, from time to time.

I haven't run across any particularly good game UI reading material, but below are a few interaction design books I highly recommend looking into:
> 8 votes

# Answer
General purpose computer interface design techniques may be more helpful than game-specific ones. Computer interface design can be split into two parts, the aesthetics and the usability. However, it is important remember that the two are related, similar to the coloring/shading on a piece of art, and the composition/lineart.

For usability, consider things such as Fitt's Law to determine appropriate sizes for UI elements. Fitt's Law implies that objects in the corners of the screen are the easiest to hit. That only applies to mouse-based interaction though, which provides resistance on the edges of the screen.

As for aesthetics, consider basic principles of design, such as composition, and the "weight" attributed to things of different colors and shapes. Color theory will help you, as well as keeping in mind that the apparent color of an object is altered by the color of the things around it. Also consider other elements and principles of design.

When analyzing the UI of other games, take these basic elements into account. Where does your eye go first? How does it move though the interface? Understand what draws your attention and why as opposed to just copying the UI of another game.

Like others have said, design is an art, not a science. If you don't have the feel for it, perhaps it is not for you. Technical people tend to have a good sense of composition though, so not all is lost.
> 1 votes

---
Tags: gui, interface, ui-design
---


title: How is 2D lighting implemented?

text:
# Question
Title: How is 2D lighting implemented?
I am wondering what the best way to approach a "lighting" effect in 2D games is. For instance, if my main character is glowing, what techniques can I use to complete the visual effect of the character glowing when it is near other objects which would be affected by the light?

# Answer
You could overlay a simple glow effect texture with soft transparent edges. If you want lighting/shadows similar to what you may find in a 3d world you could do something like this: http://www.catalinzima.com/2010/07/my-technique-for-the-shader-based-dynamic-2d-shadows/. However, if you are new to HLSL, then that may be a little bit too much.

**edit**: I stumbled onto a nice HTML5 2d light tutorial
> 39 votes

# Answer
There is an open-source XNA project which is an excellent library and implementation of 2D lighting that happens to be compatible with XNA 4.0's Reach profile - Krypton XNA.
> 7 votes

# Answer
You would need a postfilter shader effect written in HLSL or GLSL. The shader would receive the player coordinates and modify the brightness for all pixels in a certain range. XNA supports 2D shaders quite good.

Another solution would be to simulate brightness by using a texture with an alpha-channel. The texture would be mostly black except for a transparent spot in the middle. This texture we be an overlay over your game screen with the transparent spot centered on the 'glowing' player character. Old adventure games used this technique to simulate flashlights.
> 4 votes

# Answer
After some searching, this blog seemed like a good start:

http://www.soolstyle.com/2010/02/15/2d-deferred-lightning/

be sure to read the comments because there are some improvements there, but the blog post will get you started :).
> 4 votes

---
Tags: xna, 2d, lighting, graphic-effects
---


# Question
Title: Polygon editor to draw collision data over image
I need an editor to plot a polygon over the texture for of a ship in my game.

It would look like this..
Where the red is the collision outline and the image is the texture.

I want to store the polygon like texture coordinates eg top left is (0, 0) and bottom right is (1, 1).

Are there any tools (free) that does something similar to this, I'll be working with xna and C#.

# Answer
On OS X, you can use PhysicsEditor. It is a tool for Box2D or Chimpmunk but there is a txt export for your need. The main difficulty is to find a mac.

Note: there is a windows version too. But i didn't use it. Try it and add a comment if it is useful.
> 4 votes

# Answer
InkScape is a good choice for vectorial images.

* Size your document to 1m x 1m...
* Add the bitmap...
* Draw the polyline...
* Save as .svg or .xaml document... whose are text based...
* Develop a light parser to load the data
> 3 votes

# Answer
While a tool like PhysicsEditor (see Ellis answer) is certainly better, the poor mans choice would be to use an HTML-image-map editor. The coordinates for image-maps are in pixels, but you could simply divide these by *image-height* or *image-width* respectively to get coordinates in the 0..1 range.

Here's an online-tool to draw such image-maps, and here's another one.
> 1 votes

---
Tags: xna, collision-detection
---


# Question
Title: Why place entity config outside of scripts?
I've seen a lot of games that define the entity components in script files, but when they configure each entity and specify what components it has, they use some other file format (like XML). Why do they do that?

I'm asking mostly to see what others' rationale was for this. I *also* configure my entities outside of scripts (though I chose JSON not XML). My reasons for doing this are to make it easier for me to implement save games and also because I think this kind of configuration is better organized in something like XML or JSON.

---

**@Christopher Larsen's answer:** *Too long to post as a comment*

I fear you might have deviated a bit from the subject of the question. The problems you are describing are more related to hierarchy-based entities; note in my question I mentioned I was talking about component-based entities.

Here's an example of what I wanted to ask. Below are two alternative ways to configure an entity: through the script and through an external JSON file. My question was, why do so many people prefer to configure the entity outside of scripts?

*A base Entity class:*

```
class Entity:
    def __init__(self, name):
        pass
    def addComponent(self, comp):
        pass

```

*The script approach:*

```
orc = Entity('Orc')
orc.addComponent(PositionComponent(3.4, 7.9))

```

*The JSON approach:*

```
{
    "name" : "Orc",
    "components":
    {
        "PositionComponent": {
            "x" : 3.4,
            "y" : 7.9
        }
    }
}

```

I already stated my reasons for using this approach, which are technical and organizational. I wanted to know why so many others (from what I've seen) use this.

# Answer
> 13 votes
The major advantage that comes to my mind is that it allows the configuration to be edited/managed by a non-programmer without requiring them to touch any of the game scripts.

# Answer
> 6 votes
One reason I usually use a config file rather than script for this is:

The only way to check a script for correctness e.g. specifying all values and such is to run it.

Writing code to allow scripts to configure the values means writing code to create skeleton objects for the scripts to fill the values in and then validating that the script did so and such. Its more code and buggier code than loading from a flat config file, often using a library that supports some kind of validation mechanism.

# Answer
> 2 votes
The entity configuration can be simply a *serialisation* of a specific entity. This lets you handle game editing and modding tools' output roughly the same way as you would a save game. In particular, for games where you can't predict in which state a given entity will be during game saving - for example because of their AI or because they are partially procedurally generated in the first place - it's useful to be able to dump the whole data defining what an entity "is" (as opposed to what it "does") as a byte stream to be saved.

# Answer
> 1 votes
The pattern you describe is an implementation of a Data Driven System.

Data driven systems are commonly used in game development as they allow for the definition of content to be encapsulated external to the source. This external representation can then easily be modified (and even updated in realtime by an application watching for modification) to change the way an entity behaves.

Once the data is defined externally, you have all sorts of possibilities in how the designers interact with it ranging from directly editing text files (ugh!) to sophisticated UIs that guide the designer's choices in a logical, consistent and even verified for correctness (from the perspective of game balance) manner.

If the data were embedded directly in the code, any changes would require a rebuild of the application which for large projects is moderately time consuming as well as the time required for deployment of the binaries (e.g. new binaries must be deployed to and installed on the server).

Let's take an example of a sterotypical entity the "orc"...

One way of implementing for our orc would be to write a complete description in code of all of the characteristics and logic for the orc.

* maxhealth=10
* damage=3 damage per second
* runaway=true
* runawaywhen=health \< 10
* aggressive=true

When we instantiate orcs, all of their values are initialized exactly the same (or perhaps are static). The issue that arises is some designer is going to come along and say "We need a different type of orc for newbie areas, that has less health, never runs away and is not aggressive. That will let new players get used to combat without the increased difficulty and confusion while learning the combat system".

Great, now you need a different class or (maybe we were forward looking) adjust the values we feed into the "factory" that creates orcs when creating them in a "newbie" area. So we make the changes, deploy new binaries. Only to have playtesters come back and say the new health values are too low as we kill the orcs in one hit.

If our systems were data driven (and bonus points for applications that support reloading when modifications are made), then the modifications necessary to satisfy the designer and play testers are simple data changes with no recompile/deployment required. This makes designers happy because they are not stuck waiting for code changes, and it makes programmers happy because we are constantly modifing the source code to tweak values.

Taking data driven systems to extremes allows everything from game levels, spells, and even quests to be implemented by simple changes to your data requiring no code changes at all. In the end, it is about making it easy to create, tweak and iterate on the game content.

# Answer
> 0 votes
In your example you are actually using two scripting languages already. This is the manner I would say in the long run works out better but I would suggest that you unify the scripting language you are using. If the script example you gave was done in Lua then instead of Json, I would say use Lua's tables to build your object up. The syntax would actually be similar and allow you to support one interface for exposing your components.

To touch on why people choose to do it usually in XML and then script in logic, is that this makes sense when you say it. Here is my definition of the object in data, what is a good data storage format? It's almost always XML (though I also go with JSON ;). And then when they want to add in logic, well that is either coded or put into a script file.

Its not wrong thinking but in my eyes people are just not going to the next step. Look at any full language, c/c++/c#,. You can define the objects and their logic all in one language, why not do the same in your scripting interface... It's almost like saying we should define our classes in XML and our methods in c# when you think about it. Maybe older game scripting languages were not powerful enough and it's still just holding on as the way it was done.

---
Tags: component-based, scripting, entity-system, xml, configuration
---


# Question
Title: XNA Platformer Collision: PerPixel vs Rectangle
I'm writing a platformer engine with XNA and was wondering what method for handling collisions I should use. Would I be seeing some performance issues if I were to try and have PerPixel collisions? Should I be using per pixel collision handling or rectangle collision handling?

# Answer
In general, per pixel collision detection is much more expensive; so as much as possible, use rectangle collision handling. (Even for per-pixel, use rectangles first to check for overlap.) When I implemented collision detection in Radiant Wrench, this is precisely what I used.

Alternatively, you can try Flat Red Ball (which I used to use before), which uses polygons for detection (which is quite performant). You can use basic types (rectangle/circle) or create your own polygon from verticies. They don't support per-pixel collisions though.
> 4 votes

---
Tags: xna, collision-detection
---


# Question
Title: For voxel rendering, what is more efficient: pre-made VBO or a geometry shader?
Given a fairly static voxel array, what is more efficient: using the CPU to pre-generate a VBO to render the voxel faces (ignoring more advanced forms of rendering like marching cubes for now) or using a geometry shader on the GPU to generate the faces on the fly?

I'm not that worried about updating changing voxels but of course that is a benefit of the GPU-version since you don't have to rebuild the VBOs. Also, the GS approach feels a bit more modern :)

On the other hand, I haven't looked at the details on how a GS actually works with the rasterization pipeline in modern GPUs. Does it output the vertices into a sort of stream-cache or is the vertices written to the normal GPU memory in between? If it's the latter, then on-the-fly generating could reduce the available bandwidth and processing power from the rest of the GPU tasks I guess and then it would be more beneficial to do it on the CPU..

# Answer
I'm thinking of a minecraft type scene, where by voxel you mean a world of blocks that are actually rendered using polygons:

If you use a geometry shader it will be difficult to avoid having exactly three faces (or whatever) per voxel.

If you have lots of adjacent blocks that are of the same texture then you can use tiling of the textures to have much less triangles in your (degenerate) strip in a VBO approach. I mean, if there is a nice big flat 6x6 area of grass voxels, you can draw the entire top in just 2 triangles rather than 64.

With the GS approach you can't do the trivial culling of faces occluded by adjacent voxels that is very straightforward with a VBO approach either.

I have not tried the GS approach, but I can say that the VBO approach with combining of repeating adjacent tiles works very well. I found messing with element indices to be much slower than just repeating the vertices. If you split your world into nice small cubes you can typically use just one byte per component per vertice and even pack the texture info and normals (a face on an axis-aligned cube has only 3 possible normals) etc into a forth byte to make 4 bytes per vertex which is nice and fast.

I have used separate VBOs for each of the 6 faces - you only ever need to draw at most 3 of them obviously. This fits nicely with the different texturing usually used on the top-parts of minecraft-style voxels. Because for each set the normal and such is then uniform.

With use of vertically-tiled pixmaps in an atlas with `GL_REPEAT` on the horizontal axis and having 90-deg rotated versions of the pixmaps in the same atlas I found I can draw massive amounts of apparently different blocks using the same VBO in the same call. In the 6x6 grass area example, I'd have split that into 12 triangles as I only have repeat on one dimension in my atlas.

I've mostly been getting this to work on the very low end of integrated graphics chips and mobile, where GS is just something I can dream about one day playing with.
> 9 votes

# Answer
What about the third option, using instanced arrays? Basically you draw many many boxes (made of a simple 8-vertex cube) with a single draw call, sourcing the positions (and other data) as per-instance attributes from the voxel-data VBO (using `glVertexAttribDivisor` in OpenGL, I'm sure DX has that, too). This might be faster than the geometry shader approach although the application code (non-shader) should be quite similar, as I remember geometry shaders having a reputation for being slow, although I have no experience with them (or instancing) as I still sit on 2.1 hardware.

But anyway, either geometry shaders or instanced arrays should be more suited than CPU-built voxel geometry, especially when the voxel data is subject to change. In conjunction with transform feedback (stream output in DX?) you might be able to setup some good GPU based culling technique.
> 10 votes

# Answer
Geometry shader version sounds much better to me. You can have only point vbo and construct box on the fly (input point, output triangle stream). It will be fast (even faster if you will use tessellation unit in the shader model 5 eq. DX11) and will reduce bandwidth extremely, it will be nice and clean solution.

About GS. It is putted between vertex shader and pixel shader and modifies the outputed vertex(primitives) stream. While vertex shader works on the vertices only, geometry shader works on whole primitives. Output of this stream goes only to the pixel shader (and is rasterized before that off course :)) and there is no way to save it. (Maybe by some crazy rendering to texture and then parsing it... but no real simple possibility)

Performance note: You should be able to to everything in the geometry shader and skip (just pass data) vertex shader. But it not best way. Better (faster) is to do most of possible transformation on the vertex shader and try to minimize geometry shader program. Don't be afraid to use for cycle if you will need it (for box creation for example). Compiler will unroll it for you.
> 1 votes

---
Tags: opengl, directx, shaders, voxels
---


# Question
Title: Create vertices + indices for cylinder with triangle strips
I'm trying to create vertex and index buffer for a cylinder (in OpenGL, but it shouldn't matter). I think my vertex buffer is fine (I checked drawing with `GL_POINTS`). Here's the code that builds it:

```
int sides = 10, slices = 40;
float radius = 3.5 * 10.0;

numVertices = sides * slices;
Vertices = malloc(sizeof(Vertex) * numVertices);

int angleincs = 2*M_PI/sides;
int cs_angleincs = 2*M_PI/slices;
float zval;
float zstep = height / (float)sides;

float i;

for(int m=0; m<slices; m++)
{
    int index = (m*sides);
    for (int n=0; n<sides; n++)
    {
        Vertices[index + n].Position.x = cosf(i);
        Vertices[index + n].Position.y = sinf(i);
        Vertices[index + n].Position.z = zval;

        i += angleincs;
    }

    zval += zstep;
}

```

I'm stuck at the index buffer generation. Any help on how to build it? I tried to adapt some code from a torus generator, and I get something that apparently resembles a cylinder but it's a bit weird and has a few extra weird triangles.

```
numIndices = (2 * (sides+1) * slices + slices);
Indices = malloc(sizeof(GLushort) * numIndices);

int n=0;
for (int i=0;i<slices; i++) {
    for (int j=0; j<sides; j++) {
        Indices[n++] = i * sides + j;
        Indices[n++] = ((i+1)%slices) * sides + j;
    }

    Indices[n++] = i * sides;
    Indices[n++] = ((i+1)%slices) * sides;
    Indices[n++] = ((i+1)%slices) * sides;
}

```

Thanks in advance.

# Answer
To texture a cylinder you typically use `GL_TRIANGLE_FAN` for the top and bottom and a `GL_TRIANGLE_STRIP` (just a normal array, without element arrays) for the around.

This is code to produce a normal array of vertices to be used with an array.

```
// draws a cylinder 'height' high on the y axis at x,y,z position
const float theta = 2. * M_PI / (float)sides;
    c = cos(theta),
    s = sin(theta);
// coordinates on top of the circle, on xz plane
float x2 = radius, z2 = 0;
// make the strip
glBegin(GL_TRIANGLE_STRIP);
for(int i=0; i<=sides; i++) {
    // texture coord
    const float tx = (float)i/sides;
    // normal
    const float nf = 1./math.sqrt(x2*x2+z2*z2),
        xn = x2*nf, zn = z2*nf;
    glNormal3f(xn,0,zn);
    glTexCoord2f(tx,0);
    glVertex3f(x+x2,y,z+z2)
    glNormal3f(xn,0,zn);
    glTexCoord2f(tx,1);
    glVertex3f(x+x2,y+height,z+z2);
    // next position
    const float x3 = x2;
    x2 = c * x2 - s * z2;
    z2 = s * x3 + c * z2;
}
glEnd();

```

It is straightforward to adapt this to have store those vertices in a VBO for `glDrawArrays` to use.
> 1 votes

---
Tags: procedural-generation
---


# Question
Title: How do I calculate logical velocity / direction?
I have a simple jBox2D (Java) implementation of a world with couple of Circle bodies that at the begining are static.

I want to make them movable when the user touches the circle. But I want them to be movable from the point where it's touched to its logical velocity direction.

How do I set the velocity / direction of the body after the touch so that it moves to the point that is logical to the touch?

10x

# Answer
> 2 votes
If you simply want it to move toward your finger and stop there, you need to call `setAngularImpulse()` using the vector between your finger location in world space (needs translation from screen space) and the world space location of the object itself. Once it gets near (see note) to your finger, begin slowing it down, or else just set it's velocity to zero.

NOTE: Due to floating point errors, it's unlikely to ever get exactly *to* the precise touch location, but it will get very, very close. So you need to determine if it's within a small radius of the touch location. Use pythagoras to determine the distance the touch location.

---

If you want kinematic motion, i.e. dragging the circles, and once you let go, they keep flying off in the direction of motion they were experiencing...

Look into kinematic bodies in Box2D. Kinematic basically means the position is controlled directly by some non-physics input, such as user input. This differs from dynamic bodies which can only be affected in a "natural" way by world physics. This is akin to saying that normal human beings (dynamic bodies) would bounce off a wall if they ran into it, whereas Superman (kinematic) would just bash that wall right down regardless that his weight and size couldn't possibly do that in reality. These sorts of objects tend to have infinite mass, as no matter what the user does, it must be followed as input. So if you had a bucket of bodies, and one of them was kinematic / controlled by dragging, then if you dragged it, all other bodies would fly apart to get out of the way of your drag-input.

---
Tags: java, box2d, andengine
---


# Question
Title: Unity or MonoTouch with XNATouch/MonoGame? same price
After figuring out the pricing of monoTouch and Unity, I've found that the pricing will be the same ($800). With XnaTouch/MonoGame for monoTouch I am able to port my games to droid/apple. I am just curious if anyone has tried both XnaTouch and Unity and which one they prefer.

I do mostly 2D games (if Unity had a 2d Engine I would be all over that) so xnaTouch seems that it might be better, but Unity seems better for more advance/professional (more companies are using it, so if I ever wanted to do this for more than just myself I have more options, which I've thought about)

(I also read somewhere that monoTouch is against the new apple term of agreement?)

# Answer
Try out the Corona SDK. You can publish to both Android and iPhone and it's much cheaper. Plus you can try it for free for as long as you want (you have to pay to publish to the stores App Store/Android Market).
> 2 votes

# Answer
I presume that you mean MonoTouch + MonoGame (formerly XNATouch). There are several successful iOS games deployed using that combination. It seems that either way you can port to/from iOS/Android, so the question be comes which do you like better?

I believe that the iOS terms were adjusted to permit things like MonoTouch; however, (my optinion follows) *Since Apple runs the iOS environment, you will **alway** be at their mercy, whatever Steve Jobs decides isn't kocher for iOS will be given the boot.* with that said; I would probably not hesitate to use MonoTouch to develop commercial software for iOS.

In terms of Unity if you really think it might be a better option than MonoTouch and MonoGame, I'd try out the free version of Unity and see if you like the tooling and the development experience, if you like it go for it and if you don't, head to MonoTouch.
> 1 votes

# Answer
I know several MonoGame games on the iOS store ( check the monogame.codeplex.com for the current list ). I'm releasing my second MonoTouch app next week ( look out for Murder Map ). I plan to port the app to WP7 and Android. So from my perspective, Mono and the whole MonoTouch/Mono4Android investment is fruitful.
> 1 votes

# Answer
While I have high hopes for Mono and the iPhone I would probably wait to adopt that platform for iPhone / Android development at the moment. Attachment, the company which currently owns MonoTouch, recently laid off the developers responsible for Mono. They are starting a new company and plan to create a second product in the same vein as and compatible with MonoTouch\[1\]. But things are obviously in flux, so investing in MonoTouch today may be unwise.

1: http://tirania.org/blog/archive/2011/May-16.html
> 0 votes

---
Tags: unity, mono, monotouch
---


# Question
Title: How are the graphical effects in the Android game Orbital created?
I would be very grateful if someone could tell me how the graphics (and in particular, the lighting effects) for this game, Orbital, are created. Would it be OpenGL?

For some background: I'm new to this, and I really like these style of graphics, but I've no idea where to begin -- I'm just trying to figure out which direction I should be headed in. I have a very basic knowledge of Java, and I'm just starting to work with Android now. I have made simple games in Java in the past.

# Answer
> 2 votes
OpenGL is a good bet; one could produce graphics like that with just about any 3D graphics framework, though. The effect is making use of glow or bloom shaders pretty heavily -- you can find a lot of information around the internet on them, for example here is a related question from GDSE itself.

The shaders appear to be applied to a world composed largely of vector-based objects (which basically means they are defined as a series of line or curve segments instead of as a bitmap like traditional sprites). Particle systems are also employed heavily.

Just like with bloom shaders, you can find a lot of information on GDSE or the wider internet itself by searching for those topics. For example:

1. High Performance Vector Graphics Solutions
2. Tricks for getting good results from particle systems

# Answer
> 0 votes
The lightning effects for that game are basically just particle effects (there might also be a simple bloom shader in there as well for the extra 'glow' effect). Those effects usually require hardware acceleration and thus require opengl (on android at least).

Since you're pretty new to programming you might want to look at a library like Ardor3D (also works on android). This is a java-based opengl library that supports things like bloom out of the box. But if your knowledge of java/graphics is pretty basic it'll still be a steep learning curve (but at least a lot easier than learning opengl from scratch).

---
Tags: android, graphics, graphics-programming, graphic-effects
---


# Question
Title: Use PIX to find model Polygon count in XNA?
I'm using PIX from the DirectX SDK to monitor my XNA application. I want to see the polygon count a model loaded in the application and was told this was information I could get from using PIX.

Problem is, I'm not sure how. I've looked through the documenation so maybe I'm just missing something obvious or maybe this is a feature I cannot use with my XNA application.

I could write code to get this information, but I was under the impression it would better practice to use a diagnostics tool instead of altering my code to retrieve the information.

Thanks.

# Answer
PIX is a fairly low-level data collector/analyzer for D3D. PIX can examine the state of device objects -- including vertex and index buffers -- from within an experiment. The PIX tutorials page has a document on examining mesh data. The tutorials tend to build on each other so it's probably a good idea to at least skim them from the first one.

It's not a bad idea to write code to compute this information for you though, and allow you to enable/disable it at will. This isn't really "polluting" you code in any way -- you can always configure this code to be compiled-out of release builds, and by having it in your program you can set it up so you can turn it on and off at run-time as well -- this way you may be able to enable it when you encounter a difficult-to-reproduce bug that warrants looking at this diagnostics data. If you rely *only* on external tools like PIX, you'd have to be able to ensure you can reproduce whatever bug or issue you're looking at before the tool will be useful.

Since you're using XNA, and not D3D directly, you may also find it a bit harder to correlate the D3D commands XNA sends with the XNA operations you're doing, since XNA is a higher-level API.

To compute your primitive count in code, you'll want to iterate all the ModelMesh objects inside your Model. Each ModelMesh has a collection of ModelMeshParts, which each have a PrimitiveCount. The sum of all PrimitiveCounts is the primitive count of the model.
> 3 votes

---
Tags: xna, pix
---


# Question
Title: Physics in a 2D oblique perspective game
So, just to clarify, because I'm still fuzzy on the terms for perspectives in older games myself, examples of an *oblique* perspective can be seen in many older RPGs (Earthbound, Final Fantasy, Secret Of Mana, etc.).

I've seen many games created in this perspective that utilize a more action-oriented style of gameplay in which one can see various physical interactions at work, such as projectiles, jumping, friction, and more. (Alundra is one that always stands out in my mind)

My question is: How are the physics often being done from a design/engine perspective in these games? Are there common practices for this sort of game design?

# Answer
The presentation consists of several layers of content, for instance, Secret of Mana on the SNES uses (from memory):

* Far backdrop(used for parallax)
* backdrop
* active scenery
* characters/sprites
* foreground
* UI

You can examine this for yourself using a SNES emulator such as ZSNES, and disabling various layers.

As to how physics are done, just consider each layer as a discrete 2d vertical plane. For collision detection, each object would have a hit box, and collision detection would go Bounding Circle -\> Axis Aligned Bounding Rectangle -\> Per Pixel (modern systems can use frame buffers on the GPU to improve the efficiency of this, by rendering each object as a mask of different colours).
> 1 votes

# Answer
If by physics, you mean collision detection and such, I would recommend that you visualize the world from the top view while rendering it in the oblique view. For example, if you have a box, give it properties like GroundWidth, GroundBreadth, GroundPosition, etc. along with your other properties like TextureWidth and TextureHeight.

You can then perform physics easily on the "Ground" properties.
> 0 votes

---
Tags: 2d, physics, game-mechanics, perspective
---


# Question
Title: Efficient 2d Java Line of Sight for a lot of entities?
My problem today is this:

I have many civilians going around, they are classes stored by an arraylist.

The idea is when they see another civilian panic, they'll start to panic and it will spread.

First I call each classes `Step()` function by looping through an iterator. Then in the `Step()` function it goes through another civillian iterator As it goes through, it tries to detect whether it can see the other civillian in the iterator, this is where performance time goes from 0 to 50 Milliseconds for having 100 Civillians.

This is the problem I need to fix, I tried to make an easy way to detect whether any objects are in the way of point a to point b.

Here's the code for the line of sight:

```
public static Object LOS(int x, int y, int x2, int y2, String Scan, Object Me, Object You) {
   DirectionX = (x-x2)/Quality;
   DirectionY = (y-y2)/Quality;
   CurrentX = x;
   CurrentY = y;
   String[] ScanArray = Scan.split(":");
   for(int I=0;I<=Quality;I++) {
      for(String Type: ScanArray) {
         if(Type.equals("Boxs")) {
            Iterator it=Level.Boxs.iterator();
            while(it.hasNext()) {
               Box Box = (Box)it.next();
               if(Me!=Box&&You!=Box) {
                  //Collision = Tools.Collision((int)(CurrentX-(Width/2)), (int)(CurrentY-(Width/2)), Width, Width, Box.GetX(), Box.GetY(), Box.GetWidth(), Box.GetHeight(), 1);
                  boolean Col = Tools.BasicCollision((int)(CurrentX-(Width/2)), (int)(CurrentY-(Width/2)), Width, Width, Box.GetX(), Box.GetY(), Box.GetWidth(), Box.GetHeight());
               }
            }
         }
      }

      CurrentX-=DirectionX;
      CurrentY-=DirectionY;
   }
   return null;
}

```

If you have a headache the fundamentals are:

It figures out 10 points in between and detects whether it is inside, using `BasicCollision`:

```
public static boolean BasicCollision(int x, int y, int width, int height, int x2, int y2, int width2, int height2) {
   if(x<x2+width&&x+width>x2&&y<y2+height&&y+height>y2) {
      return true;
   } else {
      return false;
   }
}

```

My question is: **Is there an easier way to detect this Line of Sight that doesn't severely impact my performance in large numbers?** Any feedback?

# Answer
> 5 votes
One thought would be to maintain non-panicky and panicky people in separate lists N and P, and then limit your LOS checks to \<n, p\> ∈ N × P. That way you never check same-state people, which will speed things up.

Another thing (which you may already be doing--not sure) would be to make sure that once you determine that a nonpanicker has become a panicker, immediately halt remaining checks for that former nonpanicker. This will help your algorithm scale with increasing population size for a fixed map. When the population gets very large then you should converge toward 100% panicking pretty quickly, which means no more checks are needed as noted in the comments below.

# Answer
> 2 votes
From your description it seems like your code is iterating over every possible pairing of two civilians. The drawing suggests that this is unnecessary. You can use some sort of geometric indexing to keep track of nearby civilians. Then test them first. If they are in the LOS, then panic. Otherwise test farther away civilians.

# Answer
> 0 votes
You have several options:

A) Assume that people can panic also hearing other people screaming, so the line of sight code is not that important XD.

B) In case A is not an option, you have to do this for each civilian:

1. Calculate if the segment between two civilians has a length less or equal some constant value.
2. Compute if this segment intersects with a poligon (rectangle, in your case).

You have to perform 1 before 2 because it greatly reduces the ammount of work, given that 2 is the most expensive computation. Also you have to consider some kind of "memory" about the calculations you have already made, e.g.: If you just processed the C1-C2 segment, don't do again C2-C1.

In addition to that, you have to optimize 2. Testing if a segment intersects with a rectangle is equivalent to test if a given segment intersects with 4 segments. When you have intersected with one of them, we're sure the civilians don't see each other, so it makes no sense to process the remaining segments in the rectangle.

Since this is a typical geometrical problem, known as the *line segment intersection problem*, you can find plenty of open source code on the internet. Most people use a sweep line algorithm along with some data structure.

# Answer
> 0 votes
If you treat rooms as zones, joined by portals, you only only have to do visibility scans within each room and those parts of adjoining rooms that are visible through the pre-determined portals.

Your line-of-sight is likely not accounting for the direction the civilian is facing? In such a case, if you divide rooms that contain obstacles like pillars or goes around corners into separate convex zones and assuming that all civilians in the same zone are all visible to each other. You may take that further by having overlapping concave zones and allowing civilians to be in more than one zone at once as as to find as many as possible in the same zone as the other civilian so as to avoid all other visibility checks.

If your terrain is uneven and you have a large number of agents then you may be interested in this O(n) sweep (where N is the granularity of a grid you've divided terrain into):

---
Tags: java, software-engineering, optimization, line-of-sight
---


# Question
Title: what are the networking features available in iphone?
So far I couldn't find anything on google so I'm asking here:

I need to connect two iphones or more to each other for a multiplayer game, what features does iphone api provide? is there some kind of bluetooth device or equivalent in iphone or should i just search over the wireless network connection? and what api should I use to connect them? is it possible to use c++ or are the api functions only available via obj-c iphone sdk?

# Answer
Apple's Game Kit and Game Center frameworks include Objective-C classes for online matchmaking and local Bluetooth games as well. You should probably start with those.
> 7 votes

---
Tags: iphone, networking
---


# Question
Title: How to implement time traveling into a game?
I was wondering how to implement time travel into a game. Nothing super complex, just time-reversal like what's in Braid, where the user can rewind/fast forward time by 30 seconds or whatever.

I searched around the web a lot, but my results usually referred to using time as in like "it's 3:00" or a timer and such.

The only thing I could think of was using 2 arrays, one for the player's x position and the other for the player's y position, and then iterating through those arrays and placing the character at that position as they rewind/fast forward time. Could that work? If it would work, how large would the array have to be and how often should I store the player's x and y? If it doesn't work, what else could I try?

Thanks in advance!

# Answer
The array idea is pretty much how it was implemented in Braid. When the only things acting on a character are gravity, keyboard/joypad input, and other characters, you pretty much only need to store the position and the velocity at each step to know everything important about that character. If you store 10 snapshots per second per character then it's still less than 50K for a minute of one character's history - easily manageable on most systems, and you can find ways that are more efficient than that too.
> 6 votes

# Answer
Read up on the Command Pattern. It provides for undoing actions (and for later re-doing them.) That would handle more than just position of a ship, but all actions the player takes.

But I think your array idea is sound as well.
> 4 votes

# Answer
Rather than have two separate arrays, you should probably have one class that describes the player's position (there's probably a Point class in Java already... I'm a C# guy lately) and use one single array to hold past positions.

You need to setup a "ring buffer", meaning that when you get to the end of the array, you circle back to the beginning of the array, overwriting the oldest entries. If you travel back in time, the opposite is true (when you get to the beginning, circle up to the end).

If you want to hold 30 seconds worth of past data, you need to know your frame rate if you want to pre-allocate space and use a fixed-size array. If you render the game at 10 frames/second, times 30 seconds, that's 300 elements.
> 3 votes

# Answer
GDCVault has a lecture by Jon Blow (the creator of *Braid*) on their site called The Implementation of Rewind in Braid for $3.95. I'll bet this has the info you want ;)

EDIT: Probably won't be in Java but the ideas should hold.
> 2 votes

# Answer
Like Erik J said, storing the player's past positions as a collection of point objects in a ring-buffer sounds reasonable.

However, I would suggest using a queue to implement the buffer. It's much cheaper to update than an array and you don't have to know your frame rate in advance:

```
update():
   time_queue.push(player.positions)
   if current_time() - start_time > n:
       queue.pop()

```

This does not yet consider varying frame rates or what should happen if you actually do any time-traveling, so I suggest you store a time stamp with each entry and check that instead:

```
update():
    time_queue.push({
        'pos': player.positions,
        'time': current_time()
    })
    first_entry = queue.peek()
    while current_time() - first_entry['time'] > n:
       queue.pop()
       first_entry = queue.peek()

```

Hope this helps!
> 1 votes

# Answer
There's a design pattern called **Memento**, I think it's a starting point for a game like Braid

> The memento pattern is a software design pattern that provides the ability to restore \>an object to its previous state (undo via rollback).
>
> The memento pattern is used by two objects: the originator and a caretaker. The originator is some object that has an internal state. The caretaker is going to do something to the originator, but wants to be able to undo the change. The caretaker first asks the originator for a memento object. Then it does whatever operation (or sequence of operations) it was going to do. To roll back to the state before the operations, it returns the memento object to the originator. The memento object itself is an opaque object (one which the caretaker cannot, or should not, change). When using this pattern, care should be taken if the originator may change other objects or resources - the memento pattern operates on a single object.

http://en.wikipedia.org/wiki/Memento\_pattern

Adcional info here: http://dofactory.com/Patterns/PatternMemento.aspx
> 1 votes

# Answer
There was a game released for the XBox360 that involved time-manipulation. It was mediocre, so I can't remember the title at this time. Anyway, in an interview with a developer for it, they outlined how they managed time manipulation:

Every X frames (with lower values of X leading to more fine-grained manipulation), you take a "snapshot" of the gameworld at that point, and associate it with an in-game time.

While playing through the game normally, time-forward, every input an reaction contributes to the snapshot set at some time in the future.

The game world then iterates between the snapshot at the current time, and the snapshot X frames in the future.

Then, when you want to reverse time, just set the direction of time to be backwards, so that it is iterating between the present and the snapshot X frames in the past (while disabling the ability to create future snapshots).
> 1 votes

# Answer
You can simply treat the game's virtual time as another space-like dimension. So what's time travel from the outside is a simple n+1 dimensional movement in the game's virtual universe.

Assuming some user interaction and some sort of physics system that determine the behaviour of your universe when there's no user input, all you need to record is the effect of user interactions (for example, changes in the n+1 dimension speed/acceleration vectors), as your physics should be time-reversible.

This way you'd need much less memory to calculate the state of the game universe at any given time coordinate.
> 0 votes

# Answer
Let's say an entity has a velocity, rotation, x and y position. These are, with acceleration, the basic movement states, values, whatever you call it. You can save the data in two ways:
1. Save rotation, x and y position
2. Save rotation, x velocity and y velocity

If you have a fixed velocity, you could also only save rotation, or save only one velocity for both axis.

Saving rotation is necessary in games, unless your entity has a static rotation, what it is not in most cases.

That said, using a list of objects for multiple values is necessary. If you have a nice timer system, which, for example, calls update methods 20 times in a second, and therefore is fps independent, you can create an array of 20 * 30 objects to store the movement values you need for the last 30 seconds. Using a simple array is not recommended, since you would have to move every element one index left each update call.

Based on this, you can go through the list or whatever to go back. If you really want to gain a "realistic" effect, use this technique for all moving objects. But this is game design related.

If you destroy objects, remember to pool them, to ensure that you do not stress your neat friend Mr. Garbage ;)
> 0 votes

---
Tags: time-travel
---


# Question
Title: Which programming language is used to develop an app  in corona?
* What is Corona & Which programming language is used to develop an application in corona?
* What physics Engine is corona using?

and any other information that is absent in their site?

# Answer
You write code in Lua when developing in CoronaSDK. That information is definitely on their site, although it's not as prominent as it used to be (I haven't looked at the front page in a while).

For example, here's the page under the "Games" heading: http://www.anscamobile.com/corona/games/

First sentence: "Built on top of OpenGL, OpenAL, Box2D, and Lua"
> 2 votes

---
Tags: android, iphone, corona-sdk
---


# Question
Title: How many "parallel units" does a GPU have?
I'd like to know how many parallel units *for processing vertices* a GPU has.

This Wikipedia page provides a GFLOPS and clock speed, for example for the Radeon 5850 "Broadway PRO", you get 1000 GFLOPS. Assume running a vertex shader is 100 flops, then that means you can process 1000e9 / 100 = 10e9 vertices per second.

Is there a manufacturer published number of *number of parallel processing units*, or a way to know that number?

# Answer
> 27 votes
> Assume running a vertex shader is 100 flops, then that means you can process 1000e9 / 100 = 10e9 vertices per second.

No, it most assuredly does not.

Basically, you should consider any calculation of the execution speed of *any* code based solely on "FLOPS" count to be suspect. Indeed, it's generally best if you completely ignore FLOPS entirely.

You did not define the term "parallel unit"; without that definition, we could only guess at what you're wanting.

Take the Radeon 5870. It has 1600 floating-point units. That means, for every cycle, it can be executing 1600 scalar floating-point operations at once. However, each VLIW opcode works on 5-way vector math registers. So the smallest possible granularity of actual code is 1600/5, or 320 (note: this is a *vast* simplification). That's 320 threads.

*However*, that's not really how it works. You don't have 320 separate paths of execution going on. You cannot have 320 different pieces of code executing on 320 different units. See, the 5-way VLIWs are themselves grouped into 4-way SIMD cores. Each SIMD can have its own path of execution and its own source code. Each VLIW *within* an SIMD core can have separate data, so that they compute separate values. But each VLIW within an SIMD core executes the same instructions in lock-step with the other VLIWs in that core.

So really, you only have 320/4, or 80 total threads. But again, it depends on what kind of "parallel unit" you're talking about. Technically, 1600, 320, and 80 are all legitimate answers.

And that's just for one *specific* architecture. NVIDIA's Fermi line (GeForce 4xx and above) uses a vastly different architecture. ATI's Cayman line (Radeon 69xx) changes the 5-way VLIWs to 4-way VLIWs. Their next architecture may have some significant differences too.

Without knowing what you're looking for, there's just no way to answer the question.

# Answer
> 3 votes
I don't understand, what do you mean by parallel processing unit? shader units? Because a ppu and a gpu nowadays are basically the same thing, i mean the ppu IS the gpu if we are talking about ati radeon.

I suppose you mean the functional units, you have to read the `Config core` field in wikipedia:

`Config Core – The layout of the graphics pipeline, in terms of functional units. Over time the number, type and variety of functional units in the GPU core has changed significantly; before each section in the list there is an explanation as to what functional units are present in each generation of processors.`

so for the radeon you say it would have:

```
Unified Shaders (Vertex shader/Geometry shader/Pixel shader) : Texture mapping unit : Render Output unit

```

which for the broadway pro is: `800:40:16`

this means it has 800 shader units, 40 texture mapping units and 16 render output units.

EDIT: Well no, it seems that parallel processing unit is also applied to what you mean, so I suppose it's kinda confusing calling them that way. I would call them shader units or simd cores.

---
Tags: gpu
---


# Question
Title: How does the camera/UI know who the player is?
I'm in a bit of a dilemma regarding how certain engine components — like camera and UI — know who to follow, whose health and other attributes to represent on the screen.

How do you architect a system where does communication between those components and the entities take place? I could have a separate entity that represents the player, but that seems a bit 'hard-coded'. What if I want to pan the camera? What if the player starts controlling another entity?

In other words, how do I abstract away the data sources for components like the camera and UI, such that they don't care what entity they represent?

---

An event system will do for a lot of cases, but that is more suited for propagating information that changes or is generated 'rarely' (like the death of the player). For something like entity health and position — which need to be known every frame — an event system isn't well suited.

# Answer
> 10 votes
The simplest solution would be to keep a member pointer to an object such as Camera.Target or UI.Subject that points to the player character but can be redirected to other objects (or set to NULL) when necessary.

If the player changes character, send an event to change the camera's target variable and the UI's subject. If you want to pan the camera, override the "target" behaviour and set it to a manual movement.

# Answer
> 2 votes
I find that the easiest way to do this is to simply not restrict myself to only having a single camera.

Instead, my game worlds are full of cameras, dozens or hundreds of them. Any potentially controllable character has a camera, any cutscene has a camera, often a single entity will have several different cameras for different player activities as well. (combat moves, idling, sprinting, etc). Each camera is given its target when it's created, and that target (as a general rule) remains constant for the lifetime of the camera.

The problem now becomes not "how does the camera know which character it's following", but "how does the renderer know which of the cameras in the scene it should actually be using for rendering right now". I use a camera manager class for that, which knows about all the cameras in the scene, and can blend from one to another, as instructed by events it receives from game logic.

# Answer
> 0 votes
Players are likely different enough from other objects or entities that they will have their own class. For many games it's perfectly legitimate to have one global player object that can be available throughout the engine and always represents the player, and any system that needs to know about the player can talk to that class. This can be cleaner and simpler than passing around a pointer everywhere.

If your game is multiplayer over a network, this can still make sense because there's a big difference between the local player and the remote ones. If you support local multiplayer with two controllers, then you'd need multiple player objects and concomitant pointer-passing.

---
Tags: architecture, camera
---


# Question
Title: Why might my Object Attributes become linked after refactoring?
As part of a game design class I'm taking this semester, I'm developing the basics of a game engine. I shared what I had in the GameDev chatroom, earlier, and everything was working as expected.

Then, because I knew it needed it, I started work on refactoring the core classes within my code. I modified the ancestor GameObject class, and after the tedious process of renaming all the method and field calls (I combined two float's, xPosition and yPosition into a single, Vector2d class - yes, I realize there are existing classes out there, but it was easier to simply write a new one, given that I can't make any assumptions on the installed libraries when it comes time for grading my work. I digress), prepared to test my newly refactored code.

The results were... perplexing. Suddennly, my SpawnPoint object was moving. Not only that, but it seemed attached to the PlayerEntity object itself, always matching the position of the controllable playerEntity (though it lagged a bit behind if you moved fast enough). And yet, I *know* that I never move the SpawnPoint, only the player entity; a quick search (ctrl+f) through my code confirmed that. But despite this, I had somehow managed to achieve quantum entanglement of these disparate objects.

I've reproduced both constructors below. **Is this a case of passing by reference instead of by value?** If so, is there a general way to avoid such troubles when instantiating objects with other objects as parameters?

**Original Code:**

```
public class PlayerEntity extends GameObject{

  SpawnPoint playerSpawn;
  public boolean isDead = true;
  float xVelocity;
  float yVelocity;

  //constructor, single dimension
  PlayerEntity(SpawnPoint spawn)
  {
    this.objClass = "entity";
    this.playerSpawn = spawn;
    this.xDiameter = 15;
    this.yDiameter = 15;
    this.xVelocity = 0;
    this.yVelocity = 0;
  }

  void respawn(){
   isDead = false;
   this.xPosition = playerSpawn.xPosition;
   this.yPosition = playerSpawn.yPosition;
  }

```

**Refactored (Bugged) Code**

```
public class PlayerEntity extends GameObject{

  SpawnPoint playerSpawn;
  public boolean isDead = true;
  Vector2d velocityVector;
  float xDiameter;
  float yDiameter;
  //constructor, single dimension
  PlayerEntity(SpawnPoint spawn)
  {
    this.objClass = "entity";
    this.playerSpawn = spawn;
    this.xDiameter = 15;
    this.yDiameter = 15;
    this.velocityVector = new Vector2d(0,0);
    this.positionVector = this.playerSpawn.positionVector;
  }

void respawn(){
   isDead = false;
   this.positionVector = playerSpawn.positionVector;
  }

```

The first thing first thing the PlayerEntity does in its update() method is call "respawn()" if `isDead = true` (which is why I think I got away without initializing the position in the first, working, code).

With the help of a debugger, I've narrowed down the method call which (unintentionally) modifies the spawnpoint's position. I'll probably edit that into the question when I have exactly identified the culprit.

Edit: Here is the method where the value is changing (though I don't know **why**), taken from playerEntity.

**Original (working correctly)**

void moveEntity() {

```
    this.xPosition += this.xVelocity;
    this.yPosition += this.yVelocity;
}

```

**Refactored method (bugged behavior)**

void moveEntity() {

```
    this.positionVector.xCor += this.velocityVector.xCor;
    this.positionVector.yCor += this.velocityVector.yCor;
  }

```

for whatever reason, this is causing the spawnPoint's positionVector to alter as well.

This program is written in Processing (which is just a java library, albeit one with its own IDE).

# Answer
> this.positionVector = this.playerSpawn.positionVector;

This seems to be your problem line. It is indeed a reference; try calling

> this.positionVector = this.playerSpawn.positionVector.Clone();

Edit: Clone() seems to make no guarantees, so you should rather try:

> Vector2d vector = this.playerSpawn.positionVector;
>
> this.positionVector = new Vector2d(vector.X, vector.Y);

or

> this.positionVector = new Vector2d(this.playerSpawn.positionVector);

One of those will work for sure.
> 2 votes

---
Tags: java, debugging
---


# Question
Title: For my first 3D engine, should I go for one that is already made, or minimalistic?
I've been meaning to transition from 2D games to 3D games for some time, now. I have the most experience with RTS games, so I will be doing that.

On one hand, there's a lightweight renderer; Irrlicht. However, considering it's a renderer and not a game engine (only basic collision, etc..) , I would have to write most of the things, myself.

On the other hand, there's a full blown engine like CryEngine 3, for example. Although it is mostly complete, I would first need to understand the various parts of the engine and it's implementation enough to be able to try and transform it into an RTS engine.

My question is, which would be easier for me to transition to?

# Answer
> 2 votes
It depends on what you personally want to get out of the transition.

If you just want to make games, get the grasp of 3D you could use Unity3D, it's simple, C# based, and you can get results quickly.

If you feel that you'd prefer to stay with C++ (which could be better on a professional level) you could use CryEngine, though from what I've heard it's rather badly documented. Other game engines such as UDK could be a good way to work on something powerful yet relatively easy to use (though badly documented also).

Of course your last solution could be a good idea, using an external lib for a renderer. You could either program the collisions yourself or integrate another library, like PhysX to do your collision checking for you.

In my experience, the next-best thing to doing everything yourself is to integrate different libraries that you have chosen for their different capabilities. If you read up on these different libs, then you'll have a better grasp of what you need in your game and which lib will best suit your needs.

The last solution is the one I would go for; if after all you want to create your own engine, you'll have a better knowledge than if you just used something out-of-the-box.

---
Tags: game-design
---


# Question
Title: Database for increased scalability in a mmorpg?
I am planning a simple MMORPG, but even though it's a small, open source project, I'd like to have the best quality database. Which would be the best database software to use?

Examples:

**SQL** \- MySQL, PostgreSQL, MSSQL ...

**NoSQL** \- MongoDB, CouchDB ...

# Answer
> 4 votes
MySQL is free, is fast, can handle really big tables, is easy to use and you can find documentation and help extremely easy.

I also know MySQL better than say PostgreSQL and that is why I chose that one for my persistent multiplayer game.

Go with what you know best and if the worst case scenario happens (everyone wants to play your game and the DB knuckles) you can always change (or buy a faster server).

---
Tags: mmo, databases, sql
---


title: Entity position: In map or in script?

text:
# Question
Title: Entity position: In map or in script?
I'd like to know how others have handled the issue of storing the entity's position. (Or maybe it's not an issue and I just make it too complicated.)

I'm undecided on whether to store the position of each entity in the world map file or in the entity's script file. From what I figured, both approaches have their own good and bad points:

If you store the entity's position in the map:

* *Good:* Easier to edit the map; you can see where the entity will be. Maybe this isn't a problem for integrated map editors, but I'm using an external, general-purpose map editor (GLEED2D).
* *Bad:* Inside the game it's easier to handle data if the position is inside the entity object, not the map object. So when you load the game, you have to gather data from a lot of places to build your entity object.

On the other hand, if you store the position inside the entity script, the advantages and disadvantages are exactly the opposite of the above.

# Answer
I would definitely store the position of entities in the map file. I mean, if you have multiple copies of the entity in your scene then you'd need multiple scripts that are identical except for the position; horrible! I consider that way more important than either of the points you mentioned.
> 5 votes

---
Tags: maps, entity-system, scripting
---


# Question
Title: How would you structure a weapon class such that it works for many types of weapons?
How would you go around creating a reusable weapon class? I can't really wrap my head around creating a class, which will work for both melee and ranged weapons.

Example given, that you have a knife, an RPG, and you have an ordinary pistol. How would you go around creating a class all three can inherit from?

# Answer
> 8 votes
It should certainly be possible to create a single class that represents all weapons equally well -- and this is ideal, because allowing yourself to fall into the trap of creating many subclasses for each weapon type is cumbersome. Composition(\*) should be favored over inheritance.

The big challenges are going to be

1. Enumerating the set of data and behavior that you expect of all classifications of weapon.
2. Determining how to abstract that data and behavior into a data-oriented approach.

"Range" is a good example -- both swords and guns both have a range. You can either elect to use a simple system when a range of 0 just means "melee" or you can use a real-world measurement so as to (as suggested by another poster), gives daggers a shorter reach than a polearm.

Behavior can be handled by scripting(\**). You could have an "on-activated" script object that was invoked when the weapon was used or swung -- the script for a melee weapon would look at the range, and the location of the actor using the weapon and perhaps compute the set of targets in an semi-circle in front of the actor and apply damage to each. Conversely the script for a gun might do a raycast from the actor, limited by the range.

(\*) This does not strictly imply that you have to rely on "component oriented" systems to effectively avoid going crazy with inheritance.

(\**) Either via scripts loaded from another language, like Lua, or by pointing the weapon at a C++ "Script" class which you *do* create subclasses of. The latter is obviously easier, but lacks some of the benefits of a scripting system as it requires recompilation, for example.

# Answer
> 4 votes
The same way you design any inheritance structure: You think about what all weapons, without exception, have in common. Obviously, damage comes to mind. Attack rate. Remember that you don't have to (and should not!) cramp everything into the base class. You put into a class what you need it (and all child classes) to do, no more and no less.

Next step, you could make 2 classes, MeleeWeapon and RangedWeapon, which both inherit from Weapon. Maybe that split is necessary because a MeleeWeapon has no range, and/or only a RangedWeapon uses ammunition. Then you repeat the above process for each of those classes, until you have all classes you need.

At every branch, you should also consider if you really need to split into 2 or more classes. For example, melee weapons could also have a meaningful range, such as spear vs. dagger, or your ranged weapons could have infinite ammo. That totally depends on your game design and cannot be generalized.

# Answer
> 1 votes
To add to Hackworth's answer, with regard to damage and attack rate, in an RPG there are also modifiers to abilities. A heavy weapon may actually reduce your strength or dexterity, and give you negative modifiers. However, instead of thinking about having all weapons inheriting your modifiers, create a Modifier interface and implementation that has getters/setters for those modifiers. Now your Weapon interface should have a getter/setter for your Modifier object. This favors composition over inheritance when it makes sense.

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


title: Storing Entity Meta-Data

text:
# Question
Title: Storing Entity Meta-Data
The question is about how to handle data *about* entities, but not particularly useful to the entity itself. An example of such data may be the external script that controls the entity's behavior or the path to the animation file — such data is gathered when loading the entity and is no longer useful until you save the game; it certainly doesn't belong in the entity object. Any tips on how to handle metadata?

# Answer
> 1 votes
Put the data in an external file that gets loaded by the object factory. Both XML and JSON are very useful for this purpose:

```
<entity id="anEntity">
  <script>script.lua</script>
  <image>image.png</image>
</entity>

```

Then when you save the game just save which entity it was (ie. the ID). When loading the saved game refer back to the entities data file:

```
<game>
  <entity>anEntity</entity>
  etc.
</game>

```

ADDITION: Y'know, I think you may be overcomplicating things based on "it certainly doesn't belong in the entity object". If there is some information about the entity that your application needs to continually refer to then stick that information in the entity and provide a getter; if not, then don't.

If you really need/want it, provide one level of indirection; the EntityFactory class has information about what script to use when making intances of Entity. That is how I would design things for the use case I'm guessing you're getting at, since all Entity instances would reference the same script, but really it depends on your exact use case.

# Answer
> 1 votes
> such data is gathered when loading the entity and is no longer useful until you save the game; it certainly doesn't belong in the entity object. Any tips on how to handle metadata?

This statement actually gives me pause, and makes me think you may have a very unusual state serialization system. But, that said...

> The question is about how to handle data about entities, but not particularly useful to the entity itself. An example of such data may be the external script that controls the entity's behavior or the path to the animation file

If you have a generic key/value dictionary type of storage for the data, you could simply hang a reference to that data off the entity object itself. It's fine that the entity knows that *it has* metadata, it's generally only problematic if the entity gets to know all about specific kinds of metadata.

(Of course that only matters if you've decided to let the specific metadata live above the level of abstraction of the entity itself, which it sounds like you have.)

Another option is to store the metadata dictionary elsewhere, perhaps in an interface whose job is to recover the metadata for a given entity given its entity ID or whatever.

Neither option is objectively better than the other in general; the latter tends to allow you to restrict what other systems have access to the metadata, which can be nice for enforcing your abstraction boundaries. The former tends to be easier to use. Which will be most ideal will depend more on your specific needs.

---
Tags: scripting, entity-system
---


# Question
Title: D3D11 - Setting multiple ID3D11SamplerStates for the pixel shader stage once and leaving them be
In my Direct3D 11 application, I am using several sampler states to retrieve texture data. Some of them are used in all pixel shaders, some of them are only used in very specific ones.

The question may seem simple, but I was not able to find any decent information on the topic-

Are there any penalties (performance or otherwise) involved in creating a number of sampler states for the pixel shader stage of D3D11, setting them all at once and just never touching them again? My shaders would reference these samplers in HLSL if they need them (for instance some shaders would reference `SamplerState linear_sampler : register(s0);` while some others would reference `SamplerState point_sampler : register(s1);`, possibly without referencing s0 at all.

Also, is it correct, that if I never want to reference these samplers in my c++ code after creation and setting, I could just release my own external references after they are set and they will not get destroyed, as D3D is keeping internal references as long as they are "bound"(?) ? And even if had to somehow get a reference, I could simply use ID3D11DeviceContext::PSGetSamplers (of course accepting the involved performance penalty of the lookup), correct?

# Answer
> 1 votes
I don't have exact numbers as I have not done any benchmarks. That said, in my engine for compatibility with DirectX 9 I have one sampler per texture, so there are quite a few, and they are not always referenced in the shader. So far I have not noted any performance degradation compared to before we added DX9 support. As long as you create your sampler state at the beginning of the program and not (or rarely) during you should be fine (from the DirectX SDK documentation).

Concerning the references in the C++ side, I would want to hang onto them anyway; what happens when you change a sampler state ? You lose the previous one ? I'd store them somewhere "static" like says a static array of 16 samplers for example.

---
Tags: hlsl, directx11, fragment-shader
---


# Question
Title: What is OpenGL ES Shading Language based on and what are the differences?
My guess is that it is derived from version 1.10 of the OpenGL Shading Language, document revision number 59. Found it here, page 7: http://old.siggraph.org/publications/2006cn/course16/KhronosSpecs/ESLanguageSpec1.10.11.pdf The differences are also listed there with underlined text.

Can anyone confirm that it is based on version 1.10?

I took a look into the latest revision of OpenGL ES Shading Language - 1.0.17. It seems there is no reference to the original OpenGL Shading Language and no difference specs at all. The problem is that I can't find any document revisions between 1.10.11 and 1.0.17. They could change their mind and derive ES Shading Language from Shading Language 1.20. or something else.

# Answer
> I took a look into the latest revision of OpenGL ES Shading Language

Are you sure you did? Because the PDF of the 1.0.17 spec very clearly states, in the Introduction:

> The OpenGL ES Shading Language (also known as GLSL ES or ESSL) is based on the OpenGL Shading Language (GLSL) version 1.20.

Following this is a detailed change log of every revision of the spec.

Furthermore, what does it matter what it is based on? It copies and modifies the GLSL specification; you don't need to look at any particular GLSL spec to read the ESSL spec.
> 5 votes

---
Tags: opengl-es
---