# Question
Title: Can't load model using ContentTypeReader
I'm writing a game where I want to use ContentTypeReader. While loading my model like this:

```
terrain = Content.Load<Model>("Text/terrain");

```

I get following error:

```
Error loading "Text\terrain". Cannot find ContentTypeReader
AdventureGame.World.HeightMapInfoReader,AdventureGame,Version=1.0.0.0,Culture=neutral.

```

I've read that this kind of error can be caused by space's in assembly name so i've already removed them all but exception still occurs.

This is my content class:

```
[ContentTypeWriter]
public class HeightMapInfoWriter : ContentTypeWriter<HeightmapInfo>
{
    protected override void Write(ContentWriter output, HeightmapInfo value)
    {
        output.Write(value.getTerrainScale);
        output.Write(value.getHeight.GetLength(0));
        output.Write(value.getHeight.GetLength(1));

        foreach (float height in value.getHeight)
        {
            output.Write(height);
        }
    }

    public override string GetRuntimeType(TargetPlatform targetPlatform)
    {
        return
            "AdventureGame.World.Heightmap,AdventureGame,Version=1.0.0.0,Culture=neutral";
    }

    public override string GetRuntimeReader(TargetPlatform targetPlatform)
    {
        return
        "AdventureGame.World.HeightMapInfoReader,AdventureGame,Version=1.0.0.0,Culture=neutral";
    }
}

```

Does anyone meed that kind of error before?

# Answer
I can't be sure from the description but is your content-type-reader class in your content-pipline-extensions project? If so than that is probably the reason why it can't find it. The content-type-reader has to be available at runtime and thus has to be part of the game project or of one of the linked game library projects. Be sure to update your assembly name when you move your class and also, just to be sure, add spaces after the commas in the string that desribes where the class should be.

Edit: to be sure you have to exact QualifiedAssemblyName of a class write this piece of code:

```
string info = typeof(HeightMapInfoReader).AssemblyQualifiedName;

```

Of course this only works for a class in the same, or a referenced, assembly so you still have to copy the string in info and put it in the `ContentTypeWriter`'s `GetRunTimeReader` method harcoded but it makes sure you don't have typo's.
> 1 votes

---
Tags: xna, c#, .net, xna-content-pipeline
---


# Question
Title: Entity Component Systems with Model View Controller
Can the Model View Controller design pattern be used with non-OOP coding style, specifically with Entity Component System?

# Answer
> 5 votes
Four points to make, including an answer to your question:

1) There is nothing non-OOP about entity systems. Data-oriented programming is incompatible with bad over-use of poorly designed interfaces common to most mediocre OOP programming styles, but otherwise good data-oriented component systems (including entity systems) are quite naturally fit into an OOP model. You just end up defining a very different set of object models than you otherwise might. Bad OOP systems tend to define objects at boundaries that make sense to our physical real-world human experiences and linguistic taxonomic sensibilities, but which make no sense from a computer engineering standpoint. DOD will force you to use OOP better, which may be very different than what you're used to.

2) MVC is a horrible fit for almost all games, no matter how your engine is implemented internally. It just doesn't make a ton of sense, because individual game objects do not have multiple possible views or controllers, and the model has a strong influence on rendering and control (an MVC system inverts things such that the model has no say on visualization, the controllers drive everything, and views are pluggable by the controller to visualize a single model in multiple ways). MVC is great for data-focused traditional apps, not real-time interactive simulations like games.

3) You are falling into the trap of taking off-the-shelf design patterns and trying to fit them together. When you start out saying that the problem you want to solve is using design A and design B together, you're working backwards. Start out with the actual game you want to make. Then start coding that exact game. If and only if you run into a problem should you start asking yourself if a design patten might solve that specific problem.

4) In answer to your actual question: yes, it's possible to use MVC and entity systems. It'll be an awkward fit, but you can make it work. You can make *anything* work, because this is the world of software, and we aren't limited by any physical laws of the universe. You're free to make any architecture you want. More specifically, it'll largely boil down to using the entity system as your Model, your game logic/scripts as your Controller, and the rendering engine (with some non-MVC integration with the ES and scripts, as per my point 2 above) as your View.

---
Tags: entity-system, oop, mvc
---


title: Sweep and Prune vs Quad Tree

text:
# Question
Title: Sweep and Prune vs Quad Tree
I need some broad phase algorithm for my 2d game (shmup, bullet hell). Does one or another solution have any major advantages?

# Answer
> 1 votes
The two algorithms you have named are designed for arbitrarily large 3d worlds. While they can be adapted to a 2d shooter, there are simpler methods for the simpler environment.

For a 2d shooter I would use some variation of the blockmap concept used in DOOM - a grid of lists of objects that intersect each cell in the grid. Update the grid on each frame, and you only need to to collision detection on each set of objects in each cell.

---
Tags: collision-detection, quadtree
---


# Question
Title: UnityEngine.Vector2 does not contian a definition for "Set".... using futile
I am a bit lost, I am using futile and I am just trying to run the demo. But I keep getting UnityEngine.Vector2 does not contian a definition for "Set" in just one class, my using statments are:

```
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

```

When I look at the documents, I see that Set is a function http://docs.unity3d.com/Documentation/ScriptReference/Vector2.html I am using version 3.4.2 (in futile its happening in just the FAtlas class)

# Answer
> 1 votes
Looks like the Unity docs are for the most recent released version only. The Set method was added in version 3.5.0\*, which is why it isn't available in 3.4.2.

\*based on the information at http://docs.unity3d.com/Documentation/ScriptReference/40\_history.html#3.5.0

---
Tags: c#, unity
---


title: Making a Camera look at a target Vector

text:
# Question
Title: Making a Camera look at a target Vector
I have a camera that works as long as its stationary. Now I'm trying to create a child class of that camera class that will look at its target.

The new addition to the class is a method called SetTarget(). The method takes in a Vector3 target. The camera wont move but I need it to rotate to look at the target. If I just set the target, and then call CreateLookAt() (which takes in position, target, and up), when the object gets far enough away and underneath the camera, it suddenly flips right side up. So I need to transform the up vector, which currently always stays at Vector3.Up. I feel like this has something to do with taking the angle between the old direction vector and the new one (which I know can be expressed by target - position).

I feel like this is all really vague, so here's the code for my base camera class:

```
public class BasicCamera : Microsoft.Xna.Framework.GameComponent
    {
        public Matrix view { get; protected set; }
        public Matrix projection { get; protected set; }

        public Vector3 position { get; protected set; }
        public Vector3 direction { get; protected set; }
        public Vector3 up { get; protected set; }
        public Vector3 side
        {
            get { return Vector3.Cross(up, direction); }
            protected set { }
        }

        public BasicCamera(Game game, Vector3 position, Vector3 target, Vector3 up)
            : base(game)
        {
            this.position = position;
            this.direction = target - position;
            this.up = up;

            CreateLookAt();

            projection = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.PiOver4,
                (float)Game.Window.ClientBounds.Width /
                (float)Game.Window.ClientBounds.Height,
                1, 500);
        }

        public override void Update(GameTime gameTime)
        {
            // TODO: Add your update code here
            CreateLookAt();

            base.Update(gameTime);
        }
}

```

And this is the code for the class that extends the above class to look at its target.

```
class TargetedCamera : BasicCamera
    {
        public Vector3 target { get; protected set; }

        public TargetedCamera(Game game,
            Vector3 position,
            Vector3 target,
            Vector3 up)
            : base(game, position, target, up)
        {
            this.target = target;
        }

        public void SetTarget(Vector3 target)
        {
            direction = target - position;

        }

        protected override void CreateLookAt()
        {
            view = Matrix.CreateLookAt(position, target, up);
        }
    }

```

# Answer
Where do you want the camera's up to be when the object is below the camera? The roll of the camera can't be calculated when cross(dir, up) is zero and inaccuracies will result in mostly random roll values. You can cache the cameras up vector of the last frame and use it as up in CreateLookAt instead of your static up vector when cross(dir, world\_up) gets to small, but it depends on how you want it to behave.
> 1 votes

# Answer
Whenever you call Matrix.CreateLookAt(pos, targ, Up), use this for you up vector arg:

`Vector3 currentUp = Matix.Invert(lastFramesView).Up;`

and your camera wont flip anymore. By setting it to Vector3.Up it will always keep it's Y component (pitch) a positive number. When you look down and start to go inverted (up side down), it flips to keep the Y component positive. But a good thing about using Vector3.Up is that it also keeps the X & Z where it needs to be to keep the camera from any roll.

By using last frame's world space up vector, you remove the +Y pitch aspect so it will remain inverted but be careful, you also eliminate the roll prevention that Vector3.Up gave you.
> 0 votes

---
Tags: xna, camera
---


title: Animated Models in XNA

text:
# Question
Title: Animated Models in XNA
I've been using XNA for 2D games for awhile, and I am just learning 3D now. I have a question, which seems like it should be fairly basic. As I understand it, I make a model in Maya (or whatever) and have some animations in it (walk, jump, etc.). How do I take that model, and put it in my game, and have it run the animation to walk? Thanks!

# Answer
Take a look at the XNA code samples: http://xbox.create.msdn.com/en-US/education/catalog/sample/skinned\_model
> 1 votes

---
Tags: xna-4.0, models, maya
---


# Question
Title: Most suited technology for browser games?
I was thinking about making a 2D MMO which I would in the long run support on various plattforms like desktop, mac, browser, android and ios.

The server will be c++/linux based and the first client would go in the browser. So I have done some research and found that webgl and flash 11 support hardware accelerated rendering, I saw some other things like normal HTML5 painting.

So my question is, which technology should I use for such a project? My main goal would be that the users have a hassle free experience using what there hardware can give them with hardware acceleration. And the client should work on the most basic out-of-the-box pc's that any casual pc or mac user has. And another criteria would be that it should be developer friendly. I've messed with webgl abit for example and that would require writing a engine from scratch - which is acceptable but not preferred. Also, in case of non-actionscript, which kind language is most prefered in terms of speed and flexability. I'm not to fond of javascript due to the garbage collector but have learned to work around it.

Thank you for you time.

# Answer
The best technology IMHO is HTML5. Because it has got some good support already and will be getting more very soon plus adobe is deprecating Flash.

http://blogs.adobe.com/conversations/2011/11/flash-focus.html

For 2D development, you dont need WebGL or Hardware Acceleration (although it is a good thing) you can simply play around with the html5 canvas tag, i would recommend the following library: http://www.createjs.com/#!/EaselJS it is javascript but similar to AS3 which might be what you want, i am learning it and have found it to be very useful, please note that it is being sponsored by Adobe and Microsoft so hopefully it is a good investment to make.

I Hope it helps :) best of luck for whatever you are trying to achieve :)
> 3 votes

# Answer
Just use Flash or Unity. Give up html5. Any Unity or Flash 11 app converts to native client on IOS / Android.
> 0 votes

---
Tags: mmo, browser
---


title: How do I get level design practice?

text:
# Question
Title: How do I get level design practice?
I'm a game developer wannabe. I'm looking for 2D puzzle **games** that have a level creation tool to flex my level designer muscle.

I have Portal 2 (which has a level editor) but 3D is too daunting for me. I can think of Amazing Alex and Little Big Planet. What would you recommend?

# Answer
I tried to list some puzzle games with editing environments. I would also take a look at some flash gaming sites. Theese sites often feature small puzzle games and those games sometimes come with an editor.

**Some casual/puzzle games with editors:**

* Elastomania: Its a very simple game but with a very absorbing gaming experience. The game itself comes with an editor, where you can make crazy tracks your self.
* When you name amazing alex, try the ancestors of it (The Incredible Machine etc.). Some of those games enable you to create levels yourself.
* Boomblox for Wii comes with an ingame editor.
* Some versions of Bridge Builder also come with an level editor (or there are 3rd party editors for it).
> 4 votes

# Answer
Here are some of the ones I've seen around:

And one that I've used that help me transition easily into 3D:

Sketchup is pretty neat because it allows you to quickly make mockup maps (or a redesign for your bathroom lol). I used it to design a TF2 map before (3D I know), but it's really easy to use.
> 1 votes

# Answer
Here I will add games (mostly 2D) that include a level editor:

* Crayon Physics Deluxe
> -1 votes

---
Tags: level-design
---


# Question
Title: extrapolating object state based on updates
I have a networked multi-user collaborative application. To maintain a consistent virtual world, I send updates for objects from a master peer to a guest peer. The update state contains

x,y,z coordinates of object center and his rotation matrix(CHAI3d api used a 3x3 matrix) with 30Hz frequency.

I want to reduce this update rate and want to send with a reduced update rate. I want a predictor on both peers. When the predicted value is outside, say a error value of 10% in comparison to master peers objects original state the master peer triggers a state update.

Now for position I used velocity,position updates so that the guest peer can extrapolate position.

Like velocity for position what parameter should I use for rotation extrapolition?

# Answer
Angular velocity would seem the obvious choice based on what you're already doing. But unless the objects will be moving and turning with a constant velocity, acceleration on both counts might be a better predictor for any given velocity.
> 1 votes

---
Tags: client-server, state
---


# Question
Title: How do I run an iPhone GameSalad App on an iOS Device?
I have made a simple game application with GameSalad . It runs fine in the iPhone simulator after loading the GameSalad Viewer but doesn't work in the device as it gives a code signing error. If I change the IPA according to the device then the GameSalad Viewer crashes and the app does not run.

Does anyone have a solution for this?

# Answer
I installed Xcode 4.2 on MacOS X 10.6.8 and I can run the GameSalad viewer on my iPod Touch. The GameSalad viewer needs to be built in Xcode 4.2 or later.
> 2 votes

---
Tags: ios, gamesalad
---


# Question
Title: I know fundamental programming. But how do I get started in game development now?
I'm a 20 year old programming student. I know fundamental programming in BASIC, C, C++ and JAVA. What I wanted to ask is, where do I go from here? Are there any books that the community can mention that will help me develop a game or at least learn game development? I've had a lot of ideas and really want to make some sort of prototype to see if I'm suited for the industry.

I really don't mind learning any new languages but I need to know what I should begin with. A good book that will help with a little more understanding as I go up will be very helpful. Maybe a tutorial to develop some basic 2D games like a side-scroller, snake or pocket tanks in an easy to understand SDK?

I know that to get some credit under your belt, you need to be able to make a few games on your own.

Also, what platform should I start on? The PC, iOS or Android (as an introduction) for now. I don't want to get into high level game design just yet. Just something a bit basic to help out in future development.

Anything pointing me in the right direction will be really really helpful.

Edit: Also, I want to say that I'm looking towards this from a game designer's point of view more than a game programmer. I want suggestions on any SDKs or easy to use programs I can use to understand game design. Then delve deeper into the programming after that.

Not as employment but as developing your own games (for now).

# Answer
> 7 votes
Start making a game. That is how you get started in game development.

Asking other people how to start isn't starting. Searching Google isn't starting. Reading books isn't starting.

Actually writing code is starting. Making mock-ups using boards or cards or dice is starting. This is how you get started in game development, by starting to actually make a game, using whatever skills and talents you have right now. And slowly improving those skills and talents over time, while continuing to make games.

When I first started making games, I wrote them in AppleBasic. For a text display. No graphics at all. I made dozens of them like that. Competitive multiplayer arcade games, even, programmed entirely using text output, and a single keyboard for input. Now my games use shaders and touchscreen inputs and are cross-platform and all, but.. that's not required. Especially when you're just starting.

If you want to start making games, then you have to make games. Anything else -- particularly fixating on learning to do things "the right way" (as determined by what techniques are trendy this week) -- is just procrastination, and counter-productive.

---
Tags: books, education
---


# Question
Title: convert orientation vec3 to a rotation matrix
I've got a normalized vec3 that represents an orientation.

Each frame of animation, an object's orientation changes slightly, so I add a delta vector to the orientation vector and then normalize to find the new orientation.

I'd like to convert the vec3 that represents an orientation into a rotation matrix that I can use to orient my object.

If it helps, my object is a cone, and I'd like to rotate it about the pointy end, not from its center :)

PS I know I should use quaternions because of the gimbal lock problem. If someone can explain quats too, that'd be great :)

# Answer
Your problem is under-constrained, so there are a lot of possible solutions.

My suggestion is to see your `vec3` as the result of rotating vector `[1 0 0]` by φ around axis Y then by θ around axis Z. This is the latitude/longitude notation. The corresponding transformation matrix is:

```
|cosθ cosφ   -sinθ   -cosθ sinφ|
|sinθ cosφ    cosθ   -sinθ sinφ|
|   sinφ       0         cosφ  |

```

See the first column? That’s your `vec3`, since it’s the image of `[1 0 0]`. So the good thing is that we already know a lot of the matrix values.

The following code computes the remaining values:

```
mat3 rotation_matrix(vec3 v)
{
    /* Find cosφ and sinφ */
    float c1 = sqrt(v.x * v.x + v.y * v.y);
    float s1 = v.z;
    /* Find cosθ and sinθ; if gimbal lock, choose (1,0) arbitrarily */
    float c2 = c1 ? v1.x / c1 : 1.0;
    float s2 = c1 ? v1.y / c1 : 0.0;

    return mat3(v.x, -s2, -s1*c2,
                v.y,  c2, -s1*s2,
                v.z,   0,     c1);
}

```

Be careful with the last line, it may need a transposition depending on how your matrix class works.
> 5 votes

# Answer
A single vector only represents a direction. It sounds like gimbal lock will not be a problem in your case.

First you need to select an up vector to really define an orientation instead of a direction. You can start with the world's up vector and than use the last frames up vector from there on. Now you can calculate a side vector using the cross product and correct the up vector to ensure you have an orthonormal basis. To get the rotation matrix you just put these three vectors into a matrix's rows or columns depending on your coordinate system and used matrix convention.

```
Vec3 forward = your_rotation;
Vec3 up;
Vec3 side;

side = cross(forward, last_up);
if( side.GetLengthSq() < 0.001f )
{
  side = cross(forward, world_up);
  if( side.GetLengthSq() < 0.001f )
    side = cross(forward, world_side);
}

side.Normalize();
up = cross( forward, side );

// example, depends solely on the matrix format and coordinate space used
Matrix3 rotation( forward, side, up );

```

The easier way is to use a lookat function which does exactly the same and is provided with most engines and render APIs.
> 4 votes

---
Tags: mathematics, matrix, vector, orientation
---


title: Why does CameraZ=0 result in no render?

text:
# Question
Title: Why does CameraZ=0 result in no render?
I am trying to draw simple model, but I am experiencing strange error. When I use this View matrix:

```
Matrix.CreateLookAt(new Vector3(0, 200, 1), new Vector3(0, 0, 0), Vector3.Up);

```

my model is drawn correctly. But when I set camera position Z to 0 like this:

```
Matrix.CreateLookAt(new Vector3(0, 200, 0), new Vector3(0, 0, 0), Vector3.Up);

```

nothing is rendered. Why?

# Answer
> 6 votes
This is probably because your up vector is exactly opposite to the eye vector in the second example. This makes the cross product, which is used to calculate the view matrix unreliable (for a lack of a better word).

**EDIT:** If this is not enough information, then you should read up on how a view matrix is calculated. You need three things to do that, an eye vector, an up vector and the camera position. Then the cross product is used to calculate a 4x4 matrix which transforms your points from world space into camera space. In the `CreateLookAt` function, the eye vector is calculated simply by subtracting the target position from the camera position, then normalizing the result.

So in your second example, the calculated eye vector is pointing straight down, while the up vector is pointing straight up. This means that you can't calculate the cross product between the eye vector and the up vector, which means that the view matrix can't be constructed. I say "can't", it can, but you get errors.

---
Tags: c#, xna-4.0, camera
---


title: Octrees and Vertex Buffer Objects

text:
# Question
Title: Octrees and Vertex Buffer Objects
As many others I want to code a game with a voxel based terrain. The data is represented by voxels which are rendered using triangles. I head of two different approaches and want to combine them.

First, I could once divide the space in chunks of a fixed size like many games do. What I could do now is to generate a polygon shape for each chunk and store that in a vertex buffer object (vbo). Each time a voxel changes, the polygon and vbo of its chunk is recreated. Additionally it is easy to dynamically load and reload parts of the terrain.

Another approach would be to use octrees and divide the space in eight cubes which are divided again and again. So I could efficiently render the terrain because I don't have to go deeper in a solid cube and can draw that as a single one (with a repeated texture).

What I like to use for my game is an octree datastructure. But I can't imagine how to use vbos with that. How is that done, or is this impossible?

# Answer
> 2 votes
You might want to take a look at sparse voxel octrees and you should be able to find some implementations.

You want a dynamic VBO. Every frame, you work out which boxes in the octree you want to draw, calculate the position of the box's corners, add them to the dynamic vbo as vertices and create a supporting index buffer to detail which points join to which other points to make the triangles for the box.

You can add texture information to each box and create separate lists for each texture. You can also use one giant texture sheet and one giant VBO, it just means generating the texture coordinates for each vertex a bit differently.

You can also do some culling tricks here to avoid adding points and indices for parts you can't see (don't add polygons for visible boxes touching other visible, non-transparent boxes on all sides, don't add box faces which touch other visible boxes etc).

You can use a different octree for each chunk and you don't need to rebuild the vertex buffer if you didn't change the octree in the last frame, but if you are using heavy culling in the tree then you need to rebuild when the camera moves.

---
Tags: opengl, terrain, voxels, vbo, octree
---


# Question
Title: can a guy with embedded system background go into game development
Well, I finished my Masters in Embedded Systems, and I am working in GUI development, and working with graphic tools and images and GUI's keep me glued to my seat more than working on code for MUP/MUC . And I want to give game development a Fair chance, try out developing a game from scratch using basic libraries then tryout the same in a free/open source game engine and there is a good chance I may fall in love with it, but it is poissible for a person with an Electrical and Electronics Bachelors and Embedded Systems Masters ( just a years experience in the field) go into game development and be successful in the profession.

And I asked the same question @ stackoverflow.com (wrong place to ask ) https://stackoverflow.com/questions/13794822/can-a-guy-with-embedded-system-background-go-into-game-development/13794943#13794943

And I received good but a very generic answer. I would be happy to know the actual pro's and con's of a master's in embedded systems migrating to Game Dev

And I am extremely sorry for asking the same question for the third time but I really did not know that stackoverflow had so many sister sites, So a really big sorry, and an even bigger thank you!

# Answer
> No, you can't make a game.
>
> My logic is this: if you could make a game, you'd be too busy making a game for you to want to waste your time by posting a question asking strangers on the internet whether or not you can make a game. Therefore, by process of elimination, you must not be able to make a game.

If you want to make a game, that's great -- do it! I can highly recommend game making as a rewarding creative outlet. But asking other people whether it's going to be possible for you is just pointless procrastination. And you're not going to finish a game by procrastinating.

So my advice for a happy and successful life: less asking for permission from internet strangers. More actually doing the things you want to do.
> 1 votes

# Answer
Yes, yes, and yes. I work on embedded stuff during the day and games at night for fun. Your background can give you some advantages. For example, you're used to writing code that has to meet tight timing deadlines within very limited resources. Also, you should be able to pick up GPU programming, since you've worked with similar hardware.
Good Luck!
> 1 votes

# Answer
As an embedded engineer you have some coding experience that is surely beneficial in terms of solving challenging design scenarios in game development. However, you would also need to brush up more on OOP languages as well as familiarise yourself with the tools and assets that a game programmer would have to interface with in code.

I highly suggest you try to design and code a simple but interesting game, and see if it's really something you'd enjoy doing. And it'd be good for portfolio, i think?

just my two cents as an EE engineer hobbying in game dev.
> 0 votes

---
Tags: game-design
---


title: fragment shader with SNORM textures

text:
# Question
Title: fragment shader with SNORM textures
I want to apply SNORM texture by using GL\_TEXTURE\_3D as a target, what will be the fragment shader for the same? Also, what should be the data type of texture data?

# Answer
When using `RGBA_SNORM` you should use `GL_BYTE` with four components per texel to fill it.

It is basically the same as normal UNORM textures only that you get a value between `-1.0` and `1.0` when sampling. The signed byte value is mapped -127 -\> -1.0 and +127 -\> 1.0. -128 is dropped.

Sampler type is sampler3D (Floating-point also covers normalized integer formats).
> 1 votes

---
Tags: opengl, textures, glsl
---


# Question
Title: How are games created for different platforms?
How are games created for different platforms?

For example, Call of Duty: Modern Warfare 3 is available on PS3, Xbox 360, Wii and PC.

Are they completely reprogrammed with no common code? Is there any intermediate code?

# Answer
> 11 votes
Most production level game engines have what is known as a Hardware Abstraction Layer. This is a generic API that the game engine can use to talk with hardware with out having to know which hardware that is. They just call SoundManager.PlaySFX(SFX\_ID) or the like. Underneath in the sound manager however it will know which hardware its actually working on and make the appropriate calls to get the sound effect to play.

This allows the engine to be developed using that layer of abstraction so it can run on any system provided an API is provided for that hardware that matches the abstraction. EDIT: As noted by Johnathan, an API for each platform you want to run on is required. And to Trevor's point, when moving from a high memory system to a low memory (Worst for me was PS3 to PSP) you may have to tackle the different hardware limitations. Luckily for me I have not had to rewrite an entire system because of a platform, but I have had to go through and optimize objects to take up less of a foot print.

The other side of things is in the art area where resolutions of textures or models and the like are different. The assets of the game can be built towards a specific target so a PC gets its wav files for its sound effects while they are turned into the specific formats that the PS3 support and the like.

Hope this helps.

# Answer
> 3 votes
The other answers spell things out in the ideal cases. Most code is common for games, and a clean abstraction layer is used for hardware/platform dependent parts.

However, many games have ports done by an outsourced company, and code diverges significantly. This is especially true with the consoles, but also common of ports to OSX or Linux from Windows.

On consoles, the hardware is different enough that often entire chunks of the core rendering (and rarely also other systems) must be completely rewritten. On the PC you can jut abstract over D3D and OpenGL, as the OS APIs differ but all the PC hardware is roughly the same.

On the console space, you might find that your super efficient gorgeous rendering engine is outright impossible to port directly over to a different console, since the GPU capabilities are so different and you literally need to squeeze out every last percentage of performance to get 7 year old hardware to run your modern game. You can easily find cases where the lighting passss that work best on the XBox are horrendously slow on the PS3, and where the best approach on the PS3 dogs on the XBox. The other hardware and platform differences (eg the SPUs on the PS3 vs the tri-core CPU of the XBox) make it very difficult to rely on a simple thin hardware abstraction layer as your only platform-dependent code path.

Since each platform also requires an extensive amount of expertise to utilize it properly, many games require a specialized outsourced porting company to bring the game to additional platforms. In the PC space you can sometimes find solo developers who do the ports (like Ryan "icculus" Gordon who does many Linux game ports; straight forward work usually, changing D3D to GL and Win32 to POSIX/SDL), while in the console space there are companies with all teams to do rather massive porting work to larger games.

Ports to some platforms do require almost complete rewrites or asset redesigns. The Wii ports of Call of Duty for instance where done by an outsourced company, and everything - including the art assets - had to be redone to fit within the constraints of the Wii's very limited hardware. The Wii doesn't even have shaders, for instance, so simply reusing the same engine and effects/materials was outright impossible, and the limited memory and CPU/GPU required smaller textures and less details models, plus gameplay limitations and so on. Ports to mobile platforms likewise are typically entirely rewritten, usually by a third party.

Newer engines make it easier to port between platforms, but larger games typically still need to update sizable portions of their code and redo many assets to change from more capable PC platforms and consoles to more restricted platforms.

# Answer
> 2 votes
James reponse only relates to PC and not for the implementation on the specific platforms.
While all engines abstract the platform for the far majority of the game code, some parts have to be written per platform. This includes all I/O including network, rendering, audio, device input & I think video output.
Compare the rendering code for say Unreal on the Xbox and PS3. The Xbox uses the Xbox DirectX version, while the PS3 uses libgcm (the OpenGl library is too slow). To simplify it a bit, on all platforms the gameplay programmers only see a "AudioSystem.PlaySound(*SoundName here*), while for each platform they function internally would call the platforms API for sound output.
See also Tatrad's comment for more programming.

---
Tags: xbox360, cross-platform, playstation3, wii
---


title: Suitable SDK to develop quick game?

text:
# Question
Title: Suitable SDK to develop quick game?
I'm currently undertaking a personal project at home that I need to turn around inside the next few months (which working full time and still learning programming makes it a tad difficult). I'm looking for suggestions on SDK's or tools (preferably free or that come with games, similar to steam tools) that I can use to develop a "game". I'm OK with coding but have no 3D development skills at all.

I've very little experience with mod tools or SDK's at all but I'm hoping someone can point me in the direction of one that does the following:

* A decent library of prefab 3D models to build scenes.
* Ability to add scripting to the scene

I've used Unity before and would prefer to continue to do so however I really have the worst 3D skills imaginable and can't waste time learning them.

I'd be looking for pre-fab items that are both industrial and possibly more lush environments (trees etc). If it makes any difference (due to licencing and what-not) I **WILL NOT** be selling this game or marketing it in any way and I am a University Student if any places do educations licences.

Another alternative would be to source free 3d models elsewhere but again while I'm still learning I have no idea where to look if someone could point me in the right direction I'll do the rest of the digging.

Thanks

# Answer
> 8 votes
Open Source Game SDK/frameworks/Engines may help you (for educational purposes and other purposes, for example to develop game quicker)

Unity has 3D Game Development Student Version - **Unity - Studica**

Regarding 3D, Unity is one of the best. You can use the **Free Unity Indie Package**

Also others

**EDIT :**

For free unity 3d character models, followings may help you

Resources

# Answer
> 2 votes
Are you looking for SDKs with large model packs? I don't think that happens.

However, you can look at the strongly integrated Unity Asset Store (which does have free items like this beautiful zombie). For XNA, there is Turbosquid.

And of course there are other sites with collections of free 3D models; you probably could import them into Unity. You can have a look at:

# Answer
> 0 votes
Well, you were asking for a little SDK, so I won't list now every Engine/SDK.

The Irrlicht Engine may suitable for you.

---
Tags: 3d
---


title: Raycasting "fisheye effect" question

text:
# Question
Title: Raycasting "fisheye effect" question
Continuing my exploration of raycasting, I am very confused about how the correction of the fisheye effect works.

Looking at the screenshot below from the tutorial at permadi.com, the way I understand the cause of the fisheye effect is that the rays that are cast are distances from the player, rather than the distances perpendicular to the screen (or camera plane) which is what really needs to be displayed. The distance perpendicular to the screen then, in my world, should simply be the distance of Y coordinates (Py - Dy) assuming that the player is facing straight upwards.

Continuing the tutorial, this is exactly how it seems to be according to the below screenshot. From my point of view, the "distorted distance" below is the same as the distance PD calculated above, and what's labelled the "correct distance" below should be the same as Py - Dy. Yet, this clearly isn't the case according to the tutorial. My question is, WHY is this not the same? How could it not be? What am I understanding and visualizing wrong here?

UPDATE: Here's another perspective. The tutorial at lodev.org has another way of handling the fisheye effect which confuses me in the same way. This one relies on distance vectors more than angles and calculates the perpendicular distance to the wall according to the below formulas where mapX is the position of the player, rayPosX is the position of the wall that has been hit by a ray, and rayDirX is the direction of the ray (along with its Y counterparts of course). (1-stepX)/2 is simply a way of adding 1 if the ray is on the left side of the field of view. By the same logic as in the above tutorial, the perpendicular distance is simply mapX - rayPosX in my world. Why does rayDirX need to be divided to it?

```
//Calculate distance projected on camera direction (oblique distance will give fisheye effect!)
if (side == 0)
      perpWallDist = fabs((mapX - rayPosX + (1 - stepX) / 2) / rayDirX);
else
      perpWallDist = fabs((mapY - rayPosY + (1 - stepY) / 2) / rayDirY);

```

# Answer
> 1 votes
I understand it well enough now. What I described in the question only applies when facing perfectly upwards/downwards or to the left/right. When the player faces any other direction than this however, you of course have to convert the X or Y distance to the larger, real perpendicular distance of the camera plane, hence the additions to the formulas. I knew it was simple!

---
Tags: raycasting, trigonometry
---


# Question
Title: Error when using Environment.SpecialFolder.Desktop
I'm trying to get the current location of the Desktop so that I can automate a few things in my game. The current problem though is that following line doesn't work after I publish but it works in visual studios 2010.

```
Environment.GetFolderPath(Environment.SpecialFolder.Desktop)

```

I was wondering if there is a way around this.

# Answer
It looks like Environment.SpecialFolder.Desktop is not supported by the XNA Framework.

The table here: http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx

Shows the first column indicating if the XNA Framework supports it.

Supported:

* ApplicationData
* Favorites
* Programs
* StartMenu
* Startup
* Personal
> 1 votes

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


title: Scripting for a C#, multiplayer game

text:
# Question
Title: Scripting for a C#, multiplayer game
I have a multiplayer game written in C# and we've recently been creating a lot of content but have been looking for a way to give our entities customization logic that the designers can hook into. I took a look at this post. With something like this in mind (using C# as a scripting language); I have a few questions.

1. Would one embed the script itself in the entity object before persisting to it to the disk? Is this okay?
2. Would I compile once per scripting then - this seems like a lot of overhead to store all these compiled Assemblies to execute.

Any general advice on how to do thigns is welcome, too. These entities are generated on the fly inside the editor and could be composed of a lot of different things.

# Answer
> 1) Would one embed the script itself in the entity object before persisting to it to the disk? Is this okay?

You'll get cleaner diffs in your version control and encourage reusable scripts by providing the actual script out-of-line and having the entity merely store, say, a filename and script parameters. Storing the script in the entity itself is viable however.

> 2) Would I compile once per scripting then - this seems like a lot of overhead to store all these compiled Assemblies to execute.

You're looking at a handful of kilobytes on disk per assembly if they're small, and I'd imagine a similarly small runtime overhead. While there are possible scaling concerns (loading 1000s of scripts may have some inefficiencies) you can always start to batch up assemblies at a later date if (not when) you encounter problems. An assembly per script is a simple enough starting point, and as long as you avoid tying large swaths of your codebase to an assumption that will always be the case, you should be fine (just centralize the actual loading of assemblies and extraction of types in one place instead of doing it ad-hoc.)

A bigger concern is if you want to let scripts interact with each other directly 1000 scripts all referencing each other is a PITA to untangle even without circular references: in that case you might prefer to compile, say, on a per-level basis (or just have a single global scripting assembly.) Of course, that might be trending towards putting too much logic in scripts that belongs at a more core engine level.
> 6 votes

---
Tags: c#, multiplayer, server, scripting
---


title: OpenGL: Where shoud I place shaders?

text:
# Question
Title: OpenGL: Where shoud I place shaders?
I'm trying to learn OpenGL ES 2.0 and I'm wondering what is the most common practice to "manage" shaders.
I'm asking this question because in the examples I've found (like the one included in the API Demo provided with the android sdk), I usually see everything inside the GLRenderer class and I'd rather separate things so I can have, for example, a GLImage object that I can reuse whenever I want to draw a textured quad (I'm focusing on 2D only at the moment), just like I had in my OpenGL ES 1.0 code. In almost every example I've found, shaders are just defined as class attributes. For example:

```
public class Square {

public final String vertexShader =
        "uniform mat4 uMVPMatrix;\n" +
        "attribute vec4 aPosition;\n" +
        "attribute vec4 aColor;\n" +
        "varying vec4 vColor;\n" +
        "void main() {\n" +
        "  gl_Position = uMVPMatrix * aPosition;\n" +
        "  vColor = aColor;\n" +
        "}\n";

public final String fragmentShader =
        "precision mediump float;\n" +
        "varying vec4 vColor;\n" +
        "void main() {\n" +
        "  gl_FragColor = vColor;\n" +
        "}\n";
// ...
}

```

I apologize in advance if some of these questions are dumb, but I've never worked with shaders before.

1) Is the above code the common way to define shaders (public final class properties)?
2) Should I have a separate Shader class?
3) If shaders are defined outside the class that uses them, how would I know the names of their attributes (e.g. "aColor" in the following piece of code) so I can bind them?

```
colorHandle = GLES20.glGetAttribLocation(program, "aColor");

```

# Answer
> 16 votes
I've always disliked that way of defining shaders (in a string). I prefer to do mine in a text file and read it in when loading. Defining it in a string is annoying for debugging and it just looks messy to me. It's just so much easier to be able to type it out and see it formatted like it should be, instead of inside a string.

I also have a separate class that has common shader functionality, like reading in shaders and printing logging info for shader debugging.

Where ever the shaders are defined, you can access the names just like you do in your example. Using the string literal is acceptable for shaders since those values are unlikely to change once you've implemented them.

However, in the end it's up to you. The way you're currently doing it works great, if it's not causing you any troubles.

# Answer
> 8 votes
Shader (and thus material) management is a rather tricky problem you run into when your graphics system gets more complex and you notice hard coding every shader would lead into massive code duplication. Here's a few alternative ways to solve it:

* Small examples where there are only a couple of shaders tend to hard-code them as strings to avoid file handling as Jari Komppa commented
* Better is to use separate files where you can have syntax highlighting and proper formatting. You can also code a simple debug system which watches changes in those files and apply the modified shader on-the-fly while your game is running.
* When the material count increases, a shader generator becomes almost a necessity. Basically you define common snippets like "fragment shader normal mapping snippet" and compose your complete shaders by including the desired components.
    + You could use hard-coded string snippets, but that gets really messy fast, so once again files are a good idea.
    + You can either have bits of code in separate files (or same) or alternatively use *ubershader* / *supershader* where you use the preprocessor (or uniform flags) to enable/disable stuff.

As for the attribute and uniform names and such, you just use a consistent naming across all the shaders.

---
Tags: opengl, shaders, opengl-es2
---


# Question
Title: Trade offs of linking versus skinning geometry
What are the trade offs between inherent in linking geometry to a node versus using skinned geometry?

Specifically:

* What capabilities do you gain / lose from using each method?
* What are the performance impacts of doing one over the other?
* What are the specific situations where you would want to do one over the other?

In addition, do the answers to these questions tend to be engine specific? If so, how much?

# Answer
> 1 votes
By "linking" do you mean having separate objects moving attached to a frame of some sort?

If so, this is what I've heard called "segmented mesh," and I first remember noticing it in Tomb Raider. Indeed- this is what first prompted me to start researching skinning because I realized that if you just had polygons between the segments it would (ok might) look a lot better. It would certainly look fancier.

Modern skinning though uses some number of weights on each vertex. Therefore it is much more expensive to render the objects, since you're transforming each vertex by a number of matrices and then doing a weighted sum, as opposed to just transforming the vertex by one matrix. (Which as it turns out is how our first-gen skinner worked, all verts had one weight, so the "joint faces" were the only ones that would deform.)

Capabilities gained or lost? The only difference in the end result is how they look.

Specific situations where I'd use one or the other? I'd use skinning if the jointed look didn't work or was otherwise noticeable and undesirable.

# Answer
> 0 votes
The skinning deformation calculations can be done in the vertex shader. A model created from separate rigid parts linked to a transformation hierarchy needs to be drawn with multiple draw calls, updating the transform matrix in between each.

So unless you're doing the skinning in software, skinned models will most likely perform better!

Skinning lets you do smooth deformation between joints. If you just want the look of linked animation, it can be emulated by assigning very simple skinning weights.

Linking allows you to easily connect separate models in new configurations, such as attaching weapons to a character.

---
Tags: animation, performance
---


# Question
Title: Scale a normalized 2D vector always to the same length
For any normalized 2D vector, except for ( 0, 0 ), how would I scale the vector to always be the same length?

For example:

```
int length = 10;

vector v = vector( 0.1, 0.5 );
vector v2 = vector( 0.3, 0.8 );

// Scale v to be length of 10
// Scale v2 to be length of 10

```

# Answer
You mean like this?

```
length = sqrt(v.x * v.x + v.y * v.y);

// normalize vector
v.x /= length;
v.y /= length;

// increase vector size
v.x *= 10
v.y *= 10

```
> 9 votes

# Answer
A normalized vector, by definition, has length 1. To scale it to length 10, you need to multiply it by 10.

(To multiply a vector by a number, multiply every component of the vector by the number. Depending on the language you use, just writing `vector = vector * number` may do that automatically, or there may at least be a library function or method to do that.)

By the way, the vectors in your example code are not normalized — their length is not 1. To normalize them, do as Gajoo suggests, i.e. divide them by their length. Again, your language or vector library may already provide a function to do that.
> 7 votes

# Answer
Normalised vectors have the same length by definition: one. If you want to scale them to an arbitrary length *L* instead, multiply them (or their components) by *L*. Note that the examples you have provided are not normalised vectors. To normalise, divide the vectors by their magnitude.

For example (component-wise, as I do not know the extent of vector algebra support in your environment):

```
int targetlength = 10;
vector v = vector( 0.1, 0.5 );
float vMagnitude = sqrt(v.x*v.x + v.y*v.y);
v.x = targetlength * v.x / vMagnitude;
v.y = targetlength * v.y / vMagnitude;

// v = ( 1.96, 9.81 )

```

Or with vector algebra:

```
int targetlength = 10;
vector v = vector( 0.1, 0.5 );
v = targetlength * v / v.length;

```
> 3 votes

---
Tags: 2d, mathematics, vector
---


title: Unity3d import file on iOS device

text:
# Question
Title: Unity3d import file on iOS device
im trying to figure out how to recall an external file in runtime on iOS device. I've already tried using Application.data+"/Raw/MY\_FILE", with Application.streamingAssetsPath+"/MY\_FILE", and with Application.persistentData+"/Raw/MY\_FILE" (but, if i dont get wrong, persistentData is used for write, i need just of reading).

Please, anyone can help me?

# Answer
> 1 votes
Have you added your file inside a folder named "**StreamingAssets**" in Unity Editor?

So, you can get it in runtime using this path: **Application.dataPath + "/Raw/YOUR FILE NAME"**.

More info: Streaming Assets

---
Tags: c#, unity, ios
---


# Question
Title: Android / IPhone / Desktop C++ Game Template
I was wondering if anyone has come across any articles detailing how to set up a basic game in C++ for use in Android / IPhone / Desktop applications.

My thoughts just now are that I would like to make my game as a library and have a different project for each device which just interfaces with this library. You know the kind of thing, bootstrap the program, call some library initialize, load and run routines and occasionally pass some information to the library like input. I was hoping someone would have made a template for this kind of thing but I just had no luck finding one.

It seems to me that it's the kind of thing you really only have to do once, so I was hoping someone would have done it for me already.

# Answer
> 0 votes
Cocos2d-x will generate projects for each platform you wish to develop on and link it to some basic, shared C++ code.

While the intention of this is to get cocos2d-x projects up and running, there is nothing to stop you stripping all the cocos2d-x related code from your project and just doing your own thing.

You might want to keep some cocos2d-x things in the final project, like cocos2d-x features for getting user input, but because cocos2d-x is open source, you can always replace this.

# Answer
> 2 votes
You could try looking though the ludum dare site. Many of those games are basic, work with multiple OSes and are open source. Additionally, it's a regular thing to share what you already have prepared before the competition starts. That's a good place to look for boilerplate code.

# Answer
> 0 votes
I'm working on doing a simple template for OS X, Android and iPhone. It will be available in few days on my blog. The project should be easily portable on Windows and Linux because i use glfw.

---
Tags: c++, android, iphone
---


title: Rendering scaled-down card images

text:
# Question
Title: Rendering scaled-down card images
I have high-quality SVG card images, but they drastically lose their quality when I downsize them. I have tried two ways of rendering cards (using Inkscape and Imagemagics):

1) Render SVG to high-res PNG and resize it then:

```
inkscape -D --export-png=QS1024.png --export-width=1024 QS.svg
convert QS1024.png -filter Lanczos -sampling-factor 1x1 -resize 71x QS71.png

```

2) Render SVG to image of proper size at once:

```
inkscape -D --export-png=QS71.png --export-width=71 QS.svg

```

Both approaches generate blurry card images, which looks even worse than old Windows cards. What are the best way to generate smaller card images from SVG sources and not to loose their quality a lot?

**UPDATE:** I am using Inkscape to render SVG -\> PNG and ImageMagick then to downsize PNG. I've tried using convert -resize with couple of filters (Lanczos/Mitchell/etc), but result was pretty much the same.

Original:

71x raster:

# Answer
For best quality results, you should probably first render the SVG at high resolution and then scale it down, *using a good scaling algorithm*. For example, here's the result I got by taking your 256 × 357 px image and scaling it down to 71 × 99 pixels in GIMP using Lanczos3 resampling:

It looks noticably sharper than the version you got using ImageMagick:

I'm not sure *why* the difference should be so noticeable, since your ImageMagick command line also seems to specify Lanczos resampling, but it is. Perhaps ImageMagick is using some different variant of the algorithm than GIMP, or perhaps it simply doesn't use it when scaling images down.

(The GIMP version does suffer from one big problem: the bottom edge is cut off. To avoid such edge issues, it's often a good idea to render your images with a small amount of margin around them.)

The remaining "blurriness" in the images is due to the fact that the vertical and horizontal lines are not perfectly pixel-aligned. I wrote an answer about this at the Graphic Design Stack Exchange before, so I'll just link to it from here. While manually editing this many images is probably not practical (although I guess you could do it at least for the repetitive parts such as the card edges), you might want to give the PixelSnap Inkscape extension a try.

**Edit:** Here's the same card after applying PixelSnap:

The version on the left is a direct PNG export from Inkscape, the one on the right was exported at 16 times the target size and scaled down in GIMP using Lanczos3 resampling. Note that the dimensions of both versions are 72 × 100 px to avoid clipped edges. There are still some bits that could benefit from manual tweaking (tip: set up a 1 × 1 px grid in Inkscape, with a 0.5 × 0.5 px subgrid), but that's probably inevitable with such a complex image.
> 7 votes

---
Tags: graphics, image, card-game
---


# Question
Title: Server costs and back loading for mobile devices
A company approached me to design an MMO for the mobile platform and I have the perfect idea for them. My question is how much would a server for a FTP game that has both a PVE element and PVP cost? Also do you think that it would be better or is it even possible to back load the data onto the phones (trying to come up with some interesting way to back up the data in case of emergency). I don't want the game to be totally online reliant (I want to appeal to not only phone users but also iPod touch users) and for there to be an offline mode.

If you can't tell this is my first game besides simple projects I've done on the side. Any help would be greatly appreciated.

# Answer
> 1 votes
**About estimating the required server capacity**

Making any guess here is impossible without knowing very specific details about your game and your protocol.

Just some of the variables which have a huge impact are:

* how many users will be online at the same time?
* how resource-intense is your game per player?
* how much data does each user send to the server per minute?
* how much data do you have to send to each user per minute?
* How do these metrics scale with the number of users? When you have 100 connected users, do you need to send the data of everyone to everyone (which means 100 users do not create 100 times but 10.000 times as much load as a single one) or can you minimize this scaling issues by only sending data of those other players which are relevant for each user?

Making even vague estimates for any of these numbers without actually coding and measuring it requires a lot of experience and very detailed knowledge of the game concept.

**About offline play and storing data client-sided**

When you store data client-sided, you have to be aware that users will be able to manipulate that data and cheat! You can try to make it harder through encrypting it, but that will only slow them down for a few days, because your encryption key and algorithm must be somewhere in your application.

For that reason, offline play in a competitive multiplayer game is generally a very, very bad idea. When you want to stop people from cheating, then all calculations which are relevant for the gameplay must take place on the server. Anything which happens on the client can be manipulated by the user.

---
Tags: iphone, mmo, server, mobile
---


# Question
Title: So I have this idea for a videogame. How do I make sure it gets heard?
I was wondering how I could get a developer to hear about my idea. I don't really care if my idea gets "stolen", I only want it to be heard. So do you know how I could do this, or am I just being stupid? Again, I only want to know what the developer thinks of the idea, I'm not asking the developer to make it. Sorry if this is a stupid question.

# Answer
* Get enough rep, ask about it in chat here.
* Post your idea on reddit (for brutally honest feedback).
* Post your idea on gamedev.net (make sure to read this first).
* Pick some other popular game development site that's discussion oriented and post it there.
> 10 votes

---
Tags: game-industry
---


# Question
Title: Diamond shaped selection on a staggered iso map
I have a staggered isometric tile map and want to do a selection that aligns with the diamond shape of the tiles.

This is what I mean:

So I got two points on screen and their map cell coordinates. How do I iterate over all tiles that are within the selection?

What I got to help with this is a method that gets the neighboring tiles.

# Answer
I gave up on solving this with mathematics and chose a more algorithmic way to do it:

```
    stagStart = this.selection.start;
    stagEnd = this.selection.end;

    diaStart = this.staggeredToDiamond(this.selection.start);
    diaEnd = this.staggeredToDiamond(this.selection.end);

    //for calculating the distances we convert to diamond coordinates first
    deltaX = Math.abs(diaStart.x - diaEnd.x) + 1;
    deltaY = Math.abs(diaStart.y - diaEnd.y) + 1;

    //direction for x axis traversal
    if(diaEnd.x > diaStart.x) {
        directionX = TileEngine.SOUTH_EAST;
    } else {
        directionX = TileEngine.NORTH_WEST;
    }

    //direction for y axis traversal
    if(diaEnd.y > diaStart.y) {
        directionY = TileEngine.SOUTH_WEST;
    } else {
        directionY = TileEngine.NORTH_EAST;
    }

    beginY = stagStart;

    //walk along y axis since it's easy to iterate over
    for(i = 0; i < deltaY; i++) {

        currentX = beginY;
        //draw along x axis
        for(j = 0; j < deltaX; j++) {
            tile = this.mapToScreen(currentX);
            this.ctx.drawImage(this.tileset.tiles[3].image, tile.x, tile.y);
            currentX = this.nextTile(currentX, directionX);
        }

        beginY = this.nextTile(beginY, directionY);
    }

```
> 0 votes

# Answer
First off, you should be storing all the tiles in a normal square grid. This will make tasks like this a no-brainer. The only place your tiles should actually be diamond shaped is on screen. Any selections on screen utilize a `screenToWorld(x,y)` function and any world drawing uses a `worldToScreen(x,y)` function. Then you can easily take your two points from the selection rectangle and convert them both with `screenToWorld(x,y)`, then simply use them to step through your 2D array collecting tiles that are valid for selection.

If you're not reworking your entire coordinate system, you should at least make it consistent. Your `x` coordinates are shared by two adjacent tiles, while your `y` tiles are not.

See how going in the `x` direction it's red(5), red(5), blue(6), blue(6), red(7), red(7)? Then in the y direction it's blue(1), red(2), blue(3), red(4)?

This means it's very difficult to even iterate over the tiles in a consistent way.
> 5 votes

# Answer
I suggest changing the coordinate space too. But here is some untested code that should do the trick. p0Screen and p1Screen are the two points in screen space. ScreenX and ScreenY are two vectors that represent the screen space vector from one cell to the next in the two diagonal directions, eg 4/12 -\> 4/11 for screenX and 4/12 -\> 4/13 for screenY. The direction is not important as long as the length is correct.

In the inner loop you get the screen coordinate of each tile in the area.

```
Vec2Float p0Screen;
Vec2Float p1Screen;
Vec2Float screenX;
Vec2Float screenY;

Vec2Float deltaScreen = p1Screen - p0Screen;
float screenXLenRcp = 1.0f / screenX.GetLength();
float screenYLenRcp = 1.0f / screenY.GetLength();
Vec2Float screenXNorm = screenX * screenXLenRcp;
Vec2Float screenYNorm = screenY * screenYLenRcp;

Vec2Int delta;
delta.x = (int)(0.5f + dot( deltaScreen, screenXNorm ) * screenXLenRcp );
delta.y = (int)(0.5f + dot( deltaScreen, screenYNorm ) * screenYLenRcp );

Vec2Float deltaSign;
deltaSign.x = delta.x > 0 ? 1.0f : -1.0f;
deltaSign.y = delta.y > 0 ? 1.0f : -1.0f;

delta.x = abs( delta.x );
delta.y = abs( delta.y );

for( int y = 0; y <= delta.y; y++ )
{
    float sy = (float)y * deltaSign.y;
    Vec2Float screenDeltaY = sy * screenY;

    for( int x = 0; x <= delta.x; x++ )
    {
        float sx = (float)x * deltaSign.x;
        Vec2Float screenDeltaX = sx * screenX;
        Vec2Float tileScreen = p0Screen + screenDeltaX + screenDeltaY;
    }
}

```
> 2 votes

---
Tags: mathematics, isometric, tilemap
---


# Question
Title: Light following me around the room. Something is wrong with my shader!
I'm trying to do a spot (Blinn) light, with falloff and attenuation. It seems to be working OK except I have a bit of a space problem. That is, whenever I move the camera the light moves to maintain the same relative position, rather than changing with the camera. This results in the light moving around, i.e. not always falling on the same surfaces. It's as if there's a flashlight attached to the camera.

I'm transforming the lights beforehand into view space, so Light\_Position and Light\_Direction are already in eye space (I hope!). I made a little movie of what it looks like here:

My camera rotating around a point inside a box.

The light is fixed in the centre up and its "look at" point in a fixed position in front of it. As you can see, as the camera rotates around the origin (always looking at the centre), so don't think the box is rotating (!). The lighting follows it around. To start, some code. This is how I'm transforming the light into view space (it gets passed into the shader already in view space):

```
// Compute eye-space light position.

Math::Vector3d eyeSpacePosition = MyCamera->ViewMatrix() * MyLightPosition;

MyShaderVariables->Set(MyLightPositionIndex, eyeSpacePosition);

// Compute eye-space light direction vector.

Math::Vector3d eyeSpaceDirection = Math::Unit(MyLightLookAt - MyLightPosition);

MyCamera->ViewMatrixInverseTranspose().TransformNormal(eyeSpaceDirection);

MyShaderVariables->Set(MyLightDirectionIndex, eyeSpaceDirection);

```

Can anyone give me a clue as to what I'm doing wrong here? I think the light should remain looking at a fixed point on the box, regardless of the camera orientation.

Here are the vertex and pixel shaders:

```
///////////////////////////////////////////////////
// Vertex Shader
///////////////////////////////////////////////////

#version 420

///////////////////////////////////////////////////
// Uniform Buffer Structures
///////////////////////////////////////////////////

// Camera.

layout (std140) uniform Camera
{
    mat4 Camera_View;
    mat4 Camera_ViewInverseTranspose;
    mat4 Camera_Projection;
};

// Matrices per model.

layout (std140) uniform Model
{
    mat4 Model_World;
    mat4 Model_WorldView;
    mat4 Model_WorldViewInverseTranspose;
    mat4 Model_WorldViewProjection;
};

// Spotlight.

layout (std140) uniform OmniLight
{
    float Light_Intensity;
    vec3 Light_Position;
    vec3 Light_Direction;
    vec4 Light_Ambient_Colour;
    vec4 Light_Diffuse_Colour;
    vec4 Light_Specular_Colour;
    float Light_Attenuation_Min;
    float Light_Attenuation_Max;
    float Light_Cone_Min;
    float Light_Cone_Max;
};

///////////////////////////////////////////////////
// Streams (per vertex)
///////////////////////////////////////////////////

layout(location = 0) in vec3 attrib_Position;
layout(location = 1) in vec3 attrib_Normal;
layout(location = 2) in vec3 attrib_Tangent;
layout(location = 3) in vec3 attrib_BiNormal;
layout(location = 4) in vec2 attrib_Texture;

///////////////////////////////////////////////////
// Output streams (per vertex)
///////////////////////////////////////////////////

out vec3 attrib_Fragment_Normal;
out vec4 attrib_Fragment_Position;
out vec2 attrib_Fragment_Texture;
out vec3 attrib_Fragment_Light;
out vec3 attrib_Fragment_Eye;

///////////////////////////////////////////////////
// Main
///////////////////////////////////////////////////

void main()
{
    // Transform normal into eye space
    attrib_Fragment_Normal = (Model_WorldViewInverseTranspose * vec4(attrib_Normal, 0.0)).xyz;
    // Transform vertex into eye space (world * view * vertex = eye)
    vec4 position = Model_WorldView * vec4(attrib_Position, 1.0);
    // Compute vector from eye space vertex to light (light is in eye space already)
    attrib_Fragment_Light = Light_Position - position.xyz;
    // Compute vector from the vertex to the eye (which is now at the origin).
    attrib_Fragment_Eye = -position.xyz;
    // Output texture coord.
    attrib_Fragment_Texture = attrib_Texture;
    // Compute vertex position by applying camera projection.
    gl_Position = Camera_Projection * position;
}

```

and the pixel shader:

```
///////////////////////////////////////////////////
// Pixel Shader
///////////////////////////////////////////////////

#version 420

///////////////////////////////////////////////////
// Samplers
///////////////////////////////////////////////////

uniform sampler2D Map_Diffuse;

///////////////////////////////////////////////////
// Global Uniforms
///////////////////////////////////////////////////

// Material.

layout (std140) uniform Material
{
    vec4  Material_Ambient_Colour;
    vec4  Material_Diffuse_Colour;
    vec4  Material_Specular_Colour;
    vec4  Material_Emissive_Colour;
    float Material_Shininess;
    float Material_Strength;
};

// Spotlight.

layout (std140) uniform OmniLight
{
    float Light_Intensity;
    vec3 Light_Position;
    vec3 Light_Direction;
    vec4 Light_Ambient_Colour;
    vec4 Light_Diffuse_Colour;
    vec4 Light_Specular_Colour;
    float Light_Attenuation_Min;
    float Light_Attenuation_Max;
    float Light_Cone_Min;
    float Light_Cone_Max;
};

///////////////////////////////////////////////////
// Input streams (per vertex)
///////////////////////////////////////////////////

in vec3 attrib_Fragment_Normal;
in vec3 attrib_Fragment_Position;
in vec2 attrib_Fragment_Texture;
in vec3 attrib_Fragment_Light;
in vec3 attrib_Fragment_Eye;

///////////////////////////////////////////////////
// Result
///////////////////////////////////////////////////

out vec4 Out_Colour;

///////////////////////////////////////////////////
// Main
///////////////////////////////////////////////////

void main(void)
{
    // Compute N dot L.

    vec3 N = normalize(attrib_Fragment_Normal);
    vec3 L = normalize(attrib_Fragment_Light);
    vec3 E = normalize(attrib_Fragment_Eye);
    vec3 H = normalize(L + E);

    float NdotL = clamp(dot(L,N), 0.0, 1.0);
    float NdotH = clamp(dot(N,H), 0.0, 1.0);

    // Compute ambient term.

    vec4 ambient = Material_Ambient_Colour * Light_Ambient_Colour;

    // Diffuse.

    vec4 diffuse = texture2D(Map_Diffuse, attrib_Fragment_Texture) * Light_Diffuse_Colour * Material_Diffuse_Colour * NdotL;

    // Specular.

    float specularIntensity = pow(NdotH, Material_Shininess) * Material_Strength;

    vec4 specular = Light_Specular_Colour * Material_Specular_Colour * specularIntensity;

    // Light attenuation (so we don't have to use 1 - x, we step between Max and Min).

    float d = length(-attrib_Fragment_Light);
    float attenuation = smoothstep(Light_Attenuation_Max, Light_Attenuation_Min, d);

    // Adjust attenuation based on light cone.

    float LdotS = dot(-L, Light_Direction), CosI = Light_Cone_Min - Light_Cone_Max;

    attenuation *= clamp((LdotS - Light_Cone_Max) / CosI, 0.0, 1.0);

    // Final colour.

    Out_Colour = (ambient + diffuse + specular) * Light_Intensity * attenuation;
}

```

UPDATE:

I know this was a long time ago, but I thought I'd revisit it, because I've finally found the reason for the behaviour I was seeing. It was a fundamental misunderstanding and misuse of uniform buffers. I wasn't binding them to shader programs correctly. By chance it kind-of worked.

Yes, it took me a while and yes, I did give up on GLSL for a while because of it. Now I've nailed it, I'm back in business and OpenGL is back on the menu :).

# Answer
> 1 votes
* You do not use Light\_Position, nor do you fill attrib\_Fragment\_Light in the vertex shader.

Could it be that there is a line break missing?

```
// Compute vector from eye space vertex to light (light is in eye space already) attrib_Fragment_Light = Light_Position - position.xyz;

```

should be

```
// Compute vector from eye space vertex to light (light is in eye space already)
attrib_Fragment_Light = Light_Position - position.xyz;

```
* I don't know which framework you use. Are you sure

Math::Vector3d eyeSpacePosition = MyCamera-\>ViewMatrix() * MyLightPosition;

does apply translation, as Input and output are Vector3?

* Does TransformNormal do anything in addition to not applying translation/projection on the passed vector? After InverseTranspose a normal multiplication with w set to 0.0 should be sufficient.

MyCamera-\>ViewMatrixInverseTranspose().TransformNormal(eyeSpaceDirection);

**EDIT**

Does TransformNormal really transform the normal passed by reference or should it rather be:

```
eyeSpaceDirection = MyCamera->ViewMatrixInverseTranspose().TransformNormal(eyeSpaceDirection);

```

I did not think it through if any of these could lead to your problem, but some oddities:

length(-attrib\_Fragment\_Light) -\> the minus sign has no effect

Im not sure how Light\_Cone\_Min and Light\_Cone\_Max are filled, is Min bigger than Max, otherwise CosI will get negative which will destroy the angle attenuation

**EDIT2**

You said Light\_Attenuation\_Min \< Light\_Attenuation\_Max and Light\_Cone\_Min \< Light\_Cone\_Max:

* Smoothstep performs smooth Hermite interpolation between 0 and 1 when edge0 \< x \< edge1. Results are undefined if edge0 ≥ edge1.But you call it

smoothstep(Light\_Attenuation\_Max, Light\_Attenuation\_Min, d);

* CosI is always negative which sounds kind of odd as LdotS is bigger the nearer the fragment is to the center of the cone

---
Tags: shaders, glsl
---


# Question
Title: How do I enforce efficiency concerning thread granularity?
Lately, I've been thinking of ways to use multi-threading to improve the speed of different parts of a game engine. What confuses me is the appropriate granularity of threads, especially when dealing with single-instruction-multiple-data (SIMD) tasks.

Let's use line-of-sight detection as an example. Each AI actor must be able to detect objects of interest around them and mark them. There are three basic ways to go about this with multithreading:

1. Don't use threading at all.
2. Create a thread for each actor.
3. Create a thread for each actor-object combination.

Option 1 is obviously going to be the least efficient method; However, choosing between the next two options is more difficult.

Only using one thread per actor is still running through every object in series instead of in parallel. However, are CPU's able to create and join threads in the granularity posed in Option 3 efficiently?

It seems like that many calls to the OS could be really slow, and varying enormously between different hardware.

# Answer
> 5 votes
You forgot a very important variant in your list:

#4 Create a threadpool (size = number of physical CPUs) and distribute small tasks to them (e.g. each actor-object combination).

This assumes that the task at hand is CPU-bound. Hence there is nothing to win if you use more threads than there are CPUs. Using more threads only adds the overhead of thread scheduling. This also assumes, that you can split / join your tasks without to much locking overhead.

---
Tags: architecture, multithreading
---


title: XNA running slow when making a texture

text:
# Question
Title: XNA running slow when making a texture
I'm using XNA to test an image analysis algorithm for a robot. I made a simple 3D world that has a grass, a robot, and white lines (that are represent the course). The image analysis algorithm is a modification of the Hough line detection algorithm.

I have the game render 2 camera views to a render target in memory. One camera is a top down view of the robot going around the course, and the second camera is the view from the robot's perspective as it moves along. I take the rendertarget of the robot camera and convert it to a Color\[,\] so that I can do image analysis on it.

```
private Color[,] TextureTo2DArray(Texture2D texture, Color[] colors1D, Color[,]   colors2D)
    {
        texture.GetData(colors1D);
        for (int x = 0; x < texture.Width; x++)
        {
            for (int y = 0; y < texture.Height; y++)
            {
                colors2D[x, y] = colors1D[x + (y * texture.Width)];
            }
        }

        return colors2D;
    }

```

I want to overlay the results of the image analysis on the robot camera view. The first part of the image analysis is finding the white pixels. When I find the white pixels I create a bool\[,\] array showing which pixels were white and which were black. Then I want to convert it back into a texture so that I can overlay on the robot view.

When I try to create the new texture showing which ones pixels were white, then the game goes super slow (around 10 hz).

Can you give me some pointers as to what to do to make the game go faster. If I comment out this algorithm, then it goes back up to 60 hz.

```
private Texture2D GenerateTexturesFromBoolArray(bool[,] boolArray,Color[] colorMap, Texture2D textureToModify)
    {
        for(int i =0;i < screenWidth;i++)
        {
            for(int j =0;j<screenHeight;j++)
            {
                if (boolArray[i, j] == true)
                {
                    colorMap[i+(j*screenWidth)] = Color.Red;
                }
                else
                {
                    colorMap[i + (j * screenWidth)] = Color.Transparent;
                }
           }
    }

        textureToModify.SetData<Color>(colorMap);

        return textureToModify;
    }

```

Each Time I run draw, I must set the texture to null, so that I can modify it.

```
 public override void Draw(GameTime gameTime)
    {
        Vector2 topRightVector = ((SimulationMain)Game).spriteRectangleManager.topRightVector;
        Vector2 scaleFactor = ((SimulationMain)Game).config.scaleFactorScreenSizeToWindow;

        this.spriteBatch.Begin(); // Start the 2D drawing
        this.spriteBatch.Draw(this.textureFindWhite, topRightVector, null,
           Color.White, 0, Vector2.Zero, scaleFactor, SpriteEffects.None, 0);
        this.spriteBatch.End(); // Stop drawing.

        GraphicsDevice.Textures[0] = null;
    }

```

Thanks for the help,

Anthony G.

# Answer
To know the exact problem you should use a profiler but I can make an educated guess that the performance penalty comes from the call to `texture.GetData(colors1D);` in `TextureTo2DArray`.

As usual the excellent Shawn Hargreaves has written something about this:

> Normally, the CPU and GPU run in parallel. Framerate = max(CPU time, GPU time).
>
> If your code causes a pipeline stall, however, the processors must take turns to run while the other one sits idle. Yikes! Now framerate = CPU time + GPU time. In other words, programs that stall can be both CPU and GPU bound at the same time.
>
> The easiest way to cause a stall is to draw some graphics into a rendertarget, then GetData on the rendertarget texture to read the results back to the CPU. Think about what happens if you do this: Charles (the CPU) is processing your drawing calls. He has filled a piece of paper with instructions for his brother George (the GPU). Charles reaches an instruction that says "copy data from George back into this array". But the drawing instructions haven't actually been processed by George yet! Charles cannot just note down the GetData call on his piece of paper. The next instruction might use values from the array, so he needs that data right away. Charles has no option but to immediately hand the incomplete list of drawing instructions over to George, then wait around twiddling his thumbs in boredom until George has finished drawing everything, at which point Charles can resume processing the GetData instruction while George becomes idle.
>
> One of the great successes of the Direct3D API is how it hides the asynchronous nature of GPU hardware. Many graphics programmers are writing parallel code without even realizing it! But as soon as you try to read data back from GPU to CPU, all this parallelism is lost

http://blogs.msdn.com/b/shawnhar/archive/2008/04/14/stalling-the-pipeline.aspx

So it is generally not advisable to pipe data from the GPU back to the CPU.

Another problem is that processing individual pixels on the CPU is expensive. All modern GPUs calculate thousands of pixels at the same time but using the CPU its back to 1, 2, or 4 pixels. Remember inspecting a 1920x1080 image will mean 2073600 series of operations.

Now I don't know what the underlying problem is you're trying to solve by rendering a texture and inspecting if pixels are white but you're probably better off using some other way of abstracting this problem.
> 2 votes

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


title: Wall avoidance steering

text:
# Question
Title: Wall avoidance steering
I making a small steering simulator using the Reynolds boid algorithm. Now I want to add a wall avoidance feature. My walls are in 3D and defined using two points like that:

```
   ---------. P2
   |        |
P1 .---------

```

My agents have a velocity, a position, etc...

Could you tell me how to make avoidance with my agents?

```
Vector2D ReynoldsSteeringModel::repulsionFromWalls()
{
    Vector2D force;
    vector<Wall *> wallsList = walls();
    Point2D pos = self()->position();
    Vector2D velocity = self()->velocity();

    for (unsigned i=0; i<wallsList.size(); i++)
    {
        //TODO
    }

    return force;
}

```

Then I use all the forces returned by my boid functions and I apply it to my agent.

I just need to know how to do that with my walls.

Thanks for your help.

# Answer
Let each wall exert an influence on the velocity.

Try something like using the *inverse distance* (or inverse squared distance) from the wall to determine the magnitude of the force that each wall "exerts", and the normal of the wall to determine the direction of the force that the wall "exerts".

So here the boid interacts with 4 walls. Since the dot product of the red vectors (boid-to-wall-center) is greater than 0 for 3 of the 4 walls, those walls won't exert a force on the boid.

Only the wall with a blue vector (negative dot product) will have a force.

The magnitude of the force should be great with the boid gets too close to the wall, and the direction of the force should be in the direction of the black arrow on the wall (pointing directly away from the wall).

If you use `1 / (t+1)` for the magnitude of the force, where `t` is the distance from the wall, then the force will be really strong when gets close to 0, but fade off to nothing when t gets higher (note the axis scale in the diagram, it is *not* 0 when t=5, it is 0.2). (The t+1 is so that you don't get an infinite force / divide by 0 if the boid happens to enter the wall).

If you use `1/(t^2+1)`, then the force is much sharper near the wall, and falls off faster/smoother.

Experiment with it and see what you like.
> 14 votes

# Answer
If someone needs the code, here it is, feel free to redistribute it. I've tried to comment it to be more understandable. Based on bobobobo's solution.

```
Vector2D ReynoldsSteeringModel::repulsionFromWalls(vector<Vector2D *> walls)
{
    Vector2D force; // My force will be stored here
    Point2D pos = self()->position(); // Position of the agent

    // For each wall
    for (unsigned j=0; j<walls->size(); j++)
    {
        // Get the center point of the wall
        Real coordX = (walls[j]->p1().x() + walls[j]->p1().y()) / 2.0;
        Real coordY = (walls[j]->p2().x() + walls[j]->p2().y()) / 2.0;
        Point2D center(coordX, coordY);

        // Create a new vector between my agent and the center of the current wall
        Vector2D distance(center, pos);

        // If the wall is visible, calculate the force to apply
        double dotProduct = distance * partsList[j]->normal();
        if (dotProduct < 0)
        {
            force +=  partsList[j]->normal() / (distance.length() * distance.length() + 1);
        }
    }

    // Returned the calculated force
    return force;
}

```
> 8 votes

---
Tags: ai, steering-behaviors
---


# Question
Title: How are vertex shader outs sent as inputs to the fragment shader?
I'm learning some OpenGL 3.2 way of doing things and I think it's quite great, I'm actually understanding more of shaders and non-fixed pipeline in 1 week rather than those 2 years I tried to learn OpenGL fixed pipeline functions. But here's my question:

From what I think I've understood the vertex shader is run for each vertexes in the VBO. But the fragments shader is run per each pixel (is that right?) which is a huge number compared to let's say 3 vertexes of a triangle.

Now it seems that in the vertex shader the out variables (like colors and stuff) are passed 1 to 1 to the fragment shader. But let's say that I pass to the fragment shader the position of the vertex in the vertex shader. How is all executed? What vertex (A, B or C of the hipothetical triangle) is passed per each fragment and why?

# Answer
Because we're working with triangles all the information the vertex shader has can be interpolated along the surface of the triangle. A useful way of doing this is by using Barycentric coordinates.

OpenGL does this interpolation for us automatically, for example consider the following vertex shader:

```
#version 130

attribute vec4 position;        // vertex position from VBO
attribute vec2 uv;              // texture coordinates from VBO

uniform vec3 camera;            // position of the camera
uniform mat4 projection;        // camera projection matrix

smooth out vec2 texel;          // smoothed texture coordinate for fragment shader

void main()
{

    gl_Position = projection * (position - vec4(camera.x, camera.y, camera.z, 0.0));
    texel = uv;
}

```

This is an extremely standard vertex shader. The vertex has a position which is transformed using the camera and projection matrices.

As you can see from the comment we also output a 'smoothed texture coordinate for the fragment shader'. Using the OpenGL keyword `smooth` we tell OpenGL to interpolate this variable over the surface of the triangle of which this is one vertex. Conversely there is also the `flat` keyword which doesn't do this.

Now in the frament shader we consume this data:

```
#version 130

uniform sampler2D diffuse;      // diffuse texture
smooth in vec2 texel;           // where we should sample the texture

out vec4 outputColor;
void main()
{
    outputColor = texture(diffuse, texel);
}

```

Et voila, we have our nicely textured triangle instead of just a triangle made up of the three colours made from whatever `sample(texture,uv)` would've been in each vertex.

**Edit** the following quote is directly take from the file `teodron` linked. I thought it would be a good idea to add this to the answer to make it more complete and hopefully answer Jeffrey's question in the comments.

> The provoking vertex of a primitive is the vertex that determines the constant primary and secondary colors when flat shading is enabled.
>
> In OpenGL, the provoking vertex for triangle, quad, line, and (trivially) point primitives is the last vertex used to assemble the primitive. The polygon primitive is an exception in OpenGL where the first vertex of a polygon primitive determines the color of the polygon, even if actually broken into triangles and/or quads.
> 4 votes

---
Tags: opengl, shaders, glsl
---


# Question
Title: Is it OK to reuse art from open-source games?
There are a lot of open source games, such as Flare (Diablo clone).

Is it OK to re-use the art they put in their open source game and make a profit?

# Answer
I'm the Flare creator (main developer and main artist). Drop me a message if you have specific questions.

All of Flare's art can be reused commercially. Some assets are CC0, some are CC-BY, some are CC-BY-SA. It's important to know the requirements of each asset you use and that you credit each artist.

Share-Alike assets can only be remixed with other Share-Alike (or compatible) assets. Because of this many commercial games choose to not include CC-BY-SA art.
> 7 votes

# Answer
This will depend entirely on the license applied to the art assets. The number of open source licenses is always growing, so attempting to provide a list here would be pointless.

You will need to research the specific license that's applied to the art. Some of these licenses will allow you to reuse the art. For example, in the link you provide, a majority of the art is licensed under CC BY 3.0 which states you're free to make commercial use of the work (as long as you attribute the author).

If you're unsure what your rights are, you might try contacting the owner of the rights to the art and ask about your intended use. You may also ask for permission to use the art beyond what the original license states or work out a deal for such permission.
> 12 votes

# Answer
Publication of copyrighted works of art requires the author's consent with due exceptions and limitations that normally apply. Whether the game the art is used in is open-source, is irrelevant. However, in the spirit of this openness, it is not uncommon (but also not necessary) for the author of the game to automatically grant a liberal license to his work. The author's permission is still required, but implied, often conditionally.

If such a license is not provided or you do not wish to adhere to its conditions, and the art you wish to copy is protected by copyright, legally, you can either:

* Request the right holder's permission
* Work within the limitations of applicable copyright law
* Not use the content
> 1 votes

# Answer
Since the art from the project you linked is CC BY 3.0, it means you CAN

> You are free:
>
> * to Share — to copy, distribute and transmit the work
> * to Remix — to adapt the work
> * to **make commercial use of the work**

So **yes**, you can re-use and make a profit from some open source game art, **as long as you attribute the author of the art**.

> Attribution — You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).
> -2 votes

---
Tags: art, open-source, copyright
---


title: How do I code a 2D tile map?

text:
# Question
Title: How do I code a 2D tile map?
I'm new to game development and I want to know how to create a tile map. The map should be divided into squares, such that each square represents a location like `x : 10, y : 10`.

The width and height of the squares, as well as the number of squares, should be configurable.

How can I do this? (I'm using *MVC .NET*.

# Answer
> 4 votes
Look up the concept of tile maps. Essentially these are just 2 dimensional arrays of ID's that relate to tiles in a sheet. If a tile is 40 x 40 pixels you can draw the tiles out and get a 2d top down map. In addition you can then make maps with an editor. Good starting point is here:

http://en.wikipedia.org/wiki/Tile\_engine

# Answer
> 3 votes
The general idea is to create a data structure that holds a list of grid columns, each of which holds a list of grid squares.

To draw or otherwise traverse the grid, you would iterate through the columns, and inside that iteration, through each of the squares in that column. Something like this:

```
for x in [0, map.length]
    for y in [0, map[0].length]
        local square_contents = map[x][y]
        -- Do something with square_contents

```

For example, to draw the map in your render calls, traverse the map as above and for each tile, draw a square of side length `10` at position `x*11, y*11`. That would draw a map much like on the left here:

The other two images are differently sized maps drawn with different sizes of squares and spacing.

---

Just for reference, here's some heavily commented Love2D code that I used to generate the above image. You should be able to easily convert it to your favourite language or framework.

```
-- Parameters for map
MAP_WIDTH  = 10
MAP_HEIGHT = 10

-- Parameters for drawing tiles
TILE_WIDTH  = 20
TILE_HEIGHT = 20
SPACING     = 2

-- Just so that the background is white
love.graphics.setBackgroundColor(255,255,255)

-- {{{ CODE FOR MAP SETUP

-- Just a function to make a new tile object
function newTile(whatKind)
    return { kind = whatKind }
end

-- Storage for map data
map = {}

-- Go through values of x from 1 to MAP_WIDTH
for x=1,MAP_WIDTH do

    -- Storage for one column of the map
    map[x] = {}

    -- Go through values of y from 1 to MAP_HEIGHT
    for y=1,MAP_HEIGHT do

        -- With a 25% chance...
        if math.random() > 0.25 then
            -- ... make a new water tile
            map[x][y] = newTile("water")
        else
            -- ... else make it grass
            map[x][y] = newTile("grass")
        end
    end
end

-- }}} END OF MAP SETUP CODE

-- {{{ CODE FOR DRAWING A MAP

function love.draw()

    -- Go through all x values
    for x,column in ipairs(map) do

        -- Go through all y values
        for y, tile in ipairs(column) do

            -- Set colour depending on tile type
            if tile.kind == "grass" then
                love.graphics.setColor(24,255,24)
            elseif tile.kind == "water" then
                love.graphics.setColor(24,24,255)
            end

            -- Draw a rectangle in the correct position
            love.graphics.rectangle("fill",
                x*(TILE_WIDTH + SPACING),
                y*(TILE_HEIGHT + SPACING),
                TILE_WIDTH,
                TILE_HEIGHT
            )
        end
    end
end
-- }}} END OF MAP DRAWING CODE

```

# Answer
> 1 votes
The tile map may be simply a two dimensional array with the indexes/ids o each unique tile. Also, have a class (for example called TileIndex) to manage your unique tiles may be useful. The tiles indexes may be unload and load when you change room/scenario/level, because you probably want different unique tiles for different rooms, tiles needed to represent ground of a cave don't need to be loaded when exploring a scenario with grass in the ground. Have all unique tiles of the game loaded at all times may not be optimal, except all your game use the same tiles all the time.

The array contains only the ids of the tiles, because you build your scenario repeating tiles as smart as possible so the player won't get tired looking at the same patterns all the time.

Optimization tip:

For most games you probably will need some kind of scene organization, to quickly find objects in the screen rectangle and for efficient collision detection. If you already have payed the cost of a tile map floating around in RAM why have a separate structure like a quad tree or a grid to organize your scene. You can make the map contain in each element of the 2D array more than a tile id, in addition to the tile id you can have a pointer/reference to the entity/character/game\_object occupying the tile, or if your game need more than a single entity in the same tile at the same time, then a dynamic list rather than a single pointer.

For simplicity you can consider only objects centers to consider them occupying a tile. But consider their rectangle is not so hard as it sounds, but then a given entity can occupy more than one tile at the same time because its rectangle won't be always aligned to the tile rectangle.

You can force all characters to always stop at tiles centers (like some old 16 bit JRPG games), or allow single pixel movement, but again, in this last case you probably need to allow a character to occupy more than one tile at a given time.

> The width and height of the squares, as well as the number of squares, should be settable.

Ok, but consider the cost of constantly modifying the tile map dimensions. A Tip: don't even include set methods for the size in your tile map class, but have them in the constructor, you can plan your design so you never need to recreate a tile map except when entering a new room. When entering a new room destroy the tile map and create a new one. You probably want to unload the tile index and load a new one at this time too.

Also, for tiles width and height, you want to set them in the tile index. Usually you will have the same size for all the tiles of the index, so remember w and h for each tile is not optimal, best is have a single w and h members variables in the tile index class.

> I need to create a gridmap. The map needs to be divided in squares. Each square represents a location. For example: x:10 - y:10

If you decided to do as I say and create a class to represent the tile map then you can add some kind of get(x, y) method, a set one may be needed too if you plan to change the tiles values based on some game events (boss killed, a door opens). If you use a crude array for the map and have the logic somewhere else then simply do as with any multidimensional array to access individual elements. (\[x, y\], \[x\]\[y\]).

---
Tags: architecture, tilemap, grid
---