# Question
Title: Can I set a texture as the wallpaper of an iOS device?
I have a game in Unity which creates drawings.

I need to have a button which sets the drawing as the wallpaper (with permission from the user of course).

Is it possible?

# Answer
No, there is no public API available to set the wallpaper or lock screen images of an iOS device(\*).

You can save the picture to the user's camera roll and provide instructions for them to manually change the wallpaper, but you can't actually do it all yourself.

(\*) It seems like it should be possible to do this on a *jailbroken* device, however (some cursory searching suggests by writing to `/var/mobile/Library/LockBackground.jpg` for example). But unless you're targeting jailbroken devices you're out of luck.
> 1 votes

---
Tags: unity, ios
---


title: How should I store a city map on disk?

text:
# Question
Title: How should I store a city map on disk?
I'm working on a game where players travel in a city.

This city is defined by streets (names, positions...), points of interest (cinemas, restaurants...) and different zones (high criminality zones, rich zones, poor zones...). I still don't know if this city will be based on a real one (using OpenStreet map data) or made by game designers. In either case, I need to be able to modify the map data (add a cinema here, move a restaurant there...).

I also want to be able to search it for stuff like "Where is the closest restaurant?" or "How long would it take to travel to that street?".

How should I best store such information on disk, to be loaded or modified later?

(I'm working with Unity, but this isn't a Unity-specific question.)

# Answer
> 0 votes
Sounds like you want a graph data type. Nodes could store their positions, plus references to features like restaurants, as well as references to other graph nodes. This is effectively an adjacency list.

Existing pathfinding algorithms work well on such graphs. You could easily calculate the weight of a graph edge (the "difficulty" of that link) as the distance between two nodes' positions.

The remaining issue is *serialisation*: specifically, converting a graph into a character sequence that can be stored on disk, to load later. This StackOverflow question has some ideas, but the exact implementation will depend on your needs and tastes. If you like XML, you might like to use `xs:ID`/-`REF`. If you want to be minimalist, maybe roll your own?

I like JSON, so I would serialise your type of game map as

```
{
  "nodes" : {
    "0" : {
      "features" : [
          "bs5xgsgfg"
       ],
       "position" : { "x" : "0", "y" : "0" }
    },
    "1" : { "features" : [], "position" : { "x" : "100", "y" : "0" } },
    "2" : { "features" : [], "position" : { "x" : "0", "y" : "100" } },
    "3" : { "features" : [], "position" : { "x" : "100", "y" : "100" } }
  },
  "edges" : [
    { "from-id" : "0", "to-id" : "1" },
    { "from-id" : "1", "to-id" : "2" },
    { "from-id" : "2", "to-id" : "3" },
    { "from-id" : "3", "to-id" : "0" }
  ],
  "features" : {
      "bs5xgsgfg" : {
        "type" : "nightclub",
        "name" : "Cyberia",
        "dangerousness-level-or-something" : 15
      }
   }
}

```

That would encode a fairly boring city, with 4 street corners arranged in a square, with a nightclub at one corner and a one-way street going clockwise along the streets of that square. I think you see where I'm going with this though.

# Answer
> 1 votes
I would store the data in a graph to help with pathfinding - nodes are intersections and edges are streets (with one-way, no pedestrian, etc flags). Then for storing the data I would take a multi-layered approach

### Gather the Source Data

First find some way to define (or import) the data. Likely a visual tool would help, but you could get away with something that supports real-world coordinates (latitude, longitude, etc). You will want to support connectivity at this stage, but also allow objects to be just 'placed' in the world (cinemas, etc), since writing the tedious connectivity code in XML, JSON or a non-visual tool will be cumbersome. File format of this might be useful to be somewhat human readable, so XML or JSON, as long as the format supports circular references and links. Nodes likely should be stored in a text-editor searchable format - GUID, or some such - to help authoring and debugging.

### Add Connections & Validate

Now you need a tool that takes \**all\* of the world data and creates any game-specific connections, intersects roads and makes connections, annotates the world with one-way-streets. The data should be loaded all at once, in an offline tool, into some kind of verbose/fat format. It would have all the useful information in it so you can write validation steps. It should also allow debug pathfinding so you can run offline tests that you can truly get from the Eiffel Tower to the Louvre. Having a separate tool in an offline process for this is great because you can add as much cumbersome debugging information to it but you never have to feel like your game code is getting dirty. Plus the format you store this in memory will likely be vary different than in games - adjacent nodes will be in a dynamic list, whereas at runtime it will be in a fixed sized array, or a linked list, for example.

### Emit Data

To make searches efficient you will want to store the data in some kind of efficient representation. That means your GUIDS will be compressed down to some kind of incrementing ID, and adjacency/edge information will be stored in flat arrays, or linked lists. All of this is really important to get your searches fast. Furthermore, specific entities (such as restaurants, or cinemas, would be stored in a separate data structure so you can quickly locate their positions in the world. That structure might be a database of restaurants, say, or it might be a uniform grid where each grid stores all of the buildings in it in order to make searches for 'nearest things' faster, or both. I suspect both. By making the emitting stage separate from the validate stage you can write code that compresses the data into game-ready format without worrying that you've broken the preprocessing or validation stage. Your writing code might be sharable with the reading code in the game, too. You might also want to chunk up the data into pieces to stream in, or implement a hierarchical path finding system on top of it so you don't need all of the fine-grained data loaded all the time.

### Load the data

Now the game loads the data and starts working on it. Ideally the data is loaded with as little work possible. I always strive to make my data memory imaged so it loads in place without any allocations, but that's for my commercial production game environment.

Good luck.

---
Tags: path-finding, maps, serialization
---


title: Bullet Physics - scaling

text:
# Question
Title: Bullet Physics - scaling
I have added Bullet to my game engine. So far I am using translation and rotation, and it works fine. But now, I want to scale my geometry (eg. user can drink some potion an became small :-)).

I am using

```
btWorldTransform.setOrigin(origin);
btWorldTransform.setRotation(rotation);

```

to set position of bullet body directly (it is done only once in initial object placement in scene or in case of teleportation etc. otherwise position is updated by bullet and forces)

Now, if I put object into scene, I set its `btCollisionShape` and that has some fixed size. Now, I change size of my scene object, graphics has scale, but what to do with bullet collision shape?

I have found `setLocalScaling` method, but I am not sure if it is, what I want. Can someone verify this?

# Answer
Bullet does not allow the transform associated with a RigidBody to have any scale or shear in it. This is not uncommon; many other physics engines have this restriction as scale and shear can make the internal dynamics simulation very difficult to solve.

Instead of scaling the rigid body you will need to instead scale the shape used for collision detection. This is done by calling btCollisionShape::setLocalScaling(). You may need to call btCollisionWorld::updateSingleAABB( rigidbody ) to get the new bounding box of the scale to take effect.
> 13 votes

---
Tags: bullet-physics
---


# Question
Title: How is this particular HLSL condition treated with respect to compile- or run-time evaluation?
Let's say I have this very simple pixel shader (cbuffers and other stuff omitted)

```
float4 PS(VertexOut pin, uniform bool useLighting) : SV_Target {
    float4 retColor = gDiffuseMap.Sample( sampler0, pin.Tex );
if (useLighting) {
    retColor = retColor * float4(gAmbientLight, 1.0f);
}
    return retColor;
}

```

and two techniques such as

```
technique11 TexTech {
    pass P0 {
        SetVertexShader( CompileShader( vs_4_0, VS()));
        SetGeometryShader(NULL);
        SetPixelShader(CompileShader( ps_4_0, PS(false)));
    }
}

technique11 TexLitTech {
    pass P0 {
        SetVertexShader( CompileShader(vs_4_0, VS()));
        SetGeometryShader(NULL);
        SetPixelShader(CompileShader(ps_4_0, PS(true)));
    }
}

```

The way I understand it, the `useLighting` condition is evaluated during compile-time and each technique will have its own version of the pixel shader function without any branching. That means the `useLighting` condition wouldn't have any runtime penalties. Is that correct? So it's kind of like C preprocessing?

Why can the `pin` variable just be left out like that in the CompileShader call? It makes sense, of course, I'm just wondering if this is some special HLSL or Effect Framework syntax?

# Answer
Officially the `uniform` keyword indicates it is constant throughout the execution. All uniform variables to a shader must be resolved at compile-time.

The HLSL compiler using the legacy Effects profile will generate 3 shaders in this case:

* A `vs_4_0` profile vertex shader using the `VS` entry-point
* A `ps_4_0` profile pixel shader using the `PS` entry-point holding the `useLighting` to be `false`.
* A `ps_4_0` profile pixel shader using the `PS` entry-point holding the `useLighting` to be `true`.
> 0 votes

---
Tags: shaders, directx, directx11, hlsl
---


# Question
Title: Libgdx, how do i get the translation and rotation of a node from a model instance?
I have a model instance of a character, and a model instance of a sword weapon. THe character has a node on his right hand so he can "carry" the sword. Right now I use this code so the sword's transform follows that of the node.

```
weaponModelInstance.transform.set(modelInstance.transform).mul(weaponAttachmentNode.globalTransform);
weaponModelInstance.transform.rotate(Vector3.Z, -90); // adjustment for blender coordinates
world.modelBatch.render(weaponModelInstance, world.environment);

```

this works, except that the model instance gets scaled to the scale of the node, which i do not want, i want the weapon to keep its scale. I've tried doing the following code to fix this but I end up getting weird (and wrong) rotations for the sword

```
weaponModelInstance.transform.set(modelInstance.transform).mul(weaponAttachmentNode.globalTransform);
weaponModelInstance.transform.set(
        weaponModelInstance.transform.getTranslation(new Vector3()),
        weaponModelInstance.transform.getRotation(new Quaternion()),
        new Vector3(1, 1, 1)
);
weaponModelInstance.transform.rotate(Vector3.Z, -90);
world.modelBatch.render(weaponModelInstance, world.environment);

```

do anyone know how to properly copy the world translation and rotation from the node, but not its scale?

# Answer
> 2 votes
You will need to normalize the rotation matrix to remove its scale.

This can be done by normalizing all 3 rows of the transform basis matrix.

```
new btMatrix3x3(
  transform.getBasis().getRow(0).normalize()
, transform.getBasis().getRow(1).normalize()
, transform.getBasis().getRow(2).normalize()
);

```

or

```
new btMatrix3x3(
  transform.getBasis()[0].normalize()
, transform.getBasis()[1].normalize()
, transform.getBasis()[2].normalize()
);

```

This new matrix contains only the rotation without scaling.

If you want to extract the scaling instead:

```
new btVector3(
  transform.getBasis()[0].length()
, transform.getBasis()[1].length()
, transform.getBasis()[2].length()
);

```

---
Tags: libgdx, models, transformation
---


# Question
Title: How can I render a JBox2D ParticleGroup?
I want to render a `ParticleGroup` from `JBox2d` using OpenGL. I've managed to define a particle group area, but I'm unsure how to draw the individual particles.

Here's how I create the `ParticleGroup`:

```
m_world.setParticleRadius(0.15f);
m_world.setParticleDamping(0.2f);

PolygonShape shape = new PolygonShape();
shape.setAsBox(8, 10, new Vec2(-12, 10.1f), 0);
ParticleGroupDef pd = new ParticleGroupDef();
pd.shape = shape;
m_world.createParticleGroup(pd);

```

This is how I draw a normal `Square` (which I don't know how to apply to groups of particles):

```
public void draw(GLAutoDrawable gLDrawable, Vec3 position, float angle){

    gLDrawable.getGL().getGL2().glEnable(GL.GL_BLEND);
    gLDrawable.getGL().getGL2().glEnable(GL.GL_TEXTURE_2D);

    gLDrawable.getGL().getGL2().glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);

    gLDrawable.getGL().getGL2().glBindTexture(GL2.GL_TEXTURE_2D, TextureFactory.getTextureIndex(TextureCollection.valueOf(getTextureSelection())));
    gLDrawable.getGL().getGL2().glPushMatrix();

    gLDrawable.getGL().getGL2().glTranslatef(position.x * getP2M(), position.y * getP2M(), position.z);
    gLDrawable.getGL().getGL2().glRotated(Math.toDegrees(angle), 0, 0, 1);
    gLDrawable.getGL().getGL2().glBegin(GL2.GL_QUADS);
    gLDrawable.getGL().getGL2().glTexCoord2f(0.0f, 0.0f);
    gLDrawable.getGL().getGL2().glVertex3f(-getWidth() / 2 * getP2M(), -getHeight() / 2 * getP2M(), 0.0f);
    gLDrawable.getGL().getGL2().glTexCoord2f(0.0f, 1.0f);
    gLDrawable.getGL().getGL2().glVertex3f(-getWidth() / 2 * getP2M(), getHeight() / 2 * getP2M(), 0.0f);
    gLDrawable.getGL().getGL2().glTexCoord2f(1.0f, 1.0f);
    gLDrawable.getGL().getGL2().glVertex3f(getWidth() / 2 * getP2M(), getHeight() / 2 * getP2M(), 0.0f);
    gLDrawable.getGL().getGL2().glTexCoord2f(1.0f, 0.0f);
    gLDrawable.getGL().getGL2().glVertex3f(getWidth() / 2 * getP2M(), -getHeight() / 2 * getP2M(), 0.0f);
    gLDrawable.getGL().getGL2().glEnd();
    gLDrawable.getGL().getGL2().glFlush();
    gLDrawable.getGL().getGL2().glPopMatrix();

    gLDrawable.getGL().getGL2().glDisable(GL.GL_TEXTURE_2D);
    gLDrawable.getGL().getGL2().glDisable(GL.GL_BLEND);
}

```

How should I do this? (Example code would be great.)

# Answer
Try fetching the position buffer:

```
Vec2[] positions = m_world.getParticlePositionBuffer();

```

additionally you might want to grab the colors:

```
ParticleColor[] colors = m_world.getParticleColorBuffer();

```

Then I would draw the corresponding color at every position using OpenGL. I believe that you can write a very simple shader that would work very well for this. I would help you on this but I am not very familiar with OpenGL at all, despite my many attempts to learn it.
> 1 votes

---
Tags: opengl, java, box2d, particles
---


# Question
Title: How can I do optimal pathfinding for a Tetris piece?
Imagine a standard Tetris board (10x20) using the standard set of 7 tetrominoes.

Given a Tetris *game state* and a *target position*, how can I find the optimal sequence of moves that will get the currently active tetromino into that position?

---

A really basic example:

Clearly, the optimal path is to move to the leftmost column and not rotate the piece. I'd like the algorithm to handle more complex positions too.

# Answer
> 5 votes
I added another answer for an alternative explanation of the problem. You can think of this problem as Motion Planning in the Configuration Space of the tetris piece.

**The Configuration Space**

Define the **configuration** of a Tetris piece to be an (x, y) location and a rotation (t). The configuration of a Tetris piece is therefore three dimensional. We can define a 3D space that the Tetris piece lives in called its **configuration space**.

Now, configurations are either *possible* or *impossible*. A possible configuration has the Tetris piece completely inside empty parts of the tetris board. Impossible configurations either have the Tetris piece off of the board or colliding with occupied parts of the board.

**Configuration Space Planning**

The goal is to find a sequence of **configurations** `S =(c_0, ..., c_N)`, where `c_0` is the start configuration of the piece, and `c_N` is the goal configuration, where `S` is of *minimum length*, and all of the configurations in S are *possible*.

**Actions**

Define an `action` as a function that takes one configuration and turns it into another. In Tetris, the actions are `Turn` (which only modifies `t`), `Move Left`, `Move Right` and `Do Nothing`. Depending on the way "gravity" is implemented, every action may also move the Tetris piece down as well.

If an action would result in an *impossible* configuration, that action is itself impossible.

**Planning**

The problem can be solved using AStar. In this case, the nodes in Astar are 3D configurations of the piece `(x, y, t)`. The links are actions which change from one configuration to another such that the resulting configuration is *possible*. The distance metric and heuristic is a simple 2D euclidean measure on the position of the piece, and a simple comparison on `t`. All of the actions have weight `1`.

AStar is guaranteed to find the optimal set of actions needed to put the piece in the correct place.

# Answer
> 2 votes
I am assuming that your problem is:

> Assume the placement location is known. How do I find the optimal sequence of moves to put the piece in the correct location?

One answer to this question is to interpret the problem as an Action Planning problem. The simplest algorithm to solve it is probably STRIPS. There is another algorithm that is a more efficient version of STRIPS called GOAP which is used in the game industry. Basically, you can think of STRIPS and GOAP as an AStar path planning problem where the nodes are states, and the links between nodes are actions.

Here's how it works:

* You have a set of **states**, which we shall call `S`. In your case, the set of states is the set of all possible board positions. It can be represented efficiently as a binary matrix of 1's and 0's, where the 1's represent cells that are filled, and the 0's represent cells that are empty. You will also need to represent the current state of the piece being controlled by the player in your state.
* You also have a set of **actions** that can be taken at a particular state, called `A(S)`. In your case, the set of inputs the player can select to move the given piece.
* An action `a` performed on a state `s` leads to a new state `s'`. In your case, an action will move the current piece so that different parts of the grid become 1's and others become 0's. Given a state, there are at most 4 actions (rotate left, rotate right, move down, and do nothing). Some of these actions will be impossible.
* There is a goal state `g in S` that you want to reach, and a start state `s_0`. In your case, it will be a specific board configuration and position/orientation of the target piece.
* Assume we have a distance metric `d(s_1, s_2)` which tells us how similar two states are. In your case, the distance metric can simply iterate through all the grid cells into the two states, and add `1` whenever the cells differ. You can also do this more simply by measuring the distance between the position/rotation of the target piece in `s_1` and `s_2`.

We can interpret this as a **graph planning** problem. A node is simply a state. A link between nodes is simply an action that takes you from one state to another. The goal is to plan a sequence of actions from the start state to the goal state which has minimum length. To solve this problem, you simply use AStar on the graph, with `d` as the heuristic. Sometimes, it will be impossible to solve the problem, but Astar will always give you the optimal set of moves to take to get you to the goal.

Here's some simple pseudocode:

```
// Returns all the reachable neighbors of a given state.
List<State> GetNeighbors(State state):
    List<State> neighbors = new List<State>();
    // Iterate through all possible actions (turn left, turn right, move down, do nothing).
    foreach(Action action in Actions):
        // Some actions will not be possible given a state.
        if (action.IsPossible(state)) :
            // Apply the action to the state, yielding a new state.
            neighbors.Add(action.Apply(state));

    return neighbors;

// Gets the difference between two states.
float StateDistance(State state1, State state2):
    float dist = 0;
    // States differ if their cells differ
    for (int x = 0; x < NUM_X; x++):
        for (int y = 0; y < NUM_Y; y++):
           if (state1.occupancy[x][y] != state2.occupancy[x][y])
               dist += 1;

    // They also differ based on the position and orientation of the active piece.
    dist += state1.activePiece.position.distance(state2.activePiece.position);
    dist += abs(state1.activePiece.orientation - state2.activePiece.orientation);

    return dist;

// Gets an optimal path of actions from the start state to the goal state.
ActionPath GetActionPlan(State startState, State goalState):
    // Simply run Astar to find a path from the start to the goal with
    // GetNeighbors as the way of finding connections between states, and
    // StateDistance as a heuristic.
    return AStar(startState, goalState, GetNeighbors, StateDistance);

```

# Answer
> 0 votes
If you know the shape of the piece, and you know where you want to place it, I would assume you have determined the orientation of the piece already. If this is the case then I think the solution is fairly straight forward. You have a default orientation for each piece, and depending on the piece 0-3 possible alternate orientations. The number of rotations left or right are "pre-computed" to match the target orientation. After figuring out how many rotation moves, determine how many spaces to the left or the right you need to move the piece. You can calculate this by using the left-most tile on the piece and the left-most space of the desired location. Finally, the same can be done for the height. From the target orientation, in the starting position, what is the space difference between the lowest tile of the piece and the lowest open space of the desired position.

I say "pre-compute", because in my opinion there are too few possible orientations to make a complicated algorithm, and a waste of cycles trying to compute this. If you haven't done it already, it would probably take about 2 minutes to map out each piece and each possible orientation of each piece. For example, the 2x2 block has only one orientation, while the 1x4 bar, and the "s", and "z" shapes all have 2 possible orientations. And the rest of them, the "L", the backwards "L", and the broken plus sign, all have 4 possible orientations. (I think I got them all).

---
Tags: algorithm, tiles, path-finding, puzzle
---


# Question
Title: Can browser based games be developed without JS/Flash?
I have absolutely no knowledge about game development, and for 2 years I have been a web application developer (in PHP & JS).

I'd like to learn game development, and I'd also like to free myself from PHP and Javascript and learn some game related concepts in C/C++/C# (whatever is required for game development).

**Can browser-based games be developed in a language like C/C++/C#/Python and not using Javascript or Flash?** Additionally, would these be superior (in terms of graphics and browser compatibility,support) to games developed using Javascript/HTML5?

**EDIT:**

1. By browser based games I'm looking at **this.**
2. Java/Python/C++ which among these would provide a better support for browser game dev (interms of compatibility, graphics)?

# Answer
# Yes, using WebAssembly (“Wasm”) released in 2017.

The past few years of browser development have been an interesting time. JavaScript runs slowly and browser vendors (particularly Mozilla and Google) have been trying to speed it up. That raised the question: why use JavaScript at all?

In comes WebAssembly: it's **an assembly language for the web** which other languages such as C++ can compile into and run in the browser. At the time of writing it primarily targets C/C++ and Rust. It's a built-in browser feature and requires no plugins, applets, extensions, or external dependencies. It's currently implemented in Firefox, Chrome, Safari, and Microsoft Edge; you can see the latest support table for WebAssembly on *Can I Use*.

Its version 1.0 MVP launched in 2017 and further development is ongoing. Currently WebAssembly is 32-bit only (“wasm32”). Support for 64-bit (“wasm64”) is a work in progress.

It will take some time for languages to properly adopt compilation into WebAssembly. It is built with C/C++ and Rust in mind and Java, C#, and Python are not there yet.

Read more here:

# Rendering

Your options are currently pretty much just:

# Otherwise: It's JavaScript or bust.

The only real option beside Wasm is ordinary JavaScript. You'll either use JavaScript straight-up, or you'll transpile into JS from one of its precompiler languages (e.g. CoffeeScript, Coco, LiveScript, or TypeScript). You may be able to transpile your code into the ASM.JS subset which is a high-performance subset of JavaScript treated as a sort of assembly language—in fact it was one of Wasm's inspirations.

The day of applets is over because of a combination of security concerns and increasing power of modern JS and HTML5 so they are not an option:

# Just build for the desktop if you're learning.

If you're just learning to program video games I suggest starting out just with desktop development. You've been developing for the web, but if you're learning C++ or Java or Python, it's going to be easier for you to do that in their normal desktop environments. In a couple of years when WebAssembly is more developed and has wider adoption in development tools you'll be ready for it and it will be ready for you.
> 5 votes

# Answer
As a web-application developer you probably know that there's a client- and a server-side of the application. The same can be applied for a browser-based game, where you have the game-client (in HTML/JS) and the backend.

The backend can be written in any language you prefer, so you *could* write that in Python, C++ or any other language.

As for the client-side, you're basically limited to the things Jonathan Hobbs posted in his answer. That's Java (Applet), Actionscript (Flash SWF), .NET languages (Silverlight) or JavaScript. The only thing that runs natively in a browser is HTML5 and JavaScript. All other technologies use a plugin and there are no wide-spread plugins except for the ones mentioned above.

In my opinion, Flash has the best balance between potential user-base and capabilities. It comes with a powerful graphics/video and sound API and there are lots of tools and libraries to be found for Flash.

If you want to target as many devices as possible (including mobile), then your best bet is HTML5 and JS.

Another option that could be interesting for you is Unity3D. It allows you to develop in C# (which is one of your preferred choices) and you can then either deploy for the web using the Unity3D browser-plugin or compile to a SWF (Flash), where you benefit from a bigger user-base.
> 3 votes

# Answer
If you can get away with the game only working on Chrome there's NaCl which lets you write your game in C++, and run it at almost the same performance as you'd get not using the sandbox.
> 2 votes

# Answer
The examples you gave use 3D graphics, and to support those you would need to use JavaScript+Canvas or some kind of plugin. The most popular plugins supporting 3D content are Flash and Java. In theory you could run the 3D graphics on the server but this is not commercially viable. As other users have pointed out, the server can be written in any common language (not HQ9+).

If you are willing to work within normal HTTP and HTML limitations, you can build a game without JavaScript. These games will tend to use tables and forms for input, and few or no dynamic graphics. Business games work well in this format, like Simunomics. Real time strategy and 4x games can also fit this mold, such as Merchant Empires (google for screenshots, defunct), Ogame, or SkyLords (have enjoyed all four of these). Dating sims should work well with only HTML/CSS. RPGs - implementing a strictly turn based combat/movement system - would also work well with just HTML/CSS.

All of these could *benefit* from some touches of progressive enhancement with JavaScript - but none of them *require* it.

So, **yes**, browser based games can be developed without JS/Flash, and can be fun to play. However, **no**, 3D graphics in a browser window do require JS, Flash, or Java (or other less common plugins like Unity3D, Silverlight, etc).
> 0 votes

---
Tags: browser-based-games
---


# Question
Title: Scaling world - projection, view or separate matrix?
I am currently writing a simple 3D space visualisation program. Things get loaded into it from a simple XML file, which contains positions and sizes of objects in space, so you can put basically any numbers into the XML and it will show you what the things look like in 3D.

My problem is that when I try view for example a solar system, using real numbers as they really are in space (e. g. earth-moon distance = 3.844e8 m), my objects loose their form and textures get detached from faces due to limited floating position precision. I simply can't make users to scale the scene themselves, because with 10 planets or so it's too much work, and sometimes calculations little bit more complex.

Because of this, I decided to add an option that would make it possible for one to scale whole scene automatically.

My question is rather simple: If I want to scale world/scene, which matrix should I use? Projection matrix, view matrix, or a completely new matrix (please, not this one, I'm running out of `uniform`s)?

Thank you.

# Answer
You can make objects appear smaller or larger simply by moving the camera further or closer to them, so you will need to change the *view* matrix.

However, since the numbers you are dealing with are potentially large, be sure to also fix the *projection* matrix for the near and far clipping plane values.

Finally, note that astronomy pictures are often taken with a very small field of view. This is also set up in the *projection* matrix.
> 1 votes

---
Tags: 3d, matrix, projection, scale, view
---


# Question
Title: Allow Pushing|Boosting in free browser MMOGs?
There seems to be a set of rules (or game design criteria) common to free MMOGs, to encourage fair competition. One such rule is that each player may have only a single account (despite the difficulty of enforcing this effectively). A related issue has recently come to my attention, where a player who does not themselves play often, instead of using their limited resources for their own gain transfers them to another, stronger player. Commonly these might include spouses or disinterested roommates or children, or friends who are no longer active in the game.

Does this advantage violate an essential aspect of the design of the game, or should it be permitted?

# Answer
One mans trash, is another mans treasure.

The simple answer is, if you allow trading, this will happen on many different levels whether you want it to or not. Over the years I've come to accept it in my little browser game. The only thing I have done, is a simple IP lock for buying/selling things on the marketplace. Same IP? Can't buy. This presents its own issue, thanks to workplaces/colleges/etc sharing an external IP and thus you may be blocking two legit trades. I don't allow direct trading, but if I did I'd also have that same rule of limiting IPs via code check. Sadly, this is extremely easy to get around, even for common users.

If a user wants to do it, they'll find a way. In the end spending too much time trying to limit the impossible is going to drive players away. Too many security checks, or false positive bans, etc. I just put the rules out there, and if someone makes the mistake of letting it be known they are doing something like via chat, I'll will likely inflict a temporary ban or something to try and get everyone's attention.

In Summary: Thanks to various technology, if you allow trading of any type, there are going to be people who run plenty of accounts through proxies and even simple things like one on their cellphone and another on their desktop. You simply aren't going to stop someone from doing this stuff, aside from maybe finding a way to get a fingerprint/dna scanner required for your game. You can throw it in your rules if you want a moderator to keep an eye out, but that WILL cause false positives eventually.

Are you wanting a community, or bots? I'd take 1 spouse playing rarely and doing some minor trading over 1 bot on 24/7. The spouse has a tiny chance of interacting with others. And in the end, community for an mmo is how you keep players long term.

And last but not least, it is your game design. If this particular issue feels wrong, by all means spend the time to try and stop it. My opinion is simply that it will hurt your community more than help it.
> 1 votes

# Answer
Many online games actively encourage players to trade among each other. When you allow trading, you can't stop people from trading unfavorable (like "selling" valuable items for free to a good friend).

# Discouraging gifts to weaker players

When you have a game where items are an important factor of how powerful characters are, these can make the game far too easy for the receiver of said gift to still be enjoyable. Also, when players already got everything they need, they won't feel any reward when finding new items which *would* be an improvement for a character of their level but aren't for them because they have extremely overpowered equipment. But without a constant reward stream, MMOs quickly lose their appeal. The game will feel boring and dull and they will quit soon.

<sub>(personal side-rant: This is why I **hate** it when I play an MMO and high-levels start giving me stuff for free. No, you aren't helping me and you aren't making the game better for me. You are ruining my game experience! When you want me to feel welcome so I stick around, be nice, give me hints, offer me **fair** deals, but don't take away the actual game).</sub>

A common method to avoid this is to have progress requirements for equipping items, like requiring a certain character level of character stats. Nothing would stop a veteran from giving their *Level 90 Sword of Awesomeness +10* to a level 10 newbie, but the newbie won't be able to equip it before they reach level 90 themselves, so they won't have any benefit from it.

# Discouraging gifts to stronger players

Weak players sending their items and resources to stronger players can be prevented easily by making sure that the stronger player has no need for them because their progression level means that they can get these far easier themselves. When the progression level greatly affects how many resources a player has access to, a low-level player will no longer have an effective way to boost a high-level player. A level 10 player sending the 100 gold they make daily to a level 90 player won't help them much when a level 90 can make 1000 gold in a minute of regular play.

When you have any resources which accumulate even when not actively playing the game, these resources should be untradeable because otherwise they are an invitation for multi-accounting.

# Preventing either

Another option which was (afaik) invented by World of Warcraft is the "Binds when equipped" game mechanic: The first player-character who uses an item is the only one who can ever use it. The only value it has for other players is the resale value to NPC traders. This prevents veterans from handing their old equipment to other players, but still allows them to give away anything new they find but do not want to use themselves. So there is an even harsher form, the "Binds when picked up" mechanic which applies to some items and only allows the finder of the item to make use of it. These two mechanics can be used to prevent items from getting into the hands of players who shouldn't have them because of their level, but is also a great trade inhibitor, so you should think carefully about which items you want it to apply to.
> 3 votes

---
Tags: game-design, mmo
---


# Question
Title: XNA/Winforms - Nothing being drawn after calling SetRenderTarget(null)
I'm creating a basic scene/level editor using XNA/Winforms using the base classes from http://xbox.create.msdn.com/en-US/education/catalog/sample/winforms\_series\_1
Everything works fine and gets drawn to my custom graphics device control - grid, axis, random testcube.

However, I'm loading textures using Texture2D.FromStream, and then applying alpha pre-multiplication to mimic the content pipelines behaviour. This involves rendering the texture to a RenderTarget2D, overwriting the existing texture data, and then restoring the default back buffer with SetRenderTarget(null). Afterwards, the control doesn't render anything. It clears the screen with the default color, but nothing shows - no grid, no axis, no random test cube.
Curiously, if I use the same texture loading method in my XNA game, everything works as expected. Textures gets loaded and everything shows up ingame.

Things I've tried:
\- Disabling the alpha pre-multiplication function (everything shows up, nothing shows if its enabled)
\- Calling reset on the graphics device and its service to see if that fixes it (it doesn't)
\- Changing the color used to clear the screen when I've loaded a texture (screen color changes and everything vanishes)
\- Recreating my grid, axis and test box (nothing shows)
\- Fixing the projection/view so it looks at (0,0,0) (everything still disappears)

Anyone know what the underlying issue is here, or anything else I could try?

Render code

```
GraphicsDevice.Clear(Color.CornflowerBlue);

effect.World = Matrix.Identity;

// set the current view
effect.View = GetCurrentView();
effect.Projection = GetCurrentProjection();

// if wireframe, render as wireframe
if (WireframeMode)
    GraphicsDevice.RasterizerState = wireRS;

if (Scene != null)
    for (int i = 0; i < Scene.Meshes.Count; i++)
    {
        Mesh mesh = Scene.Meshes[i];
        for (int j = 0; j < mesh.MeshParts.Count; j++)
        {
            MeshPart meshPart = mesh.MeshParts[j];
            Texture2D texture = SynthesisManager.Import<Texture2D>(Scene.Materials[meshPart.MaterialIndex].DiffuseTexture);
            effect.Texture = texture;
            for (int k = 0; k < effect.CurrentTechnique.Passes.Count; k++)
            {
                effect.CurrentTechnique.Passes[k].Apply();
                meshPart.Draw(GraphicsDevice);
            }
        }
    }

// if wireframe is on, revert back to original
if (WireframeMode)
    GraphicsDevice.RasterizerState = normalRS;

grid.Draw(GetCurrentView(), GetCurrentProjection());

```

Texture Alpha Pre-Multiplication

```
blendColorState = new BlendState
{
    ColorDestinationBlend = Blend.Zero,
    ColorWriteChannels = ColorWriteChannels.Red | ColorWriteChannels.Green | ColorWriteChannels.Blue,
    AlphaDestinationBlend = Blend.Zero,
    AlphaSourceBlend = Blend.SourceAlpha,
    ColorSourceBlend = Blend.SourceAlpha
};

blendAlphaState = new BlendState
{
    ColorWriteChannels = ColorWriteChannels.Alpha,
    AlphaDestinationBlend = Blend.Zero,
    ColorDestinationBlend = Blend.Zero,
    AlphaSourceBlend = Blend.One,
    ColorSourceBlend = Blend.One
};

GraphicsDevice gd = synthesisManager.GraphicsDevice;
SpriteBatch sb = synthesisManager.SpriteBatch;//new SpriteBatch(gd);

RenderTarget2D target = new RenderTarget2D(synthesisManager.GraphicsDevice, texture.Width, texture.Height);
Viewport viewportBackup = gd.Viewport;
gd.SetRenderTarget(target);
gd.Clear(Color.Black);

// Multiply each color by the source alpha, and write in just the color values into the final texture
sb.Begin(SpriteSortMode.Immediate, blendColorState);
sb.Draw(texture, texture.Bounds, Color.White);
sb.End();

// Now copy over the alpha values from the source texture to the final one, without multiplying them
sb.Begin(SpriteSortMode.Immediate, blendAlphaState);
sb.Draw(texture, texture.Bounds, Color.White);
sb.End();

// Release the GPU back to drawing to the screen
gd.SetRenderTarget(null);
gd.Viewport = viewportBackup;

// set the render target as the new texture
texture = target as Texture2D;

```

\[EDIT\]

Further investigating has revealed this section of code to be the cause of my problem

```
// Now copy over the alpha values from the source texture to the final one, without multiplying them
sb.Begin(SpriteSortMode.Immediate, blendAlphaState);
sb.Draw(texture, texture.Bounds, Color.White);
sb.End();

```

For whatever reason, this seems to be causing nothing to be rendered out. How and why I don't know, since this is the only time I'm using a SpriteBatch (currently) in my code, and all my other draw calls are using DrawPrimitives and DrawIndexedPrimitives.

\[EDIT 2\] I've managed to narrow it down further. The issue seems to be with the `ColorWriteChannels = ColorWriteChannels.Alpha` line in the `blendAlphaState` tantalizer. Why this only causes a problem in WinForms and not XNA stumps me. Its all using the same code underneath.

# Answer
So, you draw all on the render target and after calling gd.SetRenderTarget(null) you need draw your render target on the screen.

```
gd.SetRenderTarget(target);

```

// ... drawing on the render target ...

```
gd.SetRenderTarget(null); // now draw on the screen ...

sb.Begin();
sb.Draw(target, Vector2.Zero, Color.White); // ... your rended target
sb.End();

```
> -1 votes

---
Tags: xna, windows-forms
---


# Question
Title: How can I test whether points are within a polygon?
I have 2D-points, which boundaries depict a polygon. The points are at integer positions (no fractions possible).

Now I want to build an enumerator in C# that returns all points that are **inside** the polygon. Implementing the enumerator is not the issue, but how do I efficiently get all the points? The polygon can be quite big.

# Answer
> 7 votes
What you are seeking is a solution to the "point-in-polygon" problem. It is described in Wikipedia here:

---

---

You can find C code following the links to *Computational Geometry in C*, or at many other locations found by searching for "point-in-polygon" code.

# Answer
> 9 votes
You will need to process all the points at least once so if this check is done only once there isn't much you can do to speed up the test other than brute-forcing it using parallelism.

If the test is going to be run multiple times there are ways to pre-calculate tables to help, such as a grid of cells marked as \[definitely inside (**green** in image), outside (**red**), and maybe (**blue**)\], only points that fall in the blue cells need to be tested against the polygon.

But if it's run only once with just few points relative to the grid or too many "maybe" cells then building this table is likely to take more time than just brute-force testing your points.

You need to have many more points than cells (low resolution grid) for this to turn a "profit", and most cells must end up as definite inside or outside (high resolution grid), so finding a balance that speed things up between those two factors can be difficult.

It's easier and more consistent in terms of gains to just split the number of points between multiple threads and do a simple odd-even intersection test. GPGPU processing such as OpenCL can give you an easy and **huge** speed up for this kind of test simply by using a massive number of cores.

# Answer
> 2 votes
Every polygon can be represented as lines\[L\] with interception points\[P\].For each line you calculate weather it is above or below a point Pn(n is the index of array P) which is not part of the line Lm.When you measure all the lines you save the result in one dimensional bool array V\[number\_lines\].When you have a random point A.Then you make for loop for each line and you make the same check if point A is below or above line Li.As you do it you compare the result to V\[i\] and if its not the same you return true if point A is over the line Li else you return false.Once the loop though all lines from \[L\] you can return true.As you do this you can know if a point is inside or outside an polygon easly which means that you can loop though all A points in the polygon bound box Box\[Px(min),Py(min),Px(max),Py(max)\].To detect weather point A is above or below line L you must turn line L into function f(x)=y=ax+b by using the two points representing the line as x=P1.x y=P1.y and x=P2.x x=P2.x including them into system.Once you have calculated the function f(x) you must simply test if f(A.x) \>\<= A.y . If f(A.x)\>A.y then the line L is above point A.If =0 then its on the line else its below it. It might look a bit complicated, but the most of those calculations are instant and can be calculated only once. As you store V,L,P arrays in the polygon represented class.

PS: If line L with points P1 and P2 is such so P1.x=P2.x then you cant create an function based on f(x)=ax+b you must simply check if the point A(which you are comparing if its below or above line L)A.xP1x. its above.of if A.x=P1.x then its on it

# Answer
> 1 votes
You could possibly treat it as a graph traversal problem. If you treat adjacent points as 'children' of each other and add each child of your boundary points to a list of open nodes (ie. unvisited nodes), then your enumerator could explore this list.

In case you're unfamiliar with search algorithms, this would probably look something like:
For each point; add the point to a set of closed nodes (ie. visited). If the point is within the polygon, add it to your enumerator and add it's children to your list of open nodes. Continue until your list of open nodes is empty. Also, only add nodes to your open list if they're not already on your closed list.

A couple of notes:

* I would argue that this approach *could* be more efficient than simply 'drawing lines' through your shapes. Notably; if any of your polygons are concave, drawing lines may not discover some sections of the shape without checking arbitrarily large numbers of points that aren't within the shape. However, you will end up with a much larger memory overhead than using lines.
* If you don't need every point straight away, this approach could allow you to generate the next point on-demand.
* You could improve the performance of the traversal if your problem is amicable to the use of a heuristic. This is most relevant if you're looking for a particular point (or group of points) which satisfy some property.

# Answer
> 1 votes
Have a look at this. It works through some very clear diagrams.

http://www.mathopenref.com/coordpolygonarea2.html

They are just calculating area and you are enumerating points. However you can adapt these ideas. Look carefully at 'A More Complex Case' and how the horizontal lines divide the polygon into a set of trapezoids (if you recognize a triangle as degenerate trapezoid with a zero length side).

If your polygons are (potentially) concave you need to discard some trapezoids based on the direction of travel Y(n)-Y(n+1) rule mentioned in the text.

So, now you've reduced enumerating points in a polygon to enumerating points in a series of trapezoids. That shouldn't be too hard particularly given the trapezoids are nicely oriented being 'trapped' two lines both parallel to the X axis. It is probably easiest to do **that** in a raster scan so you only have calculate the start X and end X of each raster row.

Your data structure might look like a list of polygons, an index indicating which polygon you're in, which x and y coordinate your at and the end index of the raster row you're in.

I'm assuming you don't mind what order you enumerate in!

Further complexity will be incurred if your 'polygons' included disjoint shapes (i.e. actually more than one polygon or could contain polygonal 'holes'.

The complexity of obtaining the trapezoids is quite low but iterating over a vast number of points may be quite slow. I have no idea what you're doing this for but as pointed out by Stephane Hockenhull above a conventional weight of making it easier is to used a coarsening approximation.

That would mean actually scanning in steps of (say) 5 and (if your algorithm is ameanable) treat the centre point of a 5\*5 'cell' as somehow representative.

I hope you weren't looking for an easy answer? I'd love to see some code for this!

---
Tags: c#, mathematics, geometry
---


# Question
Title: c - Starting an user defined function after the current one ends
The game I am creating displays a menu before starting, the user may select to start the game, or do some stuff. When the user selects an option, I need to call another function which actually does the selected option (start the game, configuration, etc...), the problem is that since I called that function from the menu function all the variables from the menu stay in memory. So I want to finish the menu function and remove all of its contents from memory and then start the function corresponding to the option selected, if the user goes back to the menu then load everything again and unload it when its finished. The problem is I there is no way (that I'm aware of) to tell the menu function which function to call after it finishes.

I though about starting the function corresponding to the option selected in another thread while the menu function finishes (what could possibly go wrong...) like this:

```
int menu()
{
    Load_menu_stuff_to_memory();

    int quit = 1;
    while(quit)
    {
        if(option_a_selected)
        {
            //the new function will be started in a new thread while the menu one finishes
            quit = 0;
            start_option_a_in_new_thread();
        }else if(option_b_selected)
        {
            //the new function will be started in a new thread while the menu one finishes
            quit = 0;
            start_option_b_in_new_thread();
        }
    }

    Deallocate_menu_stuff();
}

```

But I'm not sure if the new thread will end when the menu function does or be left like in the limbo or something.

Also I'm not sure if when the menu function ends the program will reach end of `main` (not to be confused with `menu`)

So: will my method work?

if not:

how can I call a random function but only after the caller function has finished?

# Answer
> 2 votes
First, the answer to your direct question which is whether threads continue running when the `main()` thread ends can be found at this Stack Overflow answer:

https://stackoverflow.com/a/4667273/377922

> when the main thread (that is, the thread that runs the `main()` function) terminates \[...\] the process terminates and all other threads stop.

So, as long as you continue running your main game loop, the other threads will continue to run until they end. This might take some re-factoring of your loop, because you are jumping out of it and quitting the whole game.

However, I would **strongly** discourage you from doing that, because using multiple threads without a really good reason will add an added dimension of complexity. Debugging multiple threads on the same data can be tricky at best and can cause performance problems by trying to avoid writing over data.

I would recommend using a state machine to control your state transitions. I'm not well versed in C, so I'll give you some (object oriented) pseudocode instead:

```
while (quit == false)
{
    currentState->update();
    // Returns an enum of the state type.
    enum StateType newState = currentState->getNewState();

    if (currentState != newState)
    {
        currentState->cleanUp();
        // Creates the appropriate state from the given enum value.
        currentState = createStateObject(newState);
        currentState->initialise();
    }
    currentState->render();
}

```

In `getNewState()` you should return an enum value the state that you want to transition to, based on the user input in the `update()` function. I suggest using an enum value instead of the raw function pointer to keep your files and `include` statements a bit tidier.

In your particular example `initialise()`, is where you'd put the contents of `Load_menu_stuff_to_memory()`, `update()` will contain the `if...else` clause and `cleanUp()` will contain the contents of `Deallocate_menu_stuff()`. Of course in C you'd have groups of plain functions for each state, e.g. `main_menu_update()` and `main_menu_render()`.

One last thing is that it's possible to make `currentState` a stack of states, each with render and input flags so that in future you can overlay stacks, for a pause menu or running your game in "demo mode" with the main menu drawn on top.

# Answer
> 1 votes
You could use an "event/task buffer/queue" to produce this behavior.

tl;dr: think of a main loop and a task array; the first task is initializing the menu which in turn will allow the user to activate a task that initializes the game. When a task is over, you return to this main loop, so all the resources that were used by the task, could be safely destroyed and freed from memory. The new task is queued by the menu before the menu is destroyed and then started when you get back to the main loop. You may also wish to use threads if you need to run the menu and the game simultaneously in the future.

In the main() allocate the "event buffer/task queue" and fire the starting event `init_menu`, then go into the main loop that"ll check if there is a pending or currently active event, if not, then end the loop and the process. Since there is an `init_menu` event, the loop calls the `init_menu_func` and the menu starts up. You are now running the menu in it's own thread or in the main thread; when someone chooses an option, the menu adds the correct event/task to the buffer, in this case `init_game`. The menu task removes itself from the active events buffer,exits it's loop and terminates, freeing all resources.

The main loop is now active and it checks if there is a pending event as usual, it then activates the `init_game` event and the game starts.

# Answer
> 1 votes
```
#include stdio.h

//Author: Coty Embry
/*  Program Comment: first and foremost im assuming you know how to code in c (to an extent):
    I would say to go at it like a showmenu that is a subprogram
    (think boolean value) which will show the menu, do what
    you need, then release the memory. Once it accomplishes
    what you need it to then send back the info you need then
    release the memory
    <2 Timothy 2:15>
*/

//I know im going a little different direction than you did in your example by using a switch statement, but anyways lets get to it:
    int menu(int); //this declares that there is going to be a menu

int main(void) {
    select = showmenu();
    switch(select) { //here the program switches to select (which is what the menu function will return) - hopefully you follow what i mean
        case 1: //if menu returns an int that == 1 //TODO (i.e. write your code!! lol) -
        case 2: //TODO
        //so on and so forth
    }

//this is the subprogram
int showmenu(void) {
    //here is where the magic happens (im answering you question - hopefully)
    /*  so to resolve you're issue I think the best thing to do here is to
        declare a variable then assign what you need to, free the memory,
        THEN return what you need
    */
    int whatyouneed; //sorry, but the variable name felt appropriate lol
    //TODO
    //printf("enter what you need and press enter\n");
    scanf("%d", & whatyouneed); //check to make sure syntax is correct
    //now free your memory or whatever you need to do
    Deallocate_Menu_stuff();
    //honestly not sure if you even need to free your memory - this function shouldn't
    //take much memory...but to make the program better i guess it could help in the overall scheme. im not sure to be honest, just speculating
    return whatyouneed; //returns the data you wanted and exits the menu subprogram

    //doing this basically makes it where the only "memory" that is used is the memory used to store that one variable

}

```

---
Tags: c, multithreading, game-state, menu
---


# Question
Title: Make continuos movements with controllers in LibGDX
I've been trying to make the OUYA controlers work with a LibGDX Framework Practice Game.

Everything is working perfectly expected for one thing : The movements are not continuos.

The problem is, when I press the DPAD or the Joystick into the right for example, it moves for the number of pixels I've defined and then stops, I need to release the button and press again.

When I use the Keyboard I put the code on the "render" method, using this method when I press the Right Arrow Key the sprite won't stop movie until I release the button, but since the controller use a ControllerListener I don't really know how to solve this issue.

This is what I have so far :

```
public class MyOntem extends ApplicationAdapter implements ApplicationListener, ControllerListener {
SpriteBatch batch;
Sprite sprite;

@Override
public void create () {
    batch = new SpriteBatch();
    sprite = new Sprite(new Texture("badlogic.jpg"));
}

@Override
public void render () {
    if (Gdx.input.isKeyPressed(Input.Keys.DPAD_RIGHT))
        sprite.setX(sprite.getX() + 10f);

    if (Gdx.input.isKeyPressed(Input.Keys.DPAD_LEFT))
        sprite.setX(sprite.getX() - 10f);

    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.begin();
    batch.draw(sprite, sprite.getX(), sprite.getY());
    batch.end();
}

@Override
public boolean buttonDown(Controller controller, int buttonCode) {
    if(buttonCode == Ouya.BUTTON_Y)
        sprite.setY(sprite.getY() + 1);
    if(buttonCode == Ouya.BUTTON_O)
        sprite.setY(sprite.getY()-1);
    if(buttonCode == Ouya.BUTTON_U)
        sprite.setX(sprite.getX() - 1);
    if(buttonCode == Ouya.BUTTON_A)
        sprite.setX(sprite.getX() + 1);

    return false;
}

@Override
public boolean axisMoved(Controller controller, int axisCode, float value) {
    // Left Stick
    if(axisCode == Ouya.AXIS_LEFT_X)
        sprite.translateX(10f * value);
    if(axisCode == Ouya.AXIS_LEFT_Y)
        sprite.translateY(-10f * value);

    // Right stick
    if(axisCode == Ouya.AXIS_RIGHT_X)
        sprite.rotate(10f * value);
    return false;
}

```

Thank you in Advance.

# Answer
`buttonDown()` and other methods in`ControllerListener` only fired when the key is pressed.If you want constant movement you need a variable and set for example when KeyRight is called and unset when keyRight is released or another key like KeyLeft pressed There is a good sample here

http://www.gamefromscratch.com/post/2014/11/24/LibGDX-Video-Tutorial-Handling-Keyboard-Mouse-and-Touch-Input.aspx

As you see

```
   public boolean keyDown(int keycode) {
      if(keycode == Input.Keys.RIGHT)
         movingRight = true;
      return true;
   }

```

`movingRight` equals true whenever right arrow key pressed and in `render()` method try

```
   public void render () {

      if(movingRight)
         sprite.translateX(1f);
       //...
}

```
> 1 votes

---
Tags: libgdx, sprites, movement, controllers, ouya
---


# Question
Title: how can I split the screen into two screens and make Gdx.input.setInputProcessor () accept two processors?
I want to draw in the first screen portion, and manipulate the buttons in the second part.

This is what I tried:

if (mouse.x \<600) { Gdx.input.setInputProcessor (new InputProcessor () {

```
Override
public boolean touchup (int arg0, int arg1, int arg2, int arg3) {
return false;
}
.
.
.
.
.
}
if (mouse.x> = 600) {
Gdx.input.setInputProcessor (stage);
}

```

the problem is that I have the ability to go from the first part to the second but I'm not allowed to go from the second to the first, it blocks the mouse coordinates in x = 600 This is what I tried

# Answer
You should not do it like that. Use scene2d for your buttons and menus and use InputMultiplexer to set up multiple input processor.
> 1 votes

---
Tags: libgdx
---


# Question
Title: How can I correctly use an unordered_multimap as entity and component storage?
# The Setup

I've made a few games (more like animations) using the Object Oriented method with base classes for objects that extend them, and objects that extend those, and found I couldn't wrap my head around expanding that system to larger game ideas. So I did some research and discovered the Entity-Component system of designing games. I really like the idea, and thoroughly understood the usefulness of it after reading Byte54's perfect answer here: What is the role of "systems" in a component-based entity architecture?.

With that said, I have decided to create my current game idea using the described Entity-Component system.

Having basic knowledge of C++, and SFML, I would like to implement the backbone of this entity component system using an `unordered_multimap` without classes for the entities themselves.

# Here's the idea:

An `unordered_mulitmap` stores entity IDs as the lookup term, while the value is an inherited Component object. Examlpe:

```
 ____________________________
|ID          |Component      |
 ----------------------------
|0           |Movable        |
|0           |Accelable      |
|0           |Renderable     |
|1           |Movable        |
|1           |Renderable     |
|2           |Renderable     |
 ----------------------------

```

So, according to this map of objects, the entity with ID 0 has three components: `Movable`, `Accelable`, and `Renderable`. These component objects store the entity specific data, such as the location, the acceleration, and render flags. The entity is simply and ID, with the components attached to that ID describing its attributes.

# Problem

I want to store the component objects within the map, allowing the map have full ownership of the components. The problem I'm having, is I don't quite understand enough about pointers, shared pointers, and references in order to get that set up. How can I go about initializing these components, with their various member variables, within the `unordered_multimap`? Can the base `component` class take on the member variables of its child classes, when defining the map as `unordered_multimap<int, component>`?

# Requirements

I need a system to be able to grab an entity, with all of its' attached components, and access members from the components in order to do the necessary calculations and reassignments for position, velocity, etc.

Need a clarification? Post a comment with your concerns and I will gladly edit or comment back!

# Answer
`map<Key, Value>` (and it's mates) holds `Value`, well, by value. If you try to give it an instance of derived class to hold as value, most likely "slicing" will occur. More about slicing: https://stackoverflow.com/q/274626/1125702

`std::unique_ptr<Component>` seems exactly what you want. It manages lifetime and memory of owned object. By convention, only `std::unique_ptr` may "own" it's objects, i.e. anything other may only temporarily refer to given object (either by raw pointer or by references). It is programmer's task to ensure that `std::unique_ptr` will outlive any other references to "owned" object.

Usage is quite simple.

```
// type aliases for convenience
using ComponentPtr = std::unique_ptr<Component>;
using ComponentContainer = std::unordered_map<std::string, ComponentPtr>;

// instance of container
ComponentContainer cc;

// insert component (quick way)
cc["SomeComponent"] = std::make_unique<SomeComponent>(arg1, arg2, ...);

// 'get' returns raw pointer to owned object
SomeComponent * sc_ptr = cc["SomeComponent"].get();
sc_ptr->hello();

// reference, if '->' annoys you
SomeComponent & sc_ref = *cc["SomeComponent"].get();
sc_ref.hello();

```
> 1 votes

# Answer
You might actually be better of with using std::map for this one, depending on your exact use-case. I did some testing on our little rendering framework where I thought std::unordered\_map would be good for maintaining a map of graphics resources (we are using std::map there now).

I found that it's actually slower to use std::unordered\_map since the hash-function (e.g. std::hash()) is slowing things down significantly.

Of course it might depend on the exact usage, but as always: profile profile profile.

And of course, like mentioned above, make sure you don't slice your class and use pointers such as std::unique\_ptr.
> 1 votes

---
Tags: c++, entity-system, component-based, sfml
---


title: nurbs and pathfinding optimization

text:
# Question
Title: nurbs and pathfinding optimization
I'm working on a project, and my current milestone is pathfinding. I have a working prototype that consists of several components:

1. a manually drawing of a path, that matches the visual path that the characters are allowed to walk on
2. a grid for A\* calculations
3. a ray that pokes through the grid cells neighbors during the A\* evaluation, and if it intersects a perfect GREEN pixel, sets the cell as walkable for A\* calculations, and if it hits a transparent pixel, leaves the cell as not walkable
4. after the rough A\* path is calculated, an algorithm for nurbs makes the turns in the path, more ease in, so to speak

My current issue is that the nurbs path Looks like it can use some optimization, And I can use your help to nudge me in the right direction, either pointing me to some literature or directly brainstorm.. Please see the picture below, it should be clearer what I mean, my goal is to have nurbs in a more straight-line, perhaps using some sort of extrapolation algorithm that is based on the A\* result, and simplifies it in such a way that the nurbs curve is straighter from start to end

the project is browser-based Away3D framework(sea3D framework more specific)

its github repository can be found here

Thanks!

below is an example that shows the components described above: in GREEN the path that was draw manually, in RED the A\* walkable path, in BLUE shades the nurbs

And another example how it actually looks in game, without all the pathfinding visual representations

# Answer
If you're feeling adventurous, you could try a simple stochastic hill climbing shortcutter on your path before fitting a NURBS curve. Here's how it would go in pseudocode:

```
function Path Shortcut(Path path):
    // Shortcut the path until a max number of timesteps is reached
    for t = 1 to MAX_TIMESTEPS
        // Get two random path indices to shortcut between
        i = GetRandom(1, path.length());
        j = GetRandom(i + 1, path.length());

        // Create a straight line between the two path points
        linear_segment = InterpolateLine(path(i), path(j));

        // The new path is one that is the same up to index i, then linear,
        // then the rest of the path
        shortcut_path = [path(1 : i), linear_segment, path(j : path.length())]

        // Check the linear segment to see if it goes outside of the green region.
        // If it does, continue shortcutting. Otherwise, modify the path to contain
        // the new segment
        if !CollisionCheck(linear_segment)
            path = shortcut_path

    // When we're done shortcutting, the new path is returned.
    return path;

// Creates a straight line between the start and the end with a given step size
function Path InterpolateLine(Node start, Node end, float step = 1):
   Path toReturn = [];
   Vector dir = (end - start);
   float length = dir.Length();
   dir.Normalize();
   // Just step along a line from the start to the end.
   for dPath = 0; dPath < length; dPath += step:
       toReturn.Add(dir * dPath + start);

   return toReturn;

// Returns whether any point in a path is invalid
function bool CollisionCheck(Path path):
    foreach node in path:
        if (!IsWalkable(node)) return false;
    return true;

```

After a few tens of iterations, the shortcutter will converge to a local optimum that is as straight as possible given the original path found by A\*. You can control path quality by increasing MAX\_ITERATIONS. You can also do some clever hacking by making sure that the path is not already straight and exiting early if it is.
> 0 votes

# Answer
I'm going to copy paste some basic code, I came up with in case it helps anyone

```
    private function hillClimbing( pathCells: Array): Array
    {
        var pathVectors: Array = new Array;
        for(var k:int=0;k<pathCells.length;k++)
        {
            pathVectors.push(pathCells[k].position);
        }
        trace( "path length before", pathVectors.length);

        var linear_segment: Array = new Array;
        var MAX_TIMESTEPS:int = 25;
        // Shortcut the pathVectors until a max number of timesteps is reached
        for (var t:int=0;t<MAX_TIMESTEPS;t++)
        {
            var shortcut: Array = new Array;

            // Get two random pathVectors indices to shortcut between, so ignore 0 and pathVectors.length-1,
            var i:int = int(Main.STATES.randomNumber(0, pathVectors.length-2));
            var j:int = int(Main.STATES.randomNumber(i+1, pathVectors.length-1));
            // Create a straight line between the two pathVectors points
            if(pathVectors[i] != null && pathVectors[j] != null)
            {
                trace( "selected cell",i,pathVectors[i], "AND",j,pathVectors[j]);
                linear_segment = InterpolateLine(pathVectors[i], pathVectors[j]);
            }
            else
                trace( "a cell is empty",i,j,pathVectors[i],pathVectors[j]);

            // The new pathVectors is one that is the same up to index i, then linear,
            // then the rest of the pathVectors
            //if linear segments returned is not null, then we can create a shortcut using it
            if(linear_segment != null)
            {
                trace("linear_segment length", linear_segment.length);
                for(k=0;k<i;k++)
                {
                    shortcut.push(pathVectors[k]);
                }
                shortcut = shortcut.concat(linear_segment);
                 for(k=j+1;k<pathVectors.length;k++)
                 {
                     shortcut.push(pathVectors[k]);
                 }

                 //set the updated path  as the shortcut
                 trace( "after iteration",t, "The path length is", shortcut.length);
                 pathVectors = shortcut;
            }

        }

        // Creates a straight line between the start and the end with a given step size
        function InterpolateLine(start:Vector3D, end:Vector3D, step:int = 16): Array
        {
            var toReturn: Array = new Array;
            var dir: Vector3D = end.subtract(start);
            var ratio: Vector3D = new Vector3D;
            var _length:Number = dir.length;
            trace("dir length",dir.length);
            // Just step along a line from the start to the end.
            var max: Number = Math.max(Math.abs(end.x - start.x),Math.abs(end.y - start.y),Math.abs(end.z - start.z));

            if(ratio.x == 0 && ratio.y == 0 && ratio.z == 0)
            {
                ratio.x = (end.x - start.x)/max;
                ratio.y = (end.y - start.y)/max;
                ratio.z = (end.z - start.z)/max;
            }//this is a poor attempt to normalize by 3-D vector, there are better ways/classes

            for (var dPath: Number = 0; dPath < _length; dPath += step)
            {
                var result: Vector3D = start.add(new Vector3D(dPath*ratio.x,dPath*ratio.y,dPath*ratio.z));
                //trace( "resulting step", result);
                toReturn.push(result);
            }

            //check to see if the  vectors generated are completely on path or not
            if( shortcutter(toReturn))
            {
                trace( "the return length",toReturn.length);
                return toReturn;
            }
            else
            {
                trace( "shortcutter not valid");
                return null;
            }
        }
        // When we're done shortcutting, the new path is returned. ideally it would never have less than 4 vectors
        trace( "updated path contains", pathVectors.length, "vectors for nurbs");
        return pathVectors;
    }

        public function shortcutter(vectors: Array): Boolean
    {
        var ray:Ray = new Ray;
        for (var i:int=0;i<vectors.length;i++)
        {
            var vector: Vector3D = vectors[i];

            //create  the corner vectors of the plane, this plane is the image for the path
            var lt:Vector3D = new Vector3D;
            var rb:Vector3D = new Vector3D;
            var lb:Vector3D = new Vector3D;
            var rt:Vector3D = new Vector3D;

            //this is temporary needed to hold the plane to get the material later on
            var planes: Array = new Array;
            //trace( "coordinates",vector.x,vector.y, "grid",vector.gridC,vector.gridR);

            //check to see which planes is the vector supposed to intersect/be part of
            //if found, then set its vector corners for future triangulation
            for(var j:int=0;j<Main.mapTilesPath.numChildren;j++)
            {
                if(Math.abs(vector.x) > Math.abs((Main.mapTilesPath.getChildAt(j) as Mesh).position.x) &&
                    Math.abs(vector.x) < Math.abs((Main.mapTilesPath.getChildAt(j) as Mesh).position.x) + dim.x &&
                    Math.abs(vector.y) > Math.abs((Main.mapTilesPath.getChildAt(j) as Mesh).position.y) &&
                    Math.abs(vector.y) < Math.abs((Main.mapTilesPath.getChildAt(j) as Mesh).position.y) + dim.y &&
                    Math.abs(vector.z) > Math.abs((Main.mapTilesPath.getChildAt(j) as Mesh).position.z) &&
                    Math.abs(vector.z) < Math.abs((Main.mapTilesPath.getChildAt(j) as Mesh).position.z) + dim.z)
                {
                    //if((Main.mapTilesPath.getChildAt(j) as Mesh).name)     trace( "intersecting",(Main.mapTilesPath.getChildAt(j) as Mesh).name);
                    lt = (Main.mapTilesPath.getChildAt(j) as Mesh).position;
                    rb = (Main.mapTilesPath.getChildAt(j) as Mesh).position.add(new Vector3D(-dim.x,-dim.y,dim.z));
                    lb = (Main.mapTilesPath.getChildAt(j) as Mesh).position.add(new Vector3D(0,-dim.y,dim.z));
                    rt = (Main.mapTilesPath.getChildAt(j) as Mesh).position.add(new Vector3D(-dim.x,0,0));
                    //if a plane is found. Keep a future reference to get the material later on
                    planes.push((Main.mapTilesPath.getChildAt(j) as Mesh));
                }
            }
            //this is the destination vector when checking the ray intersection, it's a simple line on the Z axis starting from the  vector position
            var dest: Vector3D = vector.add(new Vector3D(0,0,Main.cellSize));

            /*//draw some lines for visual representation of the  rays, not needed in final production
            //be advised that the calculations for path and the lines have a Delta, which is the camera position
            //this means that calculations for path are relative to the absolute position  of the vectors and meshes
            //the lines are displayed relative to the camera, so they appear to be "under" the actual vectors
            var line:LineSegment = new LineSegment(vector.subtract(adjustCamera),dest.subtract(adjustCamera),0x00ffff,0x0000ff);
            var lineSet:SegmentSet = new SegmentSet();
            lineSet.addSegment(line);
            Main.away3dView.scene.addChild(lineSet);*/

            //because we have to check the intersection with a plane, we first split the plane into 2 triangles, if all goes well then either there is no intersection,  or at most there is only one
            var intersectL:Vector3D = ray.getRayToTriangleIntersection(vector, dest, lt, lb, rb);
            var intersectR:Vector3D = ray.getRayToTriangleIntersection(vector, dest, lt, rt, rb);
            var intersect: Vector3D = new Vector3D;
            if(intersectL != null)
            {
                intersect = intersectL;
                //trace("LEFT intersect ray: "+intersectL);
            }
            if(intersectR != null)
            {
                intersect = intersectR;
                //trace("RIGHT intersect ray: "+intersectR);
            }

            //here, if an intersecting plane is found, we actually take the image path and evaluate the value of the pixel where the vector intersects
            //if the value is zero, then the intersection was with a transparent pixel, otherwise it should be GREEN
            if(planes.length > 0)
            {
                var material:TextureMaterial = ((planes[0] as Mesh).material as TextureMaterial);
                var texture:BitmapTexture = material.texture as BitmapTexture;
                var bitmapData:BitmapData = texture.bitmapData;

                //we need to convert global to local and 3-D to 2-D coordinates, and remember the camera Delta. :-)
                var local:Vector3D = lt.subtract(intersect);
                var _x:int = local.x;
                var _y:int = -local.z/caz + Math.round(adjustCamera.y/say);

                //If the pixel is GREEN, this means the vector should be made walkable as  it's on  "path"
                if(bitmapData.getPixel(_x,_y).toString(16) != "ff00")
                {
                    trace( "invalid shortcutter!");
                    return false;
                }
            }
        }
        return true;
    }

public function nurbsCurve(pathCells: Array): void
    {
        //before nurbs,  do a stochastic hillclimbing
        var pathVectors: Array = new Array;
        pathVectors = hillClimbing(pathCells);

        trace( "hillclimbing done",pathVectors.length);

        var i:int;//set it here to be used later in for loops
        var controlPoints:Vector.<Vector3D> = new Vector.<Vector3D>();
        //evaluate all  cell position in the array path
        for(i=0;i<pathVectors.length;i++)
        {
            var vector:Vector3D = pathVectors[i];
            controlPoints.push(vector);
        }

        trace( "control points length", controlPoints.length);

        var result:Vector.<Vector3D> = new Vector.<Vector3D>();
        var increment: Number = 0;
        while (increment <= 1)
        {
            var out:Vector3D = new Vector3D;
            out = Nurbs.nurbs(increment,controlPoints);//use only with 4 or more control points
            //out = Nurbs.nurbs(increment,controlPoints,2,1);//use only with 3 or less control points
            result.push(out);
            increment+=0.002;
        }

        trace( "number of nurbs", result.length);

        for(i=0;i<result.length;i++)
        {
            var l:Vector3D = result[i].subtract(Main.MAP3D.adjustCamera);
            var line:LineSegment = new LineSegment(l,l.subtract(new Vector3D(0,0,32)),0x00ffff,0x0000ff);
            var lineSet:SegmentSet = new SegmentSet();
            lineSet.addSegment(line);
            Main.away3dView.scene.addChild(lineSet);
            //trace( "results", result[i], result.length);
        }
    }

```
> 1 votes

---
Tags: path-finding
---


# Question
Title: How can I parse the leaderboard data returned from Google's API?
We're developing our first Android game and we want to get leaderboard data from Google Play Game Services and use the score data from the different leaderboards.

I am able to use Unity's `WWW` class to get the plain text results of (for example) this data, but handling would take a lot of parsing, wouldn't it?

# Answer
Google's APIs return JSON data. The format of that is described by the API documentation (for example, the format of the leaderboard data is here).

You are correct that parsing it yourself would be involved. However, the good news is that there are already several APIs that will parse JSON into more-friendly data structures your code can consume. SimpleJSON, as mentioned in the comments, is one such option.

Once you have such an API up and running, you can feed the plain-text response you got from the `WWW` module into it. Most APIs have a method to do so; for example, with SimpleJSON you'd do something like:

```
using SimpleJSON;

// ...elsewhere in some handler code...
var root = JSON.Parse(wwwResponseText);

```

Then you can access the children of the `root` object like you'd access a dictionary (and you can treat JSON arrays as C# arrays). For example, if `wwwResponseText` contained a leaderboard result like:

```
{
  "kind": "games#leaderboard",
  "id": string,
  "name": string,
  "iconUrl": string,
  "isIconUrlDefault": boolean,
  "order": string
}

```

you could recover the ID and name of that leaderboard like:

```
var leaderboardId = root["id"].ToString();
var leaderboardName = root["name"].ToString();

```
> 2 votes

---
Tags: unity, android, google-play
---


title: Prevent movement cheating in MP games

text:
# Question
Title: Prevent movement cheating in MP games
I have read a lot about movement in multiplayer games, but not so much on preventing cheating.

Let's say a client sends moves packets whenever the player press a movement button, then the server checks if that move is valid (that is, if the player is not colliding with anything).

At the same time, there must be some speed check, like dropping packets if the client is sending too many in a short period of time. But the server has no guarantees whether the packets received were sent at the same time or just received at the same time. Client could include a timestamp, but there are 0 guarantees it was crafted by a malicious client.

In short, how can i validate movement speed?

# Answer
Your client never moves you. The server moves you.

Think about it this way:

> ```
> A client sends a movement request packet to the server to start moving.
>
> The server says sure you can start moving, there's nothing in the way.
>
> The server begins moving the player in x direction.
>
> The same client ask the server to start moving again.
>
> The server says, you're already moving stupid.
>
> ```

You always want your client to be requesting things from the server.

Speed hacks are normally achieved by setting the movement speed illegally. For instance, if there's a "speed power up", "mounted on horse", "flying", etc...the hacker sets the movement to one of those states to get faster movement.

A basic anti-speed hack is checking for a maximum velocity that the character can never go over. Figure out how fast they will ever be moving, if a character is ever over it, disconnect them for speed hack.

```
if (playerSpeed > 10){
  Kill(Player);
}

```

You could also check for mount/vehicle pertaining to speed

```
if (Player!= mounted && playerSpeed > 10){
  Kill(Player);
}

```

If the player is NOT mounted to increase above maximum walking speed, but yet moving faster, they must be cheating.
> 4 votes

# Answer
The server should be authoritative on this matter, the client should never be trusted and each action should be checked by the server.

The typical movement scenario would be:

1. player wants to move, so it sends a move message (actual position, direction), and immediately starts the move animation.
2. the server receives the message, it tests if the move *was* legal (lag compensation here, it considers game state some ms ago depending on latency). If the move was indeed legal then the server computes the new position of the player at current time + latency estimation (when will the player receive the server message). If the move was *not* legal, the server sends a legal position, or another message.
3. the player reacts to messages: for example updates its position based on server answer. The new position would be a mix of the player estimation (result of the movement in step 1) and the server answer, the easing between these would not be noticeable in general but in case of speed cheating it would result in a pop back to a legal position.

Regarding packet loss and packet reordering, which both may happen in udp, you consider a queue of messages and ignore old ones. Old message movement are not relevant any more because you already considered a newer one.

Some messages have to be reliable, for example gun firing so some reliability mechanism has to be implemented above udp for these.

If you receive too much packets from a client you could just decide to disconnect him for flood.

*Comment about reliability:*

There are three degrees of reliability :

* *non reliable :* packets may be lost or arrive in different order (UDP). Movement belongs here, you send many of them losing one is not big deal, if you have a sort of msg number you drop old ones. Anyway they are too old now.
* *reliable :* packets cannot be lost, but may arrive in different order (UDP + reliability layer). Ex. when you fire a gun you sent this once, you do not want to lose the message.
* *ordered reliable :* packets cannot be lost and always arrive in order (TCP). Ex. Chat messages, you want your messages to always arrive in order.
> 1 votes

# Answer
I will keep it short and sweet.

There are two "servers" running. One locally and one remotely online. The user simply operates the mouse and keyboard to control the game. Input is parsed by the client and converted to commands (e.g. move forward / turn left / jump). The client sends these commands to the local server and remote server. They both process these commands. Very often, the remote server sends the correct state to the local server and the local one quickly interpolates it's "predicted" state with the true global state on the remote server. All rendering is done from the model on the local server.

1. Use two server processes, a local server one (possibly with less data \[lacking data of monsters and players outside range of sight\]) and a remote server (has all data).
2. The users uses the input peripherals to control the game (e.g. mouse & keyboard) and the local client software translates user input into game "command" objects (e.g. run forward and shoot).
3. The clients sends these command objects serialized to the local and remote servers.
4. Both servers deserialize them and compute the results of the player's actions.
5. The local server's model (game data) is used for all rendering purposes.
6. The remote server updates the local server frequently with the true global state of all objects and creatures exposed to the player's senses (line of sight / hearing / psychic).
7. The local server knows how to smoothly and quickly interpolate to the new updated state.
> 0 votes

---
Tags: movement, multiplayer, anti-cheat, movement-prediction
---


# Question
Title: Do resolution settings have any impact or give any advantage in online FPS games?
There is this crazy theory that has always bothered me. I am not after a technically but more theoretically (although technical knowledge is required to) answer;

Two friends are playing the same video game over the internet (say ... CS:GO). The only difference is that Bob is playing on a 640x480 but Mike on 1900x1600.

Does the different resolution give any of them any advantage?

# Answer
> 7 votes
The resolution *should not* affect computation of simulation logic such as "where your bullet hit." Any reasonable game will divorce such simulation data from the final render resolution of the screen. That means the main thing you're talking about with respect to resolution is what the player sees.

---

If *all other things are equal*, then a lower resolution *might* give a player a disadvantage.

A higher resolution render will be able to transmit more fine detail for objects further away. What may be reduced to 4x4 pixel smudge in the distance on a 640x480 display may be 9x9 pixels on a higher-resolution one, which may be enough additional information to convey a better sense of the color of the object which in turn may be enough to convey to the player whether the object is a friend, foe, or irrelevant.

Depending on the nature of the game, however, this may not matter; the loss of fidelity in distance rendering may only impact objects so far away that they are beyond a reasonable player's concern anyway (their weapons cannot reach them, and/or the object in question could close to a relevant range in a reasonable period of time, et cetera).

This advantage is not likely to introduce any sort of statistical significance in the win/loss rate of players, although the number of real-world factors that complicate actually testing this hypothesis are many, and consequential I doubt any real evidence exists.

---

In practice, lots of factors will be altered by a change in resolution (so all things are *not* equal). For example, it takes more processing power to render more pixels, and this can result in a decreased responsiveness to user input, conveying an advantage to the player with a lower resolution (and thus a higher responsiveness). The factors so impacted will vary depending on the specifics of the implementation of the game in question, and are far too broad to enumerate completely here.

Beyond anything else, though, I suspect players who opt to run at lower resolutions or with lower graphical settings to convey an advantage to themselves do it either because it does give them a clear boost to their FPS *or* because they *feel like* it does. It's important not to overlook the placebo effect, the fact that if a player *thinks* they have an advantage they may play better regardless of whether or not they *actually* have one (the opposite is also true).

Perhaps to reinforce this point, most players don't seem to really understand what "FPS" is measuring (and specifically, how it's a non-linear measurement) and will bend over backwards to push 5 FPS on to a game running at 500, not realizing how small of fraction of time that is. They nonetheless may assert that they perform much better at 505 FPS than 500, which is almost certainly attributed to the placebo effect.

# Answer
> 0 votes
**Pros**

1. Higher resolution should give the player more visual information about the game world. Everything will be clearer and more sharply defined. This should confer an advantage in overall situational awareness, which in an FPS is important.
2. There should be no effect on game state as the game engine does not compute the position of objects and actors based on screen resolution but on resolution independent internal map co-ordinates or something along those lines.

**Cons**

1. The higher the resolution, the lower the frame rate as the hardware has to do more work to render each frame and it has a finite processing capacity. Frame rates lower than around 20 frames per second are too slow for games where there is a lot of action and the camera (point of view) is changing a lot as movement of objects in the field of view will become less noticable.

This one requires a little more explanation. The human visual system is quite good at identifying and tracking moving objects (whether they be prey, predator or environmental hazard), and less good at identifying static objects (or in our case, objects whose movement is rendered with low fidelity due to reduced framerate).

In an FPS, much of the game play revolves around rapidly identifying and assessing potential targets and threats and forumlating a suitable response (i.e. "twitch" gaming). Strategies tend to be more of a secondary layer, but the twitch is more important.

For slower paces games such an RPGs a framerate a low as 15 FPS may be acceptable, but anything below 10 FPS is very noticeable and rapidly becomes a slideshow.

**TL;DR**

You must strike a balance between high detail (higher resolution) and smooth action (higher framerate).

---
Tags: opengl, collision-detection, graphics, resolution, online
---


# Question
Title: Is it more efficient to transform vertices on the CPU or the GPU?
Working on optimizing the rendering core of my game engine and I have a couple of questions.

Is it more efficient to transform vertices to world space on the CPU before you send then stream to the GPU, or is it better to do this on the GPU? If done on the GPU this means I have to send the world matrix to the GPU for every different mesh however the GPU is highly optimized to deal with these calculations. It seems to me that doing it on the CPU would save some time, however, because I can transform the vertices and send over world positions all at one time.

# Answer
> 7 votes
In short - it is better to do the transformation on the GPU.

Firstly, the GPU is designed to support huge amounts of parallelisation. Your CPU on the other hand is not nearly as capable. The NVIDIA GTX 980, for example, has 2048 CUDA cores to process those vertices with in comparison to the 2-16 threads/cores a processor might support.

So from a number crunching point of view alone, the GPU is going to be better.

However, there is a far more obvious reason to do this on the GPU. While passing data data across the bus to the GPU might be expensive, it's not so expensive that passing a world, view (worldview) and projection matrix for every mesh is going to be a concern. However, passing all meshes every frame will be, and that's what you need to do if you process the vertices CPU-side.

In the normal pipeline you generate a vertex/index buffer, pass it to the GPU and render. At this point the GPU has stored the data in it's own internal memory. You then only update when something in that mesh changes. Usually this is only for dynamic buffers, such as might be used for a particle or sprite batching system. Most objects should be in static buffers which are only passed once - when the object is loaded for the first time.

If you are then manipulating that mesh each frame to change it's position then you are saving on passing the matrix by working CPU-side but now have to re-send all of the vertex data instead.

If your object is static and so will always use the same transform matrix you still get no saving by doing the transform CPU-side as you still probably have a moving camera. You will, in a normal render pipeline, eventually need the vertices in camera space so you need to perform this transformation as well and quite often people combine the world matrix with the view matrix so there's a single object to camera space transform matrix - often called the worldview matrix.

**Note on Geometry Batches**

One of the only occasions I can think of where you would want to perform this transformation CPU-side is when batching multiple meshes into a single buffer as might be done for static geometry (that shares materials), particles or sprites.

In this situation what you would really be doing, however, is translating the vertices into a common space for the buffer. Having one local reference space for each buffer means no extra vertex data is required to determine how to later translate that vertex to screen-space.

In other words, if you batched two buildings into a single buffer but didn't translate the vertex positions to a common space you would have to pass two world matrices and flag each vertex to determine which to use on each vertex. This can actually be achieved by using two separate index buffers (one for each building) and rendering in two draw calls with different world matrices but with the same vertex buffer in place.

Usually the common space is simply world-space, but could equally be camera space or some other local space if that was convenient for some reason.

Even in this case, however, you probably do this as little as possible and perform the translation to camera-space, then screen-space, using the GPU each frame.

---
Tags: c++, directx, transformation
---


title: Mesh Generation In Code

text:
# Question
Title: Mesh Generation In Code
My camera looks like this:

I am trying to add 2D polygons to the screen based on the percentage that they take up of a 1920x1080 pixel canvas. Therefore, I calculate this and then use Camera.ViewportToWorldPoint() to determine the world point for the mesh vertices. Below you can see how I declare vertices and uvs (I am confident my triangles are correct) for the polygon.

```
foreach (var point in poly.path)
    {
        uv.Add(new Vector2((float)(point.X - envelope.left) / (envelope.right - envelope.left), (float)(point.Y - envelope.bottom) / (envelope.top - envelope.bottom)));
    }

```

I assume this is the correct way to calculate the uvs since they are basically the percentage that vertices lie within the bounds of the polygon's bounding envelope.

Here is what I am not so sure on. When I set the vertices like so (assume temp is the array of vertices used):

```
        var temp = new List<Vector3>();
    var envelope = GetEnvelope();
    foreach (var point in path)
    {
        var vect = new Vector3((float)(point.X - envelope.left) / (envelope.right - envelope.left),
            (float)(point.Y - envelope.bottom) / (envelope.top - envelope.bottom), 1.0f);

        temp.Add(camera.ViewportToWorldPoint(vect));
    }
    return temp.ToArray();

```

everything works and the polygon is displayed to my screen except it scales so that the polygon draws as though the viewport is the entire envelope. I expect this, however it is not the functionality I want. So instead I try and declare vertices like so in order to have the polygon displayed in its correct relative position on the screen:

```
var temp = new List<Vector3>();
    foreach (var point in path)
    {
        var vect = new Vector3((float)point.X/1920,
            (float)point.Y/1080, 1.0f);

        temp.Add(camera.ViewportToWorldPoint(vect));
    }
    return temp.ToArray();

```

however when I set the vertices this way, I no longer see the meshes being rendered. My goal with changing the code to this is to have the polygons be their true size on the screen as they are on the 1920x1080 canvas rather than being skewed as they are in the code that I said was working. Am I misunderstanding how vertices and uvs relate?

Thank for any help!

# Answer
> 0 votes
My meshes were being generated correctly. However they were not rendering to the camera. I had to change the mesh's scale's z value to any value less than 0f for it to render. I am closing this question and opening another to figure out why exactly this is.

---
Tags: unity, 2d, projection, mesh
---