# Question
Title: Is it possible to retrieve shader function names associated with a technique pass using the DirectX Effect API?
For example, given the pass

```
pass p0
{
    SetVertexShader(CompileShader(vs_4_0, VSFunction()))
    SetPixelShader(CompileShader(ps_4_0, PSFunction()))
}

```

Ss it possible to retrieve the names VSFunction and PSFunction? It doesn't look like any of the associated shader descriptors actually contain the name of the entry point.

# Answer
When an HLSL effect is compiled, the entry point names don't show up anywhere in the bytecode (you can check it yourself using fxc.exe and a hex editor). Since the bytecode is the input to the Effect API, I don't believe there's any way to extract the entry point names.

The entry point names do appear in the debug information (which is included in the bytecode if you ask for it with a compiler flag). If the shader was compiled with debug information, it can be extracted using D3DGetDebugInfo, but as far as I know, the format of this information is undocumented.
> 1 votes

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


# Question
Title: How to generate texture coordinates for a rectangle?
I've got a function which generates geometry data for a rectangle. So far I've got the vertex, indices and the normals nailed, but I have no idea how to generate the texture coordinates - so far I've only used textures with imported 3d models, but now I want to generate my own rectangle on the fly and so need to generate the texcoords aswell.

So how do I make the texcoords? I am not sure how the mapping works.

```
bool CreateRectangleData(const float sizeX, const float sizeY, const float sizeZ, std::vector<float>& vertexData, std::vector<float>& normalData, std::vector<float>& texcoordData, std::vector<uint32_t>& indiceData)
{
    if (sizeX <= 0 || sizeY <= 0 || sizeZ <= 0)
        return false;

    const float X = sizeX / 2.0f;
    const float Y = sizeY / 2.0f;
    const float Z = sizeZ / 2.0f;

    float cubeVertices[] = {-X, -Y, -Z, -X, -Y, Z, X, -Y, Z,
                            X, -Y, -Z, -X, Y, -Z, -X, Y, Z,
                            X, Y, Z, X, Y, -Z, -X, -Y, -Z,
                            -X, Y, -Z, X, Y, -Z, X, -Y, -Z,
                            -X, -Y, Z, -X, Y, Z, X, Y, Z,
                            X, -Y, Z, -X, -Y, -Z, -X, -Y, Z,
                            -X, Y, Z, -X, Y, -Z, X, -Y, -Z,
                            X, -Y, Z, X, Y, Z, X, Y, -Z};

    float cubeNormals[] = {0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f,
                           0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
                           0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f,
                           0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f,
                           0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
                           0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
                           -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
                           1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f};

    float cubeTexCoords[] = {};  // ???

    uint32_t cubeIndices[] = {0, 2, 1, 0, 3, 2, 4, 5, 6,
                              4, 6, 7, 8, 9, 10, 8, 10, 11,
                              12, 15, 14, 12, 14, 13, 16, 17, 18,
                              16, 18, 19, 20, 23, 22, 20, 22, 21};

    vertexData.insert(vertexData.begin(), cubeVertices, cubeVertices + (sizeof(cubeVertices) / sizeof(float)));
    normalData.insert(normalData.begin(), cubeNormals, cubeNormals + (sizeof(cubeNormals) / sizeof(float)));
    texcoordData.insert(texcoordData.begin(), cubeTexCoords, cubeTexCoords + (sizeof(cubeTexCoords) / sizeof(float)));
    indiceData.insert(indiceData.begin(), cubeIndices, cubeIndices + (sizeof(cubeIndices) / sizeof(uint32_t)));

    return true;
}

```

Thanks

# Answer
Texture coordinates always start at 0 and end at 1. Imagine stretching a cloth over the extremities of the object you are texture mapping.

For example (assuming the x-axis increments right and the y-axis increments down), for a square the top left UV coordinate would always be (0, 0) and the top right UV coordinate would always be (1, 0) regardless of the size of the square.

For a 3D model you can map textures however you like as long as there is a direct relationship between the texture image and the UV coordinates.

The simplest way to map a texture to a cuboid would be to map the texture to each face independently as opposed to an unwrapped model. So, each face would have the same texture coordinates.

In your supplied code all you would need to do is to create an array which matches your index list in a way that would ensure that the top-left of a face has UV coords (0, 0) and the bottom-right has UV coords (1, 1) when looking at the face straight on (assuming the coordinate system mentioned above).

The actual texture image can be a square or a rectangle.
> 2 votes

---
Tags: c++, opengl, 3d-meshes
---


# Question
Title: Implementing smooth 8 directional movement
I have my units that i move around my map with path finding. The units can move in 8 directions, currently i have the units moving around the map with a extremely basic check against the unit's current position vs. the next target destination in an array of Vector2s (the path). However, the movement is rather jagged and not very fluid.

Current code (I know its not very good, i did this just to test out the pathfinding really);

```
 if (Position.X < Path [CurrentPathPoint].X) {
     SpeedDir.X = 1;
 }
 if (Position.X > Path [CurrentPathPoint].X) {
     SpeedDir.X = -1;
 }
 if (Position.Y < Path [CurrentPathPoint].Y) {
     SpeedDir.Y = 1;
 }
 if (Position.Y > Path [CurrentPathPoint].Y) {
     SpeedDir.Y = -1;
 }

 Position += SpeedDir * Speed;

```

I should mention that im not looking for any sort of rotational movement, just smooth diagonal and directional movement. However, i'm at a lose on how i can achieve that... So any help greatly appreciated :)!

Edit: Smooth Transitioning between movements is what i'm looking for. Right now, the units sometimes (not sure how to describe but they "stutter" along), looks like they are shaking when moving. As to what i tried before, i had the position being updated directly in the If statements, that didn't give me any stuttering but did not seem like a good approach so i changed to the one above.

# Answer
**Implement acceleration.** Don't modify the velocity directly, let the acceleration change your velocity over time. This will make the movement appear more natural and smooth, because it's close to how things work in real life.

With the changes the pathfinding will change the acceleration value. In turn, the velocity will be adjusted smoothly from one vector to the next by changing over time.

You may want to also include some friction into the equation. This way, when you're going forward, then start applying force to go right, you won't forever continue to go forward too.

For stopping you can do a little bit of steering type behavior to come to a stop.

If you're not wanting "free movement" of the unit, this probably isn't the solution for you. It's going to be very difficult to make orthogonal/diagonal-only movement look natural and smooth between transitions because nothing in the real world moves like that.
> 0 votes

---
Tags: xna, c#, movement
---


# Question
Title: What is actually loaded during a game's loading screen?
I am at the stage of my game where I have to develop the loading screen. It's actually already there, but I don't know exactly what it should be loading while it's presented.

Why would I have a loading scene instead of just going directly to my game scene? I don't even know what else to load besides the textures with the texture `SpriteCache`.

Am I doing the correct content loading? I missing something to load during that loading scene?

# Answer
> 11 votes
Typically, the loading screen is presented so the user sees some kind of activity or indication that the game has not stalled while the game loads all the necessary data to play the level (or whatever), especially when loading the data might take a long time.

If your game can *already* go directly to the gameplay without an unpleasantly long delay, then you don't *need* to implement a loading screen.

# Answer
> 0 votes
I don't have experience in cocos-2d but in general during loading screen the game would load various assets. For example the textures, background music, sound effects files, video files if you have any or reading in any map/game data files. Some game may want to preconstruct some of the levels because they take a lot of time(e.g. randomly generated map) so once the player get into the game they don't need to wait for any loading screens anymore.

Preloading resources means that you can directly use those resources later in the game without the user waiting for them to be read in which improves the user experience. However you don't want to load every single assets you might need in the future. First is because you don't want to occupied a lot of memories for things that you might not need later. If you use too much memory the system may kill you off or it will actually affects the performance of the game due to paging. Second is startup time is one of the factors that affects user experience and generally player don't want to wait too long for starting up the game(they might just want to have a game when waiting for someone for a few minutes). In situation like this smoothing out the loading time by deferring loading or background loading may actually be a better idea.

In summary, deciding what to load during the loading screen depends on the specific game you are making. Keep tuning it until you satisfy with it :)

# Answer
> 0 votes
There's an implied question here: "When do I need to use a loading screen, and when can I do without?"

If your game is still small, you can probably let the player begin immediately with no delay. As your project grows, you might notice that the app "stalls" or hangs for a time before the game becomes responsive and the player can start playing.

If the delay before the game starts becomes noticeable, that's when you might need a loading screen. *Find out what is slowing down the start of your game and do that during loading*.

Of course, if you can keep everything fast enough that you never have a noticeable delay, so much the better - eliminate the loading screen entirely!

---
Tags: cocos2d-iphone
---


# Question
Title: How can I load a text file from Content?
I created a small Windows Phone game with XNA, but I have some trouble with loading a text file from Content. I added the text file to my Content project and marked the Build Action to "Content". The static text file should be loaded when the game starts, but I always get an exception in this line of the method:

```
if (File.Exists(filename))

```

> An exception of type 'System.MethodAccessException' occurred in mscorlib.ni.dll but was not handled in user code

If there is a handler for this exception, the program may be safely continued.

What is wrong? How can I load a text file from Content?

```
private const string filename = "Level1.txt";
public void LoadfromContent()
    {
        if (File.Exists(filename))
        {
            using (StreamReader reader = new StreamReader(File.OpenRead(filename)))
            {
                strs = reader.ReadLine().Split(';');
                game1.HowManyEnemies = int.Parse(strs[1]);
            }
        }
    }

```

# Answer
> 1 votes
The content pipeline project is for content to be *built* with the content pipeline.

If your file will not be processed by the content pipeline, it needs to go in your main game project. Then follow the instructions from the link Byte56 gave you. Basically set "Content" and "Copy if newer".

---

The exception you are getting, `MethodAccessException`, is because that API isn't available on WP7. Use Title Storage instead. To open your file, you can use:

```
TitleContainer.OpenStream(filename);

```

See the information on MSDN about Reading Game Data from Title Storage and Adding Game Data Files to Title Storage.

---
Tags: xna, c#, windows-phone-8
---


# Question
Title: Debugging multiplayer games without killing network thread?
How do I approach multiplayer games for debugging? When debugging locally - how can you prevent yourself from disconnecting? The debugger halts network activity.

# Answer
By far the most effective way I have found to handle this problem is to eliminate it entirely.

I should say, up front, that the techniques I'm talking about here require that your game is *really* well architectured. You need to be able to create multiple instances of the game, update the game without rendering anything, render to a specific viewport, plug in different network connection objects (a simulated network is ideal for this), and so on.

It also requires your game is reasonably fast. Being able to simulate at a few hundred frames per second *really* helps.

---

If you can manage that, you can do two very powerful things:

**First:** you can run multiple instances of the game in a single process, connect them together with a virtual (or actual) network, and test them all on a single screen. This is fantastic by itself - but comes in really handy when you can just hit "pause" in the debugger and the entire process, including every instance of the game, stops at once.

**Second:** If you really want to go all out, you can run an "offline" simulation of the game (again with multiple instances in the one process). You can use this to do powerful things like graph out the positions of objects over time to see if they're moving correctly.

This is cool on its own. But it becomes extremely powerful when debugging if you set it up so you can re-run that simulation on-demand (being a network game, it should be highly deterministic) and then have `Debugger.Break()` get called on a specific frame.

---

I've got a DevLog **video here** showing both techniques being used in development of my game, Stick Ninjas.

Here are some screenshots. First, multiple instances of the game in the one process. Check out the packets flying across the simulated network.

And, second, the game graphing out object positions over a short run with a specific set of inputs and network conditions. Both client and server states are graphed.

---

The origin for these techniques is something I came across, while researching, about how the networking for Quake was developed. (See this page for some details).

Basically the idea was that the engine takes *everything* as an input: actual user inputs, packets, even clock ticks. That way - all those inputs can be recorded and replayed through the engine at a later time (perhaps with a debugger attached, perhaps in a debug build, perhaps with a specific frame scheduled to cause `Debugger.Break()` to get called).

This is, itself, an excellent idea for debugging. Although, with the tools I've described above, I haven't yet found a need to fully implement recording and playback yet for my project.

---

Of course, all of these depend on your game being deterministic and behaving itself. You might find you need to use some of the techniques in this excellent article (that John McDonald already beat me to linking in the comments).

I really like the first technique: Basically set the game to pause if the network times-out. This is important - not so much because of your network thread - but because network clocks getting out of sync can be problematic.

But, also with these techniques, I'm yet to encounter a need to implement them in practice.

---

The last technique I should briefly mention is **plain ol' unit testing**. I'm not really huge on unit testing everything. But one thing you absolutely should unit test are your methods for reading and writing data into packets. These are methods that you need to rely on with 100% confidence. An error in one of these methods can be a nightmare to track down.

For good measure, I also have a few unit tests that set up an instance of my game world, push it across a virtual network, and make sure it comes out unscathed at the other end.
> 6 votes

# Answer
Here's a few options:

1. Debug by displaying debug information on screen, or to the debug console.
2. Use a network packet inspection tool like Wireshark.
3. Don't keep the game breakpointed in the debugger for too long - examine the state quickly, resume execution, and repeat. If need be you can also increase timeouts in debug builds.
4. Use UDP for everything. Because it's connectionless you don't have any timeouts imposed on you. Of course this also means there's more code to write because you don't get things like automatic retries for dropped packets.
> 1 votes

# Answer
Actual network threads are perfectly happy to be unused for long periods of time. If your debugging activity stops voluntary activity, and that upsets the server, you need to fix that problem at the server.

If the nature of your problems is real-time interaction in unexpected ways, then a certain Heisenberg effect is inevitable. You best bet is to instrument your application to keep communication history, and use the logs forensically.
> 1 votes

---
Tags: c#, visual-studio
---


# Question
Title: how to set image resource path for D3DXCreateTextureFromFileEx method?
I try to merge all the image resources to a folder called resource. So, set image path as "resource/" but my directX framework only works if I compile at VS 2010. If I run from the debug folder it cannot run.(I already copy all the image resources to debug folder)

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

```
string folder = "resource/";

void setTexture(LPDIRECT3DTEXTURE9& texture, string imgName, int imgWidth, int imgHeight, D3DCOLOR TransparentColorKey)
{
    string path;

    path = folder + imgName;

    //  Create texture.
    hr = D3DXCreateTextureFromFileEx(d3dDevice, path.c_str(), imgWidth, imgHeight,
        D3DX_DEFAULT, NULL, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED,
        D3DX_DEFAULT, D3DX_DEFAULT, TransparentColorKey, NULL, NULL, &texture);
}

```

# Answer
A simple way would be to configure your output directory for your project and then set your working directory to that folder.

1) Set your output directory. This folder holds your `.exes`, `.liks` and `.pdbs`. In this example I will output to a folder called Bin outside of my project directory.

2) As you are outputting to a folder for multiple configs, you will want to modify your target name so they can be distinguished between debug and release. In this example I have appended `_debug` to my Target Name for my Debug config and `_release` for my Release config so that when I build both configs there will be two sets of files for each config.

So now you will have a folder storing your exe outside of your project root.

3) Create your Resource folder in the same directory as your Bin and Project. The folder structure will look something along the lines of:

> ```
>  -- DirectX FrameWork
>     |-- Bin
>     |-- Project
>     |-- Resources
>
> ```

4) Set your working directory to your Bin folder.

Now as you can see, when you run from Visual Studio or the .exe they will both be using the same working directory, so the same relative file path can be used when referencing files. Doing this also helps to separate your code from your resources.
> 1 votes

# Answer
*There are multiple things that can cause this but maybe try this, if that doesn't work please provide us with more information about the project and deployment setup*

When running via Visual Studio the CWD (current working directory) is that of the project (by default) so the path to your files is "./resource/" while if you're running from the debug folder your CWD is that of the executable, so the path to the resources is "./../resource/".

You have to set up that your resources are copied to the output directory. You can do this in the solution explorer by selecting the resource and selecting "Copy To Output Directory"
> -1 votes

---
Tags: c++, directx, directx9, loading
---


# Question
Title: Stretching a texture over multiple faces
I have a grid of vertices that I'm using as the ground for my game in XNA. I have a effect file / shader which handles texturing and lighting. Right now I have it so the texture tiles across each face of the grid, but the texture i'm using is 4096x4096 and i'd like to have it completely stretched across all the faces of this grid instead of repeating itself over each face. How would I go about doing this?

Thanks

# Answer
> 1 votes
Assuming the following:

* (0,0) is the top-left coordinate.
* Each vertex in the grid is equidistant in x and y.

---

```
float u, v;
for( int Row(0); Row <= NumberOfRows; ++Row )
{
    for( int Col(0); Col <= NumberOfCols; ++Col)
    {
        u = Row / float(NumberOfRows);
        v = Col / float(NumberOfCols);

        // Store u and v
     }
}

```

This code creates UV coordinates with a constant increment from 0 to 1 in both x and y. This will allow you to map one square texture over the full grid. All you need to remember is that texture coordinates rely on the smallest extremity being equal to 0 and the largest extremity being equal to 1 of the object your mapping.

---
Tags: xna, textures
---


title: SpriteSheet in slick2d or lwjgl

text:
# Question
Title: SpriteSheet in slick2d or lwjgl
```
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

public class SpriteSheet {
    private String path;
    public final int SIZE;
    public int[] pixels;

public static SpriteSheet tiles = new SpriteSheet("/texture/spritesheet.png", 256);

public SpriteSheet(String path, int size) {
    this.path = path;
    this.SIZE = size;
    pixels = new int[SIZE * SIZE];
    load();
}

private void load() {
    try {
        BufferedImage image = ImageIO.read(SpriteSheet.class.getResource(path));
        int w = image.getWidth();
        int h = image.getHeight();
        image.getRGB(0, 0, w, h, pixels, 0, w);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

```

So I'm trying to load a SpriteSheet either using slick2d or lwjgl. Was wondering is this faster, than the method above. Also, how do you actually do a spritesheet class for lwjgl.

I'm just confused how you use Sprites in Slick2d. It looks like I need to create an image class and then have SpriteSheet class extend the image class.

http://slick.cokeandcode.com/javadoc/org/newdawn/slick/Image.html

# Answer
> 2 votes
> Was wondering is this faster, than the method above.

It would have been better for you to post the SpriteSheet.java class from slick2D so we could compare them. I couldn't find the actual code to compare sorry. However, I don't believe it would really matter because you are essentially only loading the spritesheet once :)

> I'm just confused how you use Sprites in Slick2d. It looks like I need to create an image class and then have SpriteSheet class extend the image class.

Check out some tutorials on loading images with slick2D Slick2D Game Tutorial

As for your last statement. It seems as though you would like to create your own sprite sheet class? If so, Then you can use the same method I use to retrieve my sprites from my sprite sheet. It's simple and effective.

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

 import javax.imageio.ImageIO;

 public class SpriteSheet {

//Integers
public static int TILE_SIZE = 32;

//Strings
private static String path = "res/SpriteSheet.png";

//Images
private static BufferedImage spriteSheet;

public static BufferedImage getSprite(int xGrid, int yGrid) {
    if (spriteSheet == null) {
        try {
            spriteSheet = ImageIO.read(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return spriteSheet.getSubimage(xGrid * TILE_SIZE, yGrid * TILE_SIZE, TILE_SIZE, TILE_SIZE);
  }
}

```

Above is my SpriteSheet.java class. In this class I have 3 Variables. \- an int for the size of my tiles on the sprite sheet image. \- a String for the path of my sprite sheet image. \- a BufferedImage which will hold my sprite sheet image.

Luckily for us BufferedImage has a getSubImage(x, y, width, height). We use this to retrieve our sprite from the sprite sheet.

The way we retrieve our intended sprite is by accessing the SpriteSheet class statically with:

```
 SpriteSheet.getSprite(0, 0);

```

This returns the sprite at the top left corner which is xGrid co-ordinate 0 and yGrid co-ordinate 0.

I hope you get something from this. If not then I just wasted 20 minutes of my life lol.

enjoy

# Answer
> 0 votes
Slick2D is made to be easy to use. As far as I know the constructor of `Spritesheet` allows for a string literal so you should be able to just say:

`Spritesheet sheet = new Spritesheet("path/to/spritesheet.whatever");`

All a spritesheet is anyway is an image divided into smaller sub images. You can load the seperate images from the spritesheet by using

`Image sprite = sheet.getSprite( whateverXposition, whateverYposition);`

and then

`sprite.draw();`

As for the decision between lwjgl or slick2d that doesn't really make sense. lwjgl is a wrapper for OpenGL, which is nothing more than an API for communicating with your graphics card. If you're looking to animate a sprite slick2d's solution is going to be much easier for you I think than lwjgl, though exploration is always nice.

Something like:

```
Spritesheet s = new Spritesheet("something.png");
while( animateSprite == true )
{
    Image currentSprite = s.getSprite( currentX, currentY );
    currentSprite.draw();
    ...blah blah exit loop statements and logic...
}

```

You can loop across the values from the spritesheet and draw the image.

---
Tags: slick
---


# Question
Title: What is a good balance between client and server actions?
I'm working on a voxel-based game right now which will have a lot of events, like clicking a block or object.

Say I want to open an interface when I click a certain block. Should I handle this on the client, or send a packet to the server with the action and it's details such as what the ID of the block is, its position et cetera, and then send a packet back to the client with the action `OpenInterface` with the interface ID?

# Answer
> 0 votes
It's quite common for the server to handle bits like sending messages to open an interface. There may be extensive scripts or other logic you want to run when clicking a block or interacting with inventory, for example, which you don't want to have to stream to clients (maybe the script has a secret or something you don't even want them to see). You can also make the argument that you don't want clients being asked to run arbitrary code unless you have a very tightly sandboxed script engine.

The actual GUI code itself needs to be on the client, of course, but you can definitely make all interaction require the server.

It's also of course common to just have the client handle it. It's definitely easier in some cases, especially if you want to make the game feel smooth.

Which way is right is 100% dependent on your game and what features you need. If in doubt, just go with whichever seems easier to you.

# Answer
> 0 votes
GUI/interface related stuff should be taken care of client-side, the server doesn't need to know if you're opening a dialog screen.

Send the server information that changes the game state: if your menu screen has a "delete voxel button", send a packet telling the server `user X is trying to delete voxel Y`, not `user X has pressed "delete voxel button"`.

In your example, clicking on a certain block could ask the server for information about the block (block type, position, etc...), then when that information is received, the client opens the interface, and if the player does something that changes the "game state" through the interface (for example, changing the block type, position, color, etc...) you send *that* action to the server, not the GUI-related action.

---
Tags: networking
---


# Question
Title: Wrong intersection: Bounding Sphere and Ray
I've got a huge problem with `BoundingSphere`s and `Ray`s in XNA and I really don't know how to solve it.

The problem:

```
foreach (BoundingSphere s1 in GetCollisionHullBoundingSpheres())
   if (ray.Intersects(s1) != null)
   {
      System.Console.WriteLine("Sphere: " + s1.Center + " Radius: " + s1.Radius);
      System.Console.WriteLine("Ray: " + ray.Position + " Direction: " + ray.Direction);
      System.Console.WriteLine("Ray: " + ray.Intersects(s1).Value + "\n");
      return true;
   }

```

The collision hull bounding spheres are the spheres from the mesh and the ray is calculated by using the `playerposition` and the vector (0,-5,0) as the direction.

Here is the output:

```
Sphere: {X:-16,52211 Y:-3,34731 Z:-15,66445} Radius: 5,077909
Ray: {X:75,29767 Y:29,15445 Z:-45,73476} Direction: {X:0 Y:-5 Z:0}
Ray: 35,84612

```

I can't understand how that ray can intersect with the sphere.

# Answer
> 2 votes
Xna's `Ray.Intersect()` tests that utilize the Ray's direction assumes that the direction vector is unit length.

If you normalize `ray.Direction` before running the test you will find it will not intersect.

the documentation supports the direction vector being unit length.: http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.ray\_members.aspx Unit length vectors have a magnitude of 1, your 0,-5,0 has a magnitude of 5. A by product of the math behind the intersection test is that the sphere's radius is scaled by the magnitude of the direction vector... so it needs to be kept at 1

---
Tags: xna, c#, intersection, sphere
---


title: How do I simulate a swinging pendulum?

text:
# Question
Title: How do I simulate a swinging pendulum?
I want to simulate a rope with a weight attached, swinging back and forth like a pendulum. Any actual physics is overkill; it's just endlessly repeating the same motion.

JQuery has a the "swing" ease similar to what I'm looking for. How does it work?

I was thinking of rotating from one angle to another with `Math.easeOutExpo`, but real pendulums ease differently...

# Answer
> 10 votes
Well, you'll have to use a little bit of physics, but you don't need to *simulate* any physics. There are formulas for pendulum motion you can easily use to set the rotation of your pendulum. For small swings, the motion can be approximated with simple harmonic motion.

The angular displacement at a specific time can be approximated with:

This is most accurate for a small maximum θ, but will likely be accurate enough for your purposes. Create a function that takes the current time, and outputs the angle for which your pendulum should be rotated, and rotate your sprite by that amount.

# Answer
> 4 votes
Here is a no-trig calculation, derived from straight-forward Grade 11 Trig and Physics. It assumes that the origin is the lowest point of the pendulum bob's suspension, that L is the length of the pendulum, and that the normal graphics convention of y increasing down, and x increasing to the right is adopted:

**Update:** I messed up yAcceleration initially; this is easier.
**Update #2**: Added explicit time control, and added units of measure.

```
const float gravity = 9.8;     // units of metres/sec/sec
const float deltaT  = 0.001;   // equals 0.001 sec or 1 millisecond

var xVelocity = 0.010;         // units metres/sec equals 10 cm/sec
var x = 0.0;                   // units metres
var y = 0.0;                   // units metres

while (true) {
  var xAcceleration = -gravity * (x/L) * (L-y)/L;

  x += (xVelocity + (xAcceleration/2 * deltaT)) * deltaT;
  y  = Math.SQRT(L*L - x*x) - L;

  xVelocity += xAcceleration * deltaT;
}

```

---
Tags: cocos2d-iphone, rotation, easing
---


title: Showing "Please buy" screen to pirates

text:
# Question
Title: Showing "Please buy" screen to pirates
*I recently saw this and this, and that got me thinking*

When publishing a commercial game without DRM, would it be a good idea to upload a slightly modified copy of the game that shows a screen like this at startup to, say, The Pirate Bay:

> Hello pirate! Looks like you downloaded this game from The Pirate Bay! That's okay, but: Making a game costs time and money. If you like the game, please buy it so we can continue to update this game with new content! You buy it for only $xx.xx at www.example.com!
>
> In the meantime: Have fun!
>
> *Press Enter to continue*

And then continues to the title screen and from there is identical to a legal copy.

The point is that it will probably (very, very, VERY high chance that it will) be uploaded sooner or later anyway, so this may decrease the harm.

Would that be a good idea?

# Answer
> 14 votes
If it's a good idea or not is up to you. And the success of the strategy depends on what your actual goal is.

No Time to Explain did this *way back* in 2011. They uploaded a special version of the game to Pirate Bay that had all the characters wearing pirate hats.

> “We thought it’d be funny to leak a pirate version ourselves which is literally all about pirates and pirate hats,” Alex told TorrentFreak. “I mean, some people are going to torrent it either way, we might as well make something funny out of it.”

It's unknown if the strategy of creating a special version just for pirates gets more pirates to buy the game instead of pirate it. However, it's been shown in the past to improve the media coverage of the game, potentially drawing more legitimate users. The developers of No Time to Explain said:

> “We saw very positive WTF REALLY feedback from users, and saw reactions that people bought it simply because they liked the joke. So we don’t see it hurting sales in any way,” Alex said.

However, it's unclear if this strategy only works for games that were already popular, or if a fairly unknown game could be boosted into the spotlight with this method. Further, this strategy likely has limited uses. It's only been successful because it's somewhat unique and interesting. If every game does this, it's not as interesting and news sites stop reporting on it.

You could opt for a more subtle approach of just including a message for *everyone*, telling them you've worked hard on the game and you appreciate their purchase of the game. Something like what S.P.A.Z. did:

There are a number of approaches to marketing and getting your game more widely known. There isn't any evidence (as far as I know) of any strategies that effectively convert pirates into paying customers. **So, if your intention of doing this is for marketing, then sure, it's worth a try, but if it's solely an attempt to convert pirates, you're not likely to have much success.**

---
Tags: legal, publishing, commercial
---


# Question
Title: How can I show xna graphics content in a control on a form in xna?
I was able to create a form in xna using "Add Windows Form", named "Form1" then adding:

```
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());

```

How can I add graphics to some control, perhaps a picturebox, on Form1 that could potentially show my game as in a level editor?

Thanks.

# Answer
> 2 votes
Microsoft has an official tutorial on this: http://xbox.create.msdn.com/en-US/education/catalog/sample/winforms\_series\_1

> "or maybe you're writing a level editor and want to place Windows user interface controls around the 3D drawing surface"

Basically, you embed your game as a control in a winform.

---
Tags: xna, level-design, windows-forms
---


title: Player position triggering teleports

text:
# Question
Title: Player position triggering teleports
I'm developing a Minecraft plugin (bukkit) in which a server admin can create 'portals' - a small region that will teleport any players who enter it. I have the teleportation sorted and I know how I could define areas that the player's position could be tested against.

This would involve an `ArrayList` containing the zones and then hooking the `PlayerMoveEvent` so that the `ArrayList` is searched each time for a matching portal region.

Although this method would work, I doubt that it would be very efficient when 100+ players are all moving around at the same time. Is there a better way of checking a player position against a set of 'zones' / regions?

# Answer
There is an open source plugin called VoxelPort that does this, see here: https://github.com/TVPT/VoxelPort/tree/master/src/main/java/com/thevoxelbox/voxelport

It uses Zones as you suggested, and each "Port" calculates whether a player is inside the region & if they are holding the appropriate key. To prevent tons of lag, it has 2 types of ports. Instant ports, and Delayed ports. The delayed ones are used more on our server because they only check if a player is in a zone every so often(Based on set-time). On the server we're on (VoxelBox) it's about every 5 seconds or so.

As for player move events, it stores the data from the event in a HashMap instead of checking every move event. Then a thread "ticks" for when to check players.
> 1 votes

# Answer
You should use the bukkit forums and you might get more replies, but anyway. Im a bukkit plugin dev myself, although I haven't been on bukkit a while. If you want to find a useful method you should look at the javadoc.I had a quick skim through and it seems that would be the only way, unless you changed the behaviour of another block to act as a proximity detector.
> 0 votes

---
Tags: java, minecraft-modding, bukkit
---


# Question
Title: how to do turn based board game movement on a 2d map
I don't know if what I programmed worth anything, I've never programmed something like that, I just need to handle a player movement on a map, I thought a tile map will work, but I don't know anymore.

**Description of logic of end result**

I have a board game I want to program, the map has 3 levels.

Each level is a square (outer square, inner, and middle square).

On a player move phase (I have phases and turns implemented).

He rolls a dice (random func from 1 to 6 implemented).

And he can move forward or backwards how much he rolled (let's say he rolled 3).

**End description of logic of end result**

Below here is what I tried to do.

I can get the player map pos, the map is a 2d array (like a tilemap), I've also created a "location" array to represent each location. (bellow is an example not actual code).

```
var map = [
             [0,1,3,5]
            ,[11,31,4,5,]
            ,[12,31,4,5,]
          ];

var locations = [];
locations[0]={name:"trailer park",desc:"bla",pos_on_map:[0,0]};
locations[1]={name:"mall",desc:"bla",pos_on_map:[1,0]};

```

Say I created a move method on the game handle object how do I let the player select to move 3 squares backwards or forward(he can select to move 1 or 2 if he wants). and what if it means going from 0 to 11 or 12 or from 11 to 3.

How do I loop through such options? It's from one array "row" to another on the 2d array.

Now I have:

```
if(game_manger.turn_phase >2){game_manger.manu="game_manu"}
//loop trogh all input options output
var loop_tims = game_manger.move_amount;
var c_player = game_manger_p.current_player();
var p_loc = c_player.loc;
var c_p_level = c_player.map_level;
var board_len = my_map[c_p_level].length ;

for(var i =0; i < loop_tims;i++)
{

    if(i < board_len)//only existing locations
    {

        var loc = i+1 + p_loc;//map location num
        jout(loc+")locatio name");
    }
}

```

It's not very well implemented... not even the map data part, I don't think a 2d array like this will work I need something to separate it to levels but still let me output it like a tile map.

Also there is no info anywhere on the web about how to program a board game or a turn based game.

# Answer
> 1 votes
The problem you have is pretty fundamental and open ended, there isn't *one* solution to your problem. I'm trying to understand the issue here. You have two arrays: The map array is the 2D array which describes your map and the other `locations` just holds where significant locations are.

Though maybe some psuedo code could help you:

```
1. Get the players current position
2. Get the status of the position the player wishes to move to
3. Look at the contents of the position to make sure it's ok
4. If the position is OK to move too set the value of the array
   at the given position to indicate the player is there
5. Remove the player status from his current position in the array
6. Update the current position of the player with the moved to position

```

Does this help?

# Answer
> 0 votes
**solved:**

didnt test it for bugs but its based on Manhattan distance algoritem thing.

as it seems my location chose menu was in an intimate (information) relationship with player class so i moved the method and they got it on too so i had to separate this method it was too unrefractiony unorganised and not very useful. so location manu will only call sometimes.

what dose it do is take the distance of movement and chack its maximum and minmum movment both left and right and up and down and then loops on all of those values,checks if posible pos |x-i+y-j| is not bigger then distance :

x=500 y=500 dist=5,i=495 j=495,|x:500-i:495|+|y:500-j:495|=10\<5=false (you cant move 5 left and 5 up its a little bigger then 5 the distance).

but if true put it in can\_move\_array ,and after you fill it do the type of action,output to show the player input to verify he chose a right move action. afterwerds ill add more condition like type of location because my board has levels,and i dont want players moving into a next level square.

someone should write a tut about it not enough resources for that kind of fun games.

maybe write an engine...

```
player_p.move_info = function(distanse,type,map,y_input)
 {
var can_move_array = [];
var move_amount = distanse;//game_manger.move_amount;
var x = this.loc[0];
var y = this.loc[1];

//map level and length
var p_level = this.map_level;
var board_len = my_map[p_level].length ;

//move from, its curent position less move amount so you can move backwords too.
var min_x= x - move_amount;
var min_y= y - move_amount;

//maximum amount can move
var max_x = x + move_amount;
var max_y = y + move_amount;
//for x
for(i = min_x; i<=max_x; i++ )
{
    //for y
    for(j = min_y; j<=max_x; j++ )
    {
         if (Math.abs(x-i) + Math.abs(y-j) <= distance)
         {
            can_move_array.push() ={x:i,y:j, location:map[i][j]};//overkill...but i need the map location num and the map cordenates.
         }

    }
}

if(type == "output")
{
    this.move_output(can_move_array);//loops can move an hilights it
    return;
}
if(type == "input")
{
    this.move_input(can_move_array,y_input);//looks stupid but chacks if input is in  can move array.if not ...return
    return;
}

```

its only conceptual and ill need to fix it .but you can use the general idea.if not leave a comment ill help.

---
Tags: tilemap, turn-based, strategy
---


title: Difference between Unity Pro licenses?

text:
# Question
Title: Difference between Unity Pro licenses?
What is the difference between the various Unity Pro licenses? What does Android or iOS pro give me that Unity Pro doesn't? And what is the point of getting Unity Pro if I only care about mobile platforms, besides Win 8/WP 8 which Pro now comes with?

# Answer
> 1 votes
Unity has a full comparison chart on their site. The differences are too extensive to list here.

iOS and Android are different flavors of Pro. Android gives you the ability to publish to Android. iOS gives you the ability to publish to iOS. They can be combined for the ability to publish to both.

You must get Unity Pro in order to have the additions of Android or iOS. They are "expansions" of Unity Pro.

So, if you only care about mobile, you still have to get Unity Pro in order to be able to add the iOS and Android options.

---
Tags: android, unity, ios
---


title: Limit the number of draw calls

text:
# Question
Title: Limit the number of draw calls
I know where the error lies in my code at this point, and I know what I need to do to fix it, I just don't know how. My problem comes with the 120,000+ draw calls I get each frame. This is caused by my main method which draws each cube in a list cubes.

```
     public void DrawMap(GameTime gameTime)
    {
        foreach (Cube block in cube.cubes)
        {
            Matrix translate = Matrix.CreateTranslation(block.cubePosition);
               cube.Draw(effect);

        }
    }

```

Now obviously there is more than just this in the method, but these are the two lines I'm focused on. I need the translate matrix to place cubes where they're supposed to go, and the cube.Draw for actually drawing the cube. My goal was to create a chunk of cubes to limit the number of draw calls, but what I have isn't accomplishing that.

What I was thinking is that I need to just use the cube.Draw method. So I tried this

```
   public void Draw(BasicEffect effect)
    {
        device.SetVertexBuffer(vertexBuffer);
        device.Indices = indexBuffer;

        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            no++;
            pass.Apply();

            device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 8, 0, 12);
        }
    }

```

There was more to it than that, but you get the idea. This only created one cube, although the index and vertex buffers have more than one cubes indices and vertices stored in it as illustrated by the code below seen in many of my past questions.

```
  for (x = 0; x < 50; x++)
        {
            for (z = 0; z < 50; z++)
            {
                for (y = 0; y <= map[x, z]; y++)
                {
                    SetUpIndices();
                    SetUpVertices();
                    cubes.Add(new Cube(device, new Vector3(x, map[x, z] - y, z), grass));
                }
            }
        }

        vertexBuffer = new VertexBuffer(device, typeof(VertexPositionTexture), vertices.Count, BufferUsage.WriteOnly);
        vertexBuffer.SetData<VertexPositionTexture>(vertices.ToArray());

        indexBuffer = new IndexBuffer(device, typeof(short), indices.Count, BufferUsage.WriteOnly);
        indexBuffer.SetData(indices.ToArray());

```

What I learned through using a breakpoint is that there were actually 2500 cubes being drawn in one place. I had only about 150 draw calls a frame at that time, which is a lot better than what I did have.

Is there something I can change that sets the vertices and indices to the position of my cube in order to draw the cubes in the right place?

```
    private void SetUpVertices()
    {
        //front left bottom corner ok
        vertices.Add(new VertexPositionTexture(new Vector3(0, 0, 0), new Vector2(1, 0)));
        //front left upper corner
        vertices.Add(new VertexPositionTexture(new Vector3(0, 1, 0), new Vector2(1, 1)));
        //front right upper corner ok
        vertices.Add(new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(0, 1)));
        //front lower right corner
        vertices.Add(new VertexPositionTexture(new Vector3(1, 0, 0), new Vector2(0, 0)));
        //back left lower corner ok
        vertices.Add(new VertexPositionTexture(new Vector3(0, 0, -1), new Vector2(0, 1)));
        //back left upper corner
        vertices.Add(new VertexPositionTexture(new Vector3(0, 1, -1), new Vector2(1, 1)));
        //back right upper corner ok
        vertices.Add(new VertexPositionTexture(new Vector3(1, 1, -1), new Vector2(1, 0)));
        //back right lower corner
        vertices.Add(new VertexPositionTexture(new Vector3(1, 0, -1), new Vector2(0, 0)));
    }

    private void SetUpIndices()
    {
        indices.Add(0);
        indices.Add(2);
        indices.Add(3);

        indices.Add(0);
        indices.Add(1);
        indices.Add(2);

        indices.Add(1);
        indices.Add(5);
        indices.Add(6);

        indices.Add(1);
        indices.Add(6);
        indices.Add(2);

        indices.Add(2);
        indices.Add(6);
        indices.Add(7);

        indices.Add(2);
        indices.Add(7);
        indices.Add(3);

        indices.Add(4);
        indices.Add(7);
        indices.Add(6);

        indices.Add(4);
        indices.Add(6);
        indices.Add(5);

        indices.Add(1);
        indices.Add(4);
        indices.Add(5);

        indices.Add(1);
        indices.Add(0);
        indices.Add(4);

        indices.Add(0);
        indices.Add(7);
        indices.Add(4);

        indices.Add(0);
        indices.Add(3);
        indices.Add(7);

```

# Answer
> 2 votes
Your code for `SetupVertices` is not taking into account the position of each cube in the chunk. The vertex buffer is for the *whole* chunk - and individual vertices must be stored in "chunk" space (relative to to the position of the chunk). Right now you're just creating a bunch of cubes at the origin. You need to translate them (just use `+`) to the correct position.

Then your `SetupIndices` method is not taking into account the location in the vertex buffer where each cube starts. So, effectively, each time you're adding a cube, you're really telling the GPU to render the first cube in the buffer - and the later cubes are just being ignored.

Here is a modified version of your code. I haven't tested it or checked your numbers. This is just to illustrate how you must do the offsetting for both vertices and indices. This code replaces `SetupVertices` and `SetupIndices` with a single method that takes the coordinates of each cube relative to the chunk.

```
private void SetUpVerticesAndIndicies(int x, int y, int z)
{
    short verticesStart = (short)vertices.Count;
    Vector3 cubePosition = new Vector3(x, y, z);

    // Create the appropriate vertices for the cube:

    //front left bottom corner ok
    vertices.Add(new VertexPositionTexture(cubePosition + new Vector3(0, 0, 0), new Vector2(1, 0)));
    //front left upper corner
    vertices.Add(new VertexPositionTexture(cubePosition + new Vector3(0, 1, 0), new Vector2(1, 1)));
    //front right upper corner ok
    vertices.Add(new VertexPositionTexture(cubePosition + new Vector3(1, 1, 0), new Vector2(0, 1)));
    // ... etc ...

    // Create the appropriate indices for the cube:
    // (these are indexes into the vertices list)

    indices.Add(verticesStart + 0);
    indices.Add(verticesStart + 2);
    indices.Add(verticesStart + 3);

    indices.Add(verticesStart + 0);
    indices.Add(verticesStart + 1);
    indices.Add(verticesStart + 2);

    // ... etc ...
}

```

Hopefully you can see how this would translate to a method to add individual faces, as we discussed in your previous questions.

# Answer
> 0 votes
I don't really know what you're actually drawing, but you should start with some simple culling.

In essence, don't draw stuff you can't see anyway.

This can be a bit tricky in 3D and it's partially done by the graphics card anyway, but it will still have to try to draw things, which will still cause work to be done.

Also try to avoid creating new objects in your drawing code, unless they're really small/primitive.

I assume this is supposed to become some kind of minecraft like block landscape.

* So, at first, I'd cull by distance: Group blocks into larger chunks of blocks. For explanation I'll only explain this in one dimension. In the end you'd apply it to all dimensions, essentially collecting cubes within a grid of cubes.
* Let's assume you've got 100 cubes to draw with `x` coordinates ranging from `0` to `100`. You create chunks or containers every 10 units: The 10 cubes with coordinates between `0` and `10` are associated to the first chunk, the cubes from `10` to `20` belong to the second chunk, etc.
* Based on your view/drawing distance, now you only draw chunks being closeby. For example, let's assume the drawing distance is `5` and your camera is at `47`: This would mean you'd be drawing the chunk from `40` to `50` as well as the chunk from `50` to `60`. so instead of drawing 100 cubes, you'd actually draw a maximum of 20 cubes. You're saving 80% of draw calls!
* Further optimizations: Cache the render data for each chunk. For example, assign each chunk it's own vertex buffer and stuff instead of drawing cube by cube. Then just draw the chunks. You only update that data if a cube inside the chunk changes (e.g. is destroyed).

Regarding your last note with positioning: Your actual vertex coordinates should always be local. E.g. their origin should be at the cube's (or chunk's) origin. Then adjust your world matrix to "move" these into position. This way you don't have to touch vertex data again, resulting in another performance gain.

Overall, in DirectX there are three matrixes determining how/where something is rendered. Right now I'm not 100% sure how abstracted away these are in XNA, so I might be a bit off here:

* **World Matrix:** This determines the actual translation/rotation of some vertex in the actual world. It's essentially the global coordinate of an object.
* **View Matrix:** This determines the camera's position, orientation, etc.
* **Projection Matrix:** This determines how the camera actually "looks" into the world. For example, this determines the aspect ratio/opening, the actual projection (orthogonal vs. perspective), etc.

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


title: Handling intro and title screen

text:
# Question
Title: Handling intro and title screen
What is the best way to handle the intro, title screen, and menus? I am contemplating that each of these could be a "scene" object of sorts. Perhaps in the game loop based on what needs to be done, a specific scene is loaded and everything that is contained within is executed. When that scene is no longer needed, it is unloaded.

Am I thinking about this correctly? I am not sure if "Scene" would be the best term to use in this case, but it is the best way I can describe it. Perhaps screen objects handled by a screen manager? If there is something more appropriate, I would love to know!

Also, for example I am thinking to have:

* Intro "scene"
* Main menu
* Settings

# Answer
Simplest way to handle these, would be state enums. You would create enum, that has all the different states. Changing state, would cause program to run different code.

Define enum at somewhere:

```
public enum States
{
    Intro,
    MainMenu,
    Settings
}

```

Store your current state in a variable:

```
States gameState;

```

Set initial state at your game startup method.

```
void Init()
{
    gameState = States.Intro;
}

```

In your update method / mainloop, check the state and do something about it.

```
void Update()
{
    switch(gameState)
    {
        case States.Intro:
            ProcessIntroState();
            break;
        case States.MainMenu:
            ProcessMainMenuState();
            break;
        case States.Settings:
            ProcessSettingsState();
            break;
    }
}

```

This is very simple state handling setup. It is ok, for smaller games and projects, but for larger project, somekind of ScreenManager would be better.
> 2 votes

# Answer
You can use a GameScene approach too, where you have scenes that inherit from a base class, and a Stack to store them. I think is a good solution that lets you encapsulate different situations in the game in different modules.

```
 abstract class GameScene {
      public static readonly Stack<GameScene> Stack= new Stack<GameScene>();
      abstract void Update(GameTime time);
      virtual void Render() {}
 }

 class Intro : GameScene {
     public override void Update()
     {
         if (seconds>3)
         {
             GameScene.Pop();
             GameScene.Push(new Menu());
         }
     }
 }

 class Menu : GameScene { ... }

 // In Game
 public void Update(gametime time) {
      GameScene.Stack.Peek().Update(time);
 }

```

Above code is similar to the Game State Manager sample from microsoft: http://xbox.create.msdn.com/en-US/education/catalog/sample/game\_state\_management
> 1 votes

---
Tags: c#, game-design
---


# Question
Title: How do I draw a border around a display object in Corona Lua?
What would be the easiest way to draw a thin border around a rectangle image display object in Corona Lua?

This is what I tried:

* Reviewed API and could not find a "border" method/property on displayObject
* Have tried creating a black box slightly bigger behind object, however can not see how to place object behind an existing object hence question How do I move an existing display object behind another in Corona Lua?
* Google results for putting a border around a display object in corona didn't help

# Answer
> 2 votes
We have display option available now. You can set strokeWidth & setStrokeColor based on your requirement for display objects.

Here is the help link

Kudos!!!

# Answer
> 2 votes
You can add an object behind another. Just add the black object (the border) first and then your main object. If you are using physics you have to set some flags so the 2 objects don't collide. Why don't you just add a sprite for your object (png, jpg) ?

---
Tags: lua, corona-sdk
---


# Question
Title: Problem with modifying dice in another players turn
I have the following problem: I want to create a multiplayer game where each player has a turn where he has to roll a lot of dice again and again. But the other players are capable of modifying each single dice with a special action. But since this is a rare action because each player has a limited amount of modifications, I do not want to implement a simple dialog where you have to approve each roll. This would make the game rather sluggish. Any suggestions for the best way to implement a UI which allows to modify every single dice, but makes the game as fast as possible?

# Answer
> 1 votes
You could make dice animations last longer on the main player screen than on the opponent screen. This way the opponent would have a very short time period to click or hit a button in order to modify the result. If all the rolls are longer on the main player screen and shorter on the opponent screen, then the main player should not be able to know if the final result has been modified or not. (Of course this require an UI that enable very fast modification)

You could also choose to give more time to the opponent to decide himself, but this is at the price of somehow informing the main player of the modification. It could be done using some kind of time traveling animations. Let's take an example: suppose the main player is rolling its fifth dice hand. In the meantime the opponent who is reviewing the third one decide to modify it. Then the main player temporary loose the control and an animation show the dice rolls in reverse animation until the third roll, then a modification occurs and finally the fourth and fifth rolls are re-played. At that point the player can continue to roll the others dices but he knows about the modifications.

Finally another way to proceed would be by modifying the results afterward. First the main player rolls all the dices and in a second time the opponent can decide to take part of the turn and modify the results or to let the game continue. Of course, this is a quite visible method too.

There is probably plenty of others approaches, but those are the main ideas that come to my mind now.

# Answer
> 1 votes
Take a look at how Magic: Duels of the Planeswalkers does things.

Each player has turns made up of multiple phases. Each action needs confirmation. The system lets a player decide if he wants to act in any particular phase with a super easy in-game panel showing the phases and which ones the game will stop for. There is a timer to ensure nobody takes forever.

You can also allow more than one modification to be applied at a time. When a player rolls, give the other player time to select any dice he wants to modify and what mods to apply. A simple drop-down or radial menu over each die might work.

---
Tags: multiplayer, turn-based
---


title: Cubes drawing on top of each other

text:
# Question
Title: Cubes drawing on top of each other
In follow up of my previous question: Limit the number of draw calls

I've lowered my draw calls to only 58 a frame!! But now I have another problem. I have 2500 cubes all drawn in the same position. I have no idea why. Everything that was done in my previous question works fine. This is my draw method that draws my chunk.

```
    public void Draw(BasicEffect effect, ThirdPersonCam cam)
    {
        device.SetVertexBuffer(vertexBuffer);
        device.Indices = indexBuffer;

        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            no++;
            pass.Apply();
            effect.VertexColorEnabled = false;
            effect.TextureEnabled = true;
            effect.Texture = grass;

            Matrix center = Matrix.CreateTranslation(new Vector3(-0.5f, -0.5f, -0.5f));
            Matrix scale = Matrix.CreateScale(1f);
            Matrix translate = Matrix.CreateTranslation(cubePosition);

            effect.World = center * scale * translate;
            effect.View = cam.view;
            effect.Projection = cam.proj;

            effect.FogEnabled = true;
            effect.FogColor = Color.CornflowerBlue.ToVector3();
            effect.FogStart = 1.0f;
            effect.FogEnd = 50.0f;

            device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 8, 0, 12);
        }

```

There might be some problems with the way the code is ordered in the method, but this is after moving things around. Changing the values in my DrawIndexedPrimitives line to vertices.Count and cubes.Count draws more cubes, but very strangely. There's 4 rows of 50 and then another row with just 10

# Answer
> 1 votes
It's (probably) your `DrawIndexedPrimitives` call. The correct arguments should be:

```
device.DrawIndexedPrimitives(PrimitiveType.TriangleList,
        0, 0, vertices.Count, 0, indices.Count / 3);

```

Using the `Count` values from the lists used to create the buffers in the first place (as per your previous question).

See the documentation on MSDN.

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


# Question
Title: Best way to load texture2d tiles in xna?
I am making a test xna game as a learning exercise and I have a small question about using 2d textures. Basically the game is a grid of different 'tiles' which are taken from a text map file. I basically just parse through the file when initializing a level and create a matrix of the different tile types. The level is essentially a tub of wall tiles and spikes. So essentially, there are lots of wall tiles and multiple spike tiles and then lots of empty tiles. However, there are four types of wall tile and spike textures to cover different directions.

My question is what is the best way to load the textures for each of the tile? Do I load individual textures for each tile? i.e when I create a tile, pass it a texture2d which I can draw and load the texture at the same time. This seems like a good way, but then I have to load each tiles texture individually and this seems wasteful.

The other option I can think of is to use a static texture in the tile struct an then simple load this texture as a tile atlas with the different walls and spikes. This way I am only loading a single texture, and then when drawing I just move a rectangle to the area of the appropriate tile within the sprite.

I am not sure which of these ways would be optimal from a performance perspective, or if there is an alternative approach?

Thanks in advanmce

# Answer
> 2 votes
Use Dictionary to hold all the textures. Key can be anything you like. I use byte, because my map format is all about bytes. Different bytes in map grid, means different tiles. This way, you don't have to load same texture multiple times or attach texture to tile.

Your map would be something like:

```
byte[,] Tiles = new byte[5,5] {
    {1, 1, 1, 1, 1},
    {1, 2, 2, 2, 2},
    {1, 1, 2, 3, 3},
    {1, 1, 2, 3, 3},
    {1, 1, 2, 1, 1}
};

```

This could and should be in file. Text or XML or something what ever feels comfortable.

Numbers could mean:

1. Grass tile
2. Sand tile
3. Bush tile

Load method would look like:

```
myGrassTile = this.Content.Load<Texture2D>("grassTile");
mySandTile = this.Content.Load<Texture2D>("sandTile");
myBushTile = this.Content.Load<Texture2D>("bushTile");

TextureDict.Add(1,myGrassTile);
TextureDict.Add(2,mySandTile );
TextureDict.Add(3,myBushTile );

```

Here i link number to match correct texture. So later on, i can just read position from map and pass that number to dictionary and it would return me the correct texture2d.

In draw call, you can just:

```
 spriteBatch.Begin();

 for (int x = 1; x <= 5; x++)
 {
      for (int y = 1; y <= 5; y++)
      {
           //calculate the location of tile.
           //If tiles are 32 pixel width and height, then x * 32 and y * 32 would be
           //correct position.
           spriteBatch.Draw(TextureDict[Tiles[x,y]],new Rectangle(x*32,y*32,32,32), Color.White);
      }
 }

 spriteBatch.End();

```

**Note** This is semipseudo code. Its written in one sit, i have not tested it, but it should show you, how it could be done.

---
Tags: xna, c#, xna-4.0, tiles, monogame
---


# Question
Title: When are HLSL literals taken as a float and integer?
```
float2 uv = float2(fX % 1, fY % 1) * 1/16;

```

In the above example 1/16 is treated as a float, multiplying the float2 by 0.0625, but in:

```
float2 uv = float2(fX % 1, fY % 1) * 1/16 + float2(1/16,0);

```

The second 1/16 is taken as an integer and the second float2 becomes (0,0).

What's the order in which a specific type is used. And is there any suffix to force a float? I know 1.0/16.0 would work.

# Answer
> 5 votes
Use a decimal to mark a type as a float. `1.0` is always floating point. Hence `1.0/16` or `1/16.0` will always be floating point.

Numeric literals are treated as floats if used in a floating-point context. Remember that operators like `*` and `/` are left-associative. So in your first example, the code is equivalent to `(float(...) * 1) / 16`. If you put the `1/16` in parentheses then it would be equal to `0` and that would be multiplied with the vector, e.g `float2(...) * (1/16) == float2(0,0)`

In your second example, the `1/16` is seen by itself, computed (as integers, because there's no float involved), and then the *result* of the expression is converted to float for the `float2` construction. You need to cause either the `1` or the `16` to be a float in order for the `/` operator to be in a float context and force the other value to be treated as a float.

---
Tags: shaders, hlsl
---


title: Loading map in tile based game

text:
# Question
Title: Loading map in tile based game
I'm currently working on a simple 2D tile based game. I want to let users (=players) to create really large maps without problems with performance. That is why I'm searching the way how to optimalize the code before I actually write it. I've read some articles about streaming tiles, but I don't think I've understood them at all.

Map is stored in simple INI file like this:

```
[MAP]
title = "Test"
tileset="test.png"
width = 5
height = 5

tile_widht = 32
tile_height = 32

[LAYER]
type="background"
data="0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4"

# ... items, NPCs and quests definitions

```

When loading a new map, I'm reading the file line by line and parse it. After that, I create array of Tiles (std::vector tiles).

Every tile knows it's own position, value (which is the number indicating the tile from tileset), passability (number which indicates how hard is it to pass this tile), inventory (list of items lying on this tile), NPC list (list of NPCs standing on this tile) etc...

Now comes my problem. How to stream the tiles? With this file format it seems to be inpossible to load data when needed, so I have to load them at once.

Only thing which comes to my mind is, to store map data in arrays and create Tile classes only when they are really needed (if the tile position is withing the screen) and unload them after leaving the screen...

My question is, how do you suppose to solve this problem? How do you do it in your games?

Thank for your help and sorry for my English.

# Answer
> 4 votes
Just load everything to memory. Even low-end PC nowadays, has atleast 500Mb spare memory available. You are going to have hard time while filling that memory.

You did not mention, how big your maps are going to be, but 1000x1000 has Million tiles. Doing that by hand, is lot more work, than coding your game. What if its 3000x3000, its escalating quite fast. Think realistically, will you, or someone ever create that big map to your game?

**Quick test with C#:**

I made map with size of 1000x1000.

Every tile had: 50 random integers ( 32bit ) and few guids strings and such. Even with 1 Million tiles, it used 350Mb of memory.

**Don't optimize your code, before you know for sure, that you need to do it.**

EDIT: Here, i'm assuming, that you are new to programming and to game programming. Finishing games, is far more important, than trying to create map loading mechanism that ( in the end ) might not even be needed.

# Answer
> 1 votes
Here is an abstract BoardStorage class that I am using on my Napoleonics engine, with maps upwards of 700 * 400 tiles. Although the code is C#, a C++ programmer should have no difficulty porting it.

```
  /// <summary>Abstract specification and implementation of the <c>BoardStorage</c> required by <c>HexBoard</c>.</summary>
  /// <typeparam name="THex">The type of the hex being stored.</typeparam>
  public abstract class BoardStorage<THex> : IDisposable {
    /// <summary>Initializes a new instance with the specified hex extent.</summary>
    /// <param name="sizeHexes"></param>
    protected BoardStorage(Size sizeHexes) {
      MapSizeHexes   = sizeHexes;
    }

    /// <summary>Extent in hexes of the board, as a <see cref=" System.Drawing.Size"/> struct.</summary>
    public          Size MapSizeHexes           { get; private set; }

    /// <summary>Returns the <c>THex</c> instance at the specified coordinates.</summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design",
      "CA1043:UseIntegralOrStringArgumentForIndexers")]
    public abstract THex this[HexCoords coords] { get; internal set; }

    /// <summary>Returns whether the hex with <see cref="HexCoords"/> <c>coords</c> is
    /// within the extent of the board.</summary>
    public          bool IsOnboard(HexCoords coords) {
      return 0<=coords.User.X && coords.User.X < MapSizeHexes.Width
          && 0<=coords.User.Y && coords.User.Y < MapSizeHexes.Height;
    }

    /// <summary>Performs the specified <c>action</c> serially on all hexes.</summary>
    public abstract void ForEach(Action<THex> action);

    /// <summary>Performs the specified <c>action</c> in parallel on all hexes.</summary>
    public abstract void ParallelForEach(Action<THex> action);

    #region IDisposable implementation with Finalizeer
    bool _isDisposed = false;
    /// <inheritdoc/>
    public void Dispose() { Dispose(true); GC.SuppressFinalize(this); }
    /// <summary>Anchors the Dispose chain for sub-classes.</summary>
    protected virtual void Dispose(bool disposing) {
      if (!_isDisposed) {
        if (disposing) {
        }
        _isDisposed = true;
      }
    }
    /// <summary>Finalize this instance.</summary>
    ~BoardStorage() { Dispose(false); }
    #endregion
  }

```

Two complete implementations (one a Simple row-major List\<List\<IHex\>\> and the other a Blocked List\<List\<List\<IHex\>\>\> with internal blocks of 32 x 32 for better localization) are available here: Hexgrid Utilities for Board games.

I got about a 5-10% improvement in path-finding times using the BlockedBoardStorage on a map of 760 * 420. Bigger maps should benefit even more.

Although I agree that premature optimization is wasteful, building simple *optimizable* structures early is simply part of good design..

---
Tags: c++, tiles, tilemap
---


title: Texturing a quad

text:
# Question
Title: Texturing a quad
Drawing a quad with a texture mapped to it with the fixed OpenGL pipeline is one of the easiest things to do in OpenGL.

And for some madmaking, mysterious, dumb reason I can't get it to work.

I loaded a texture through Slick:

```
texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("resources/textures/texture.png"), false);

```

I setup my 2D projection:

```
glDisable(GL_DEPTH_TEST);
glDisable(GL_TEXTURE_2D);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, Display.getWidth(), Display.getHeight(), 0, 1, -1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

```

Then in my game loop I call:

```
texture.bind();
glEnable(GL_TEXTURE_2D);

glBegin(GL_QUADS);
glTexCoord2f(0.0f, 1.0f);
glVertex2f(0, 0);

glTexCoord2f(1.0f, 1.0f);
glVertex2f(300, 0);

glTexCoord2f(1, 0);
glVertex2f(300, 90);

glTexCoord2f(0.0f, 0.0f);
glVertex2f(0, 90);

glEnd();

```

This is my texture:

And this is what I get:

It's smaller, and as you can see it's all wrong. It's kind of embarrassing that I have to ask this question, but it has keeping me busy for a few hours now.

# Answer
It’s likely that when loaded by your framework, the texture is padded vertically and horizontally to the nearest power of two. For instance, if it’s a 320×200 image, it will be stored in a 512×256 texture.

You have at least two options:

* use a texture with power of two dimensions
* or change your texture coordinates to the proper ones, for instance `glTexCoord2f(320.f / 512, 200.f / 256);`.
> 7 votes

---
Tags: opengl, textures, rendering
---


# Question
Title: using a texture with indices and vertices
I've written this down on paper and tried to understand how the triangles of each cube are created, but I can't get my texture drawn on my cube properly. I don't know if it's the texuture coordinates of each face of my cube, or the order in which I create the cube from my vertices, but I only see two sides correctly and the rest are gray.

```
    private void SetUpFrontFace(Vector3 cubeInChunkPosition, List<VertexPositionTexture> vertices)
    {

        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(0, 0, 0), new Vector2(0, 1)));
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(0, 1, 0), new Vector2(0, 0)));
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(1, 1, 0), new Vector2(1, 0)));
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(1, 0, 0), new Vector2(1, 1)));
    }

    private void SetUpBackFace(Vector3 cubeInChunkPosition, List<VertexPositionTexture> vertices)
    {
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(0, 0, -1), new Vector2(0, 1)));
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(0, 1, -1), new Vector2(0, 0)));
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(1, 1, -1), new Vector2(1, 0)));
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(1, 0, -1), new Vector2(1, 1)));
    }

    private void SetUpLeftFace(Vector3 cubeInChunkPosition, List<VertexPositionTexture> vertices)
    {
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(0, 0, -1), new Vector2(0, 1)));
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(0, 1, -1), new Vector2(0, 0)));
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(0, 1, 0), new Vector2(1, 0)));
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(0, 0, 0), new Vector2(1, 1)));
    }

    private void SetUpRightFace(Vector3 cubeInChunkPosition, List<VertexPositionTexture> vertices)
    {
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(1, 0, 0), new Vector2(0, 1)));
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(1, 1, 0), new Vector2(0, 0)));
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(1, 1, -1), new Vector2(1, 0)));
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(1, 0, -1), new Vector2(1, 1)));
    }

    private void SetUpTopFace(Vector3 cubeInChunkPosition, List<VertexPositionTexture> vertices)
    {
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(0, 1, 0), new Vector2(0, 1)));
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(0, 1, -1), new Vector2(0, 0)));
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(1, 1, -1), new Vector2(1, 0)));
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(1, 1, 0), new Vector2(1, 1)));
    }

    private void SetUpBottomFace(Vector3 cubeInChunkPosition, List<VertexPositionTexture> vertices)
    {
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(0, 0, 0), new Vector2(0, 0)));
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(0, 0, -1), new Vector2(0, 1)));
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(1, 0, -1), new Vector2(1, 1)));
        vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(1, 0, 0), new Vector2(1, 0)));
    }

    private void SetUpIndicesAndVertices(float x, float y, float z, List<VertexPositionTexture> vertices, List<short> indices)
    {
        short verticesStart = (short)vertices.Count;

        Vector3 cubeInChunkPosition = new Vector3(x, y, z);

        SetUpFrontFace(cubeInChunkPosition, vertices);
        SetUpBackFace(cubeInChunkPosition, vertices);

        SetUpRightFace(cubeInChunkPosition, vertices);
        SetUpLeftFace(cubeInChunkPosition, vertices);

        SetUpTopFace(cubeInChunkPosition, vertices);
        SetUpBottomFace(cubeInChunkPosition, vertices);

```

All my vertices being built. I think the texture coordinates are correct. They start from the top left corner rotating clockwise around the whole face.

```
    indices.Add((short)(verticesStart + 0));
        indices.Add((short)(verticesStart + 2));
        indices.Add((short)(verticesStart + 3));

        indices.Add((short)(verticesStart + 0));
        indices.Add((short)(verticesStart + 1));
        indices.Add((short)(verticesStart + 2));

        indices.Add((short)(verticesStart + 1));
        indices.Add((short)(verticesStart + 5));
        indices.Add((short)(verticesStart + 6));

        indices.Add((short)(verticesStart + 1));
        indices.Add((short)(verticesStart + 6));
        indices.Add((short)(verticesStart + 2));

        indices.Add((short)(verticesStart + 2));
        indices.Add((short)(verticesStart + 6));
        indices.Add((short)(verticesStart + 7));

        indices.Add((short)(verticesStart + 2));
        indices.Add((short)(verticesStart + 7));
        indices.Add((short)(verticesStart + 3));

        indices.Add((short)(verticesStart + 4));
        indices.Add((short)(verticesStart + 7));
        indices.Add((short)(verticesStart + 6));

        indices.Add((short)(verticesStart + 4));
        indices.Add((short)(verticesStart + 6));
        indices.Add((short)(verticesStart + 5));

        indices.Add((short)(verticesStart + 1));
        indices.Add((short)(verticesStart + 4));
        indices.Add((short)(verticesStart + 5));

        indices.Add((short)(verticesStart + 1));
        indices.Add((short)(verticesStart + 0));
        indices.Add((short)(verticesStart + 4));

        indices.Add((short)(verticesStart + 0));
        indices.Add((short)(verticesStart + 7));
        indices.Add((short)(verticesStart + 4));

        indices.Add((short)(verticesStart + 0));
        indices.Add((short)(verticesStart + 3));
        indices.Add((short)(verticesStart + 7));

```

The indices. I don't know why this is happening. I've messed around with the Texture values and have gotten textures to show on all sides, but they always come out skewed.

# Answer
Your texture coordinates are being specified anti-clockwise. They should match the x and y coords of your first face.

```
private void SetUpFrontFace(Vector3 cubeInChunkPosition, List<VertexPositionTexture> vertices)
{

    vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(0, 0, 0), new Vector2(0, 0)));
    vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(0, 1, 0), new Vector2(0, 1)));
    vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(1, 1, 0), new Vector2(1, 1)));
    vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(1, 0, 0), new Vector2(1, 0)));
}

```

EDIT:

Also your vertices in `SetUpBackFace` and `SetUpBottomFace` are being supplied in anti-clockwise.

```
private void SetUpBackFace(Vector3 cubeInChunkPosition, List<VertexPositionTexture> vertices)
{
     vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(0, 0, -1), new Vector2(0, 0)));
     vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(1, 0, -1), new Vector2(0, 1)));
     vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(1, 1, -1), new Vector2(1, 1)));
     vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(0, 1, -1), new Vector2(1, 0)));
}

private void SetUpBottomFace(Vector3 cubeInChunkPosition, List<VertexPositionTexture> vertices)
{
    vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(0, 0, 0), new Vector2(0, 0)));
    vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(1, 0, 0), new Vector2(0, 1)));
    vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(1, 0, -1), new Vector2(1, 1)));
    vertices.Add(new VertexPositionTexture(cubeInChunkPosition + new Vector3(0, 0, -1), new Vector2(1, 0)));
}

```

EDIT 2:

You need to re-evaluate your index list:

```
    // Front face
    indices.Add((short)(verticesStart + 0));
    indices.Add((short)(verticesStart + 2));
    indices.Add((short)(verticesStart + 3));

    indices.Add((short)(verticesStart + 0));
    indices.Add((short)(verticesStart + 1));
    indices.Add((short)(verticesStart + 2));

    // Back face
    indices.Add((short)(verticesStart + 4));
    indices.Add((short)(verticesStart + 6));
    indices.Add((short)(verticesStart + 7));

    indices.Add((short)(verticesStart + 4));
    indices.Add((short)(verticesStart + 5));
    indices.Add((short)(verticesStart + 6));

    // Left face
    indices.Add((short)(verticesStart + 8));
    indices.Add((short)(verticesStart + 10));
    indices.Add((short)(verticesStart + 11));

    indices.Add((short)(verticesStart + 8));
    indices.Add((short)(verticesStart + 9));
    indices.Add((short)(verticesStart + 10));

    // Right face
    indices.Add((short)(verticesStart + 12));
    indices.Add((short)(verticesStart + 14));
    indices.Add((short)(verticesStart + 15));

    indices.Add((short)(verticesStart + 12));
    indices.Add((short)(verticesStart + 13));
    indices.Add((short)(verticesStart + 14));

    // Top face
    indices.Add((short)(verticesStart + 16));
    indices.Add((short)(verticesStart + 18));
    indices.Add((short)(verticesStart + 19));

    indices.Add((short)(verticesStart + 16));
    indices.Add((short)(verticesStart + 17));
    indices.Add((short)(verticesStart + 18));

    // Bottom face
    indices.Add((short)(verticesStart + 20));
    indices.Add((short)(verticesStart + 22));
    indices.Add((short)(verticesStart + 23));

    indices.Add((short)(verticesStart + 20));
    indices.Add((short)(verticesStart + 21));
    indices.Add((short)(verticesStart + 22));

```
> 1 votes

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


title: cocos2d ccTouchEnded: Removing a Touch

text:
# Question
Title: cocos2d ccTouchEnded: Removing a Touch
These are my ccTouch\_*_* methods. Note that I am using the singular form of the functions (ie. ccTouchBegan v. ccTouchesBegan (don't know if that has anything to do with it, but it can't hurt to point it out)).

```
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{
    //NSLog(@"1");

    CGPoint touchLocation = [GameScene locationFromTouch:touch];
    CTouch* newTouch = [[CTouch alloc] initWithStart:touchLocation];
    [touches addObject:newTouch];

    //Right now the UILayer takes all touch events and handles them
    return YES;
}

-(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event{
    //NSLog(@"2");

    //Get the touch's location and previous location
    CGPoint touchLocation = [GameScene locationFromTouch:touch];
    CGPoint lastTouchLocation = [GameScene previousLocationFromTouch:touch];
    //Check which CTouch has been moved and move it
    for (CTouch* ct in touches){

        if ([ct checkSameTouch:lastTouchLocation]) {
            [ct setCurrentPosition:touchLocation];
        }
    }

}

-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event{
    NSLog(@"3");

    //Get the touch's location
    CGPoint touchLocation = [GameScene locationFromTouch:touch];
    CGPoint lastTouchLocation = [GameScene previousLocationFromTouch:touch];
    //The CTouch object to be removed
    //You can't remove an object from the array while its being enumerated
    CTouch* removeTouch;

    //Check and hold which CTouch has ended
    for (CTouch* ct in touches){

        if ([ct checkSameTouch:lastTouchLocation]) {
            removeTouch = ct;
        }
    }

    //Remove the touch
    [touches removeObject:removeTouch];
}

```

For some reason, the way I'm checking which CTouch object in touches to move in the ccTouchMoved function works fine, but when I try the exact same thing in ccTouchEnded, it doesn't work.

EDIT: I take it back. The "if" statement to update ct in ccTouchMoved only works the first time. I think this might be the real problem. Because the CTouch object isn't being updated, its information isn't the same as the UITouch object's by the time the touch ends.

I have tried the "if" statement in ccTouchEnded with both the lastTouchLocation and touchLocation and neither of them work. The "if" statement is never true and removeTouch is, therefore, always empty.

The lastTouchLocation and touchLocation in ccTouchEnded are always wildly different from the ct.lastPosition. Just to make sure I cover everything, here's a sample set:

```
ct.lastPosition:     84,125
ct.currentPosition:  85,125

lastTouchLocation:   155,131
touchLocation:       174,132

```

# Answer
> 1 votes
Alright, I figured it out, and it wasn't in the code I displayed.

I was checking the CTouch object's previous location against the UITouch object's. What I needed to be doing was checking the CTouch object's current location agains UITouch object's previous.

Got it working.

---
Tags: cocos2d, multitouch
---


# Question
Title: How to keep Lua bindings from cluttering up C++ code?
I'm writing a game engine that uses C++ and Lua (and Luabind).

Currently, I'm writing all the bindings inside the constructor of the class being binded. I really don't like this because it's cluttering up my code.

Where should I put the Lua glue code so that it is out of the way and not cluttering up my codebase?

# Answer
The method I have used with good results is to give each class that needs Lua bindings a static class method with the following signature:

```
static luabind::scope luaBindings();

```

The definition of this method looks like this:

```
luabind::scope
MyClass::luaBindings() {
    using namespace luabind;
    return class_<MyClass>("MyClass")
        .def(constructor<>())
        .def("someMethod", &MyClass::someMethod)
    ;
}

```

Then, in some other place, I initialize the Lua state like this:

```
void
initializeLua(
    lua_State* L
) {
    luabind::open(L);
    luabind::module(L) [
        MyClass::luaBindings(),
        MyOtherClass::luaBindings()
    ];
}

```

This way, all Lua bindings are contained in the static class methods. The Lua state is initialized in a very controlled way, without headaches about the order that classes are exported in.

The only downside I have encountered so far is that the `initializeLua` function needs to know all the classes being exported. Depending on the number of classes, this will result in a rather large list of included files and potentially long compilation times. If that's an issue for you, you can build the `luabind::scope` hierarchically like this:

```
luabind::scope
moduleABindings() {
    return (
        MyClass::luaBindings(),
        MyOtherClass::luaBindings()
    );
}

luabind::scope
moduleBBindings() {
    return (
         Foo::luaBindings(),
         Bar::luaBindings()
    );
}

void
initializeLua(
    lua_State* L
) {
    luabind::open(L);
    luabind::module(L) [
        moduleABindings(),
        moduleBBindings()
    ];
}

```

By separating those functions into separate compilation units, a small change in one of the exported classes' headers will not require recompiling the whole initializer, just the module that has changed.
> 6 votes

# Answer
0) Move your constructor to a separate file, there's no rule that says your entire class has to be all in one physical .cpp file.

1) Put your binding code in a separate function in a different file, have the constructor call it? This would be the preferred method.

2) write your binding code in a separate file, inline, and #include it directly into your constructor. This is an oldschool way to get around, not so great these days.

```
fn::fn()
{
#include "clutter.txt"
}

```

At least that way it's only cluttering up your project and not the code you see on a daily basis.
> 4 votes

---
Tags: c++, scripting, lua
---


title: Matcap and BRDF Shading

text:
# Question
Title: Matcap and BRDF Shading
I just would like to know what's the difference between the Matcap shaders used in ZBrush for example and the Bidirectional Radiance Distribution Function shader.

Are there two techniques the same ? Is Matcap done using BRDF or are they different ?

# Answer
Assuming that you are referring to Bidirectional *Reflectance* Distribution Functions, a BRDF is nothing more than a fancy name for a broad class of lighting equations. These are Functions that compute the Distribution of Reflectance from a surface based on two directions (Bidirectional): the direction of the incident light and the direction of the viewer of the surface. The BRDF directions are both defined in terms of their relative direction with respect to the normal, so the normal is effectively an implicit parameter.

This is a very *generalized* category of lighting equations. Standard Lambert, Blinn, Phong, and so forth all qualify as Bidirectional Reflectance Distribution Functions. They can all be stated in terms of the direction towards the light and the direction towards the viewer.

However, since you're comparing it to Matcap, I assume you are referring to *physically based* BRDFs, not the general category of all BRDFs. That is, BRDFs generated from tables computed by using machines to detect the light interaction properties of real materials with a changing view and light direction.

Assuming the Matcap you are referring to is something like this, I would have to say, no. At least that particular implementation of Matcap is not.

If you want to be exceptionally generous, then it is a BRDF. But only in the loosest possible sense. Why? Because the reflectance computed *does not change* with either of the two directions. Just look at the shader; the only directional information it uses is the surface normal. And while it is a property that is *used* to compute the color, from the perspective of a BRDF, it's a constant.

If you want to be technical, Matcap *uses* a BRDF. Namely, the *sphere texture*. That is what the lighting equation actually is; that's the reflectance distribution, based on a specific view and light direction.

A proper physically-based BRDF is effectively a 4-dimensional lookup table, based on the angles of the two directions. Matcap uses a 2-dimensional lookup table, and the lookup is not really based on either the view or the light direction; just the normal. Matcap is basically cheating, using a single, static 2D slice of a proper 4D BRDF.

So no, Matcap is not a BRDF, much like your code that uses the *result* of a BRDF to color a particular pixel is not itself a BRDF.
> 4 votes

---
Tags: shaders, rendering, pbr
---


title: Is SDL a game engine?

text:
# Question
Title: Is SDL a game engine?
I would like to ask if SDL is considered a game engine, or just a library like Open and Direct3D?

# Answer
> 17 votes
SDL is a library. OpenGL is kinda library. DirectX is a collection of libraries. None of these are engines. Engines are built with some or all of these though.

Understand that you are looking at this in a way which won't allow you to fully understand the scope of these technologies. The term library is thrown around a lot, and it does little here to help anybody understand the purpose/intent of the technologies describe.

**OpenGL** first and foremost is a standard which has various implementations from system to system. A group of people meet, agree upon a standard which then becomes available to people ( like graphics hardware and operating system manufacturers ) who then in turn create an implementation. The implementation of OpenGL is a library, and is almost solely focused on providing us access to graphics hardware to accelerate and better our scenes.

**SDL** is a library built to be a solution to tackle the many redundant obstacles associated with creating a cross-platform game that utilizes such things as window management, event handling, video stuff which differ from platform to platform. Don't believe me? Make a simple program that only produces a window on the three major platforms and see how long it takes, now do it with SDL and realize why it exists. SDL can also utilize an implementation of OpenGL to further extend its capabilities, but SDL is by no means an engine. SDL however is a collection of sub-systems, not all of which have to be used in a project using SDL. Some of the sub-systems are video, audio, events, timing, etc.

**DirectX** would be most comparable to SDL in this set of technologies that we are discussing. DirectX is not cross-platform, but does provide a developers tools to easily tackle some of the problems associated with developing a game on windows. DirectX ( like SDL ) is really an amalgamation of technologies such as Direct3D, DirectAudio, DirectDraw etc. which together form a very powerful solution to taking on a game project.

An engine utilizes one or even all of these technologies to build a system which can be re-used to construct various games. For instance, the Unreal Engine utilizes both OpenGL and DirectX to bolster its graphics capabilities, and help push the technology across various platforms.

---
Tags: opengl, directx, sdl
---


# Question
Title: AI of Turn Based game using Entity System approach
I just recently learned about Entity Systems and want to try it out on a real example (I was developing a game recently and want to try to port it over Entity Systems). But I got problem right away. Actually that is two questions in one.

**First would be:**

In traditional OOP approach I had game loop which was picking action to do for idling units every 100ms (so-called 'turn'). But rendering obviously was run at every game loop iteration. How should I do that? Maybe I need something like individual interval for systems to run? Like RenderingSystem running every Update while AI Systems are running each 100ms. Or maybe there is some better approach which I should use?

**Second question would be about about these AI Systems**

I understand how to make AI which will manage every unit completely individually. However I have somewhat simultaneous pathfinding for all units which will do:

1. Mark units that should start moving as 'moving'.
2. Find path for every 'moving' unit to it's target (basically closest enemy). All 'moving' units aren't considered as obstacles for path but all not-'moving' units considered as obstacles.
3. Try to move every unit one step at it's path. If can't make step (someone is already standing there) then mark path as invalid (to recalculate at next AI iteration) and move one step in direction of target (if there is free nodes).
4. Mark all 'moving' units as not-'moving'

Besides there is addition: 3. Before making step we will check if we have enemy around us and instead of moving we will attack that enemy.

So, one AI iteration **required** to give action to each unit which will be run until it finishes. Then AI should give next action.

How I can make that in Entity System approach? Because in ES all systems are run one-after-another where I need to "jump" beetween them freely. Or maybe I'm overcomplicating things and should do something different instead of "jumping" between systems?

# Answer
> RenderingSystem running every Update while AI Systems are running each 100ms.

This shouldn't be a problem. For example, simply have your AI systems accumulate the delta passed to them, and only take action when it exceeds 100ms. I.e. four (dramatically unstable fps) loops could look like this:

```
aisystem.update(20ms) -> 20ms
aisystem.update(21ms) -> 41ms
aisystem.update(60ms) -> 101ms, take action -> 1ms
aisystem.update(20ms) -> 21ms

```

Most likely this is not the best way to go about it, but it is one possible implementation.

> Or maybe I'm overcomplicating things and should do something different instead of "jumping" between systems?

Correct, you don't want to be jumping between systems. The way I see it, you described one system, not a group of systems. This one system could be called something like `AiMovementSystem`. And it simply does what you described in your question. I believe you are a bit confused with the definition of `System`. A `System` basically iterates through a group of `Entities` with correct `Components` -- you don't have a movement system for each entity that should move.
> 0 votes

---
Tags: ai, component-based, entity-system, turn-based
---