# Question
Title: What features should a moddable game have to make it easy to mod?
One of the objectives I have for a tactical RPG I'm making is moddability. My hope is that anything can be replaced with custom code.

For example: you can replace the combat system I did with, say, rules from other systems, like the combat system in tabeltop RPGs like d20 or Pathfinder (with enough perseverance, coding the whole thing), and just let the game use that, even though I'm not really sure how to go about designing my game to support that.

I don't have much experience with mods, save for trying out a few in Oblivion and Skyrim (\*ahem\* caliente, ENB mods, etc.).

So, to modders out there, what are the features that's there in easy-to-mod games that you like, that make you think "wow if this didn't exist, making my mod would have been almost impossible". Stuff that just isn't there in games where you have a bad modding experience?

To start off, here are my initial thoughts:

1. I'm thinking of adding a Lua interpreter in my game, giving various objects in the game script access.
2. Resources will be saved in text format (in JSON). For example, behaviour trees will be serialized in JSON text files that can be edited. An in-game visual editor will also be provided.
3. A mod manager for the game will likely be good also (like BOSS in Oblivion).
4. The idea of "mod packages" for easy distribution.

# Answer
> 5 votes
There are many factors that improve modding abilities in a game. Nevertheless, most games don't allow you to replace core programmings. But if your *"hope is that anything can be replaced with custom code"*, there are two key features you should provide to the community.

* Your **programming style** must be clean and legit so that other people can easily understand and dive into it. So they can modify existing code, which is basically what modding is. Most mod won't replace the whole combat system, but make some adjustments and tweaks, add new features, and so on.
* The must be a **documentation** that describes the background information about your game for programmers. A structured and easy to understand documentation is key to let other people work with your stuff. You may also consider writing beginner tutorials to let others get started easily.
* Provide and make extense use of **scripting**. Making changes to a game by scripting is much easier then by programming, because you have a given api for higher level game functions and you don't have to set up a complete development environment to recompile the whole code. By good scripting support your game becomes very easy to extend. And if you hope that others *"can replace the combat system"*, you should also consider more or less scripting that.

There might be other useful features to raise the ability and easiness to mod a game, but programming style, documentation and scripting might be the most important factors.

# Answer
> 1 votes
A "Return to factory defaults in case I screw up button". It makes it easier/safer for everyone to experiment, then there is no need to back up saves and struggle to revive them after game reinstallation. In TES Skyrim you can load complete mods. They shouldn't break the core and if something happens you can always trigger them off.

If you make anything YOU ARE CONDEMNED to make a solid reference so the players can move around your code. Like have all custom classes and functions explained so the programmers wont have to spend ages on learning how stuff works.

NPC/character editor and anything you have created to make the game. Read about the TESV Nexus.

---
Tags: modding
---


# Question
Title: Maintaining frame rate while using many High Resolution models
I have shelves "made of" steel rods as a 3D-file. So a lot of virtual metal rods make up a cage. When cloning this in unity a few times even my fast computer can only show this in a choppy way. But using an opacity map yields a flat result, which I don't want. For realism purposes there should be cylinders or similar, i.e. real 3D objects or the impression of real 3D objects, at least in close range.

How could I do that with more shelves without making the frame rate drop considerately?

I found that even though I am using opacity maps(128 x 128) just ten shelves and even 3dsmax begins stuttering.

EDIT: I uploaded a demo, it's for Win, X86 and X64. Get it here: http://www.sockshare.com/file/08BD739BDF94601C You need the opensource 7zip to extract.

# Answer
> 2 votes
You could use a combination of a opacity map with a normal map that gives the effect of round bars...

...or you could use the above with the combination of cylinders with far less geometry, say 6 sided or 8 sided.

# Answer
> 2 votes
This seems like a perfect time for LOD swapping. As in use a low resolution model with opacity maps when seen at a distance, and then swap in a more detailed cart when the camera gets close.

I mean, I'm assuming here that the shopping cart is somehow *really* important to the scene, because needing the metal rods to look super realistic seems pretty odd to me.

# Answer
> 1 votes
If you're going to have lots of individual metal rods, then you should be making them incredibly simple - they should be 6-sided cylinders at the absolute maximum (perhaps even 4). That is, of course, unless the camera is going to be super-zoomed-in on these trolley bars, but I can't think why.

LOD'ing (level-of-detail) is a good way to get around this problem. I'm not sure exactly how to implement this in unity, but it basically involves the concept of having two (or more) versions of the asset - basic and detailed versions. Ideally you should swap to the basic versions when the camera is a certain distance away from it, and then back to the high-quality version when the camera gets closer.

I would also be concerned with the effect this has on light-mapping. You might find performance increase if you have the metal bars not cast any shadows. That is of course, just a further suggestion.

Edit: You said your polycount was over 200,000 - which is extremely high. You'll need to simplify your geometry to make it run smoother. Try and look at the model at how the player will be looking at it - eg, put the detail *only* where the player will notice it. Try and bring the polycount down as much as possible.

# Answer
> 0 votes
Do you really need a high resolution mesh of your shopping cart?

You could also use a model looking more or less like a simple box and apply textures which are transparent at positions where no rods are. Which technique to use depends on how detailed the model should be. But if the player don't take too close looks on the model, I advice you to use the latter approach since it is much faster.

Otherwise you could only minify the vertices of your mesh to increase performance, I guess. You could also combine both approaches by providing one of them depending on how far the camera is away from the shopping cart. This is called level of detail.

---
Tags: unity, frame-rate, resolution
---


# Question
Title: How to implement a basic arcball camera in OpenGL with GLM
I only just started learning `OpenGL` and even things like vector maths etc a couple of days ago, so I am having a bit of trouble figuring out exactly what to do to implement an arcball camera system.

I am using `GLM` to do things like get the cross product of two vectors etc, and I am using the `glm::lookAt(position, target, up)` method to set the view matrix.

I have looked around on Google and the search on this site and even StackOverflow but since I am new to this I'm not exactly sure what I'm doing wrong (probably a lot of things) and what I should be searching for.

At the moment I am trying to follow the general steps outlined in this answer: How can I orbit a camera about it's target point?

But I am not sure if I am doing it correctly (well, actually, I know I'm not doing it correctly because it's not working).

I can get the camera's normalized `up` and `right` vectors without any problem, and I can get a vector from the camera's target point to the camera position.

I can then easily decide the angle of rotation in radians, but my main points of trouble come after that; creating a new vector to translate the camera with from a rotation matrix and then actually translating camera to get a new camera position.

I'm not sure exactly what information you would need to help me, but here is a general overview.

Currently I have a cube that is drawn around the origin, three `glm::vec3` objects which describe camera position, camera target and camera up, and the usual `projection`, `view` and `model` matrices which are multiplied together and given to `glUniformMatrix4fv()`.

Apart from `glUniformMatrix4fv()` this is all declared before the main loop.

```
glm::mat4 projection_matrix = glm::perspective(45.f, 4.f / 3.f, 0.1f, 100.f);

glm::vec3 camera_position = glm::vec3(0.f, 1.f, 5.f);
glm::vec3 camera_target = glm::vec3(0.f, 0.f, 0.f);
glm::vec3 camera_up_vector = glm::vec3(0.f, 1.f, 0.f);

glm::mat4 view_matrix = glm::lookAt(
    camera_position,
    camera_target,
    camera_up_vector
);

glm::mat4 model_matrix = glm::mat4(1.f);

glm::mat4 mvp = projection_matrix * view_matrix * model_matrix;

```

Just before the main loop I also declare two `glm::mat4` matrices to rotate with `yaw` and `pitch` and two more `glm::vec3` objects to store the target to camera and camera right vectors, since that was one of the steps in the answer I linked above.

```
glm::vec3 target_to_camera_vector;
glm::vec3 camera_right_vector;

glm::mat4 rotate_yaw_matrix = glm::mat4(1.f);
glm::mat4 rotate_pitch_matrix = glm::mat4(1.f);

```

Now, within the main loop I re-calculate the `target_to_camera_vector`, `camera_right_vector` and `camera_up_vector` before I try to do any more calculations.

```
target_to_camera_vector = camera_position - camera_target;
camera_right_vector = glm::normalize(glm::cross(target_to_camera_vector, camera_up_vector));
camera_up_vector = glm::normalize(glm::cross(camera_right_vector, target_to_camera_vector));

```

After this is where I think I am going horribly wrong.

The answer I linked above says:

> Create two rotation matrices. The 1st rotation matrix will use the up of the camera as the axis and yaw angle that you decided. The 2nd rotation matrix will use the right of the camera as the axis and pitch angle that you decided.

So I try to rotate the two `glm::mat4` matrices I had created earlier, even though I'm not 100% sure this is how you do it in `GLM`.

```
rotate_yaw_matrix = glm::rotate(rotate_yaw_matrix, yaw_angle_radians, camera_up_vector);
rotate_pitch_matrix = glm::rotate(rotate_pitch_matrix, pitch_angle_radians, camera_right_vector);

```

The answer linked above then says:

> Now rotate the camFocusVector with the new rotation matrices. This is now your new position of the camera relative to the origin. We of course, want it to be relative to the focus point...

This is where I am really just guessing what to do.

```
target_to_camera_vector = glm::vec3(rotate_yaw_matrix * glm::vec4(target_to_camera_vector, 0.f));
target_to_camera_vector = glm::vec3(rotate_pitch_matrix * glm::vec4(target_to_camera_vector, 0.f));

```

After that it says:

> Add the focus point position to camFocusVector. This is now your camera's new position. Translate your camera accordingly.

So, once again, since I'm not exactly sure what this means, I guess, of course.

```
target_to_camera_vector += camera_target;

```

And having no idea how I should use this result to translate the vector, I make the, most likely wrong, assumption that I am supposed to do this.

```
camera_position += target_to_camera_vector;

```

Afterwards I use the `glm::lookAt()` method and recalculate the model view projection matrix to pass to `glUniformMatrix4fv()`.

```
view_matrix = glm::lookAt(
    camera_position,
    camera_target,
    camera_up_vector
);

mvp = projection_matrix * view_matrix * model_matrix;

```

As I said, I only just started learning about OpenGL and 3D/Vector maths a couple of days ago, so a lot of my learning at this stage is experimenting and guessing etc. But I think I mostly went wrong around the point where I had to rotate the matrices and translate the camera position.

So my question is (finally), am I following the right path to implement an arcball camera (it seems like it should be ok), and if so, how can I properly implement the steps to rotate the `target_to_camera_vector` and then use that to translate the `camera_position`?

Any help would be appreciated.

# Answer
Place your camera target at the center of the arc rotation (That's usually where you want the camera to look anyway). Then simply transform the camera's position around the target with a rotation that uses the appropriate axis.

```
pseudo code:
//some angle & some other angle = only the amount you want the camera to rotate since last frame.

//pitch
position = (Rotate(some angle, cameraRight) * (position - target)) + target;

//yaw, Y-up system
position = (Rotate(some other angle, (0,1,0)) * (position - target)) + target;

view = LookAt(position, target, up);

```

Edit: fixed missing parenthesis
> 11 votes

---
Tags: c++, opengl, camera, glm
---


# Question
Title: Should I allow "low-level" access in my game for modders?
I'm thinking of adding a Lua interpreter in my game, giving various objects in the game script access to allow mods.

By how much should I expose to the scripting environment, I'm not sure.

Should I allow low-level access?

For example, should I just give the scripts a function to move a character (takes care of moving, playing walk animation, everything needed).

Or should I allow low-level functions instead: a function to play animation, separate from the function that moves the character, a function to receive damage (that won't care where the damage came from), perhaps even a function that just teleports a character anywhere.

One worry is that players would hack things that aren't meant to be. Then again, why not just let them do that?

EDIT: People have also pointed ease of use for the modders as a good concern, as well as being a security risk for the player's PC, so feel free to discuss those points as well in your answer.

# Answer
Personally, I *would* allow 'low-level' access to modders. Your worry isn't really all that it seems - remember, if someone *really* wants to change something they shouldn't, they'll reverse engineer your game and change it anyway (or find some creative method, such as transferring a Skyrim game from Xbox or PS3 to the computer for the console).

The question (to me, at least) is more of 'Will the added functionality available in the Modding API (or equivalent) result in feature bloat / make it too complicated?'. The best solution **may** be to give the modders two choices - one is the simple system that can move a player where they can only access high-level commands such as 'move player to **a**, or from **b** to **c**', but the other may be 'move player from **a** to **b**, through **c**, with animation **d** at speed **e**'. As you can see, this does get complicated fairly quickly, and so it may be better just to avoid the low-level commands, and see what creative ways players / modders can come up with to achieve their goals.
> 4 votes

# Answer
> One worry is that players would hack things that aren't meant to be. Then again, why not just let them do that?

Modders usually create mods without commercial interest, so they add free value to your game. When your modding interface allows enough freedom, people might even buy your game just because of the mods (just think about how many Half Life 1 copies were bought by people who just wanted to play Counter Strike - and that was before Valve hired the developers).

Giving modders as much freedom as possible is a valuable effort because it allows them to create much more creative mods.

But keep in mind that their freedom to influence everything should be confined to your game, and not beyond it. When your modding API is too powerful, it might become a security risks to the end-users.

When you expose file APIs, mods could read personal data of the user, change settings of other programs or even drop malware. When you expose networking APIs, mods could forward personal information to a 3rd party server or even turn your game into a spam- and DDoS relay. The chance to get infected by malware through a malicious mod would make people wary of installing them and greatly hamper the enjoyment which is brought by an active modding community.
> 4 votes

---
Tags: modding
---


title: Working principle of an RPG map

text:
# Question
Title: Working principle of an RPG map
I am currently thinking of building a basic browser-based 2D(that would eventually become 2.5D) RPG. I have planned everything and I think that would be able to accomplish the current goals, **but** it seems that I can't think of a good way to develop the mapping. I have been able to move(currently teleporting as no animations at the moment) the character onclick, but can't think of a way to make some parts of the grid(tiles) not clickable so the players will not walk on water or over trees or anywhere else that they are not supposed to do so. the movable area will be 3-4 tiles out of the two-tiled roads/paths. each tile will be around `40-50px` as well the character.

The game in general will be like Diablo 2 (Leveling, bosses, different areas/maps, different enemies with different levels, some equipment and etc.). And the map is mainly the biggest problem cuz I want to add cities and merchants, and the player shoould not be able to get on a questgiver's house(will not be able to get inside as well).

So to put everything together:

1. How should one create a tiled map, so that can mark unmovable and next(those that will trigger entering next part of the map) fields?

1.1 **INFO:** I was thinking of JSON to pass the data to jQ/javascript and to do the manipulation on client side but can't think of a way to mark fields
2. How to determinate the shortest path to the new char position for the purpose of animating

**EDIT:**

I am not asking anyone to do it for me, I would like to be explained how to manage everything in theory, any possible tools, technologies and etc.

# Answer
Most 2D tile-based games use arrays (of some sort) to describe the map. If you assign each type of tile (grass, path, tree, house, water etc.) a numeric index, you can describe your map like so:

```
[2][1][1][1][1]
[2][2][1][1][1]
[1][1][1][1][1]
[1][1][1][3][1]
[1][1][1][1][1]

```

(1 = grass; 2 = tree; 3 = house) = a 5x5 map with three trees clustered top-left and a house near the bottom-right.

You can assign each tile properties, such as movement cost: how 'difficult' it is for a player to traverse that tile. This is normally used in conjunction with Pathfinder algorithms); assign regular tiles (grass, path etc.) a low cost. If you don't want a player to be able to move onto a tile, you would assign that type of tile a high movement cost. Your pathfinder should then be able to calculate the quickest (i.e. lowest cost) route to the destination, which will exclude high-cost tiles.

You could also set an upper bound to the values that the algorithm will accept, meaning it won't even try to traverse high-cost tiles. This would effectively make them immovable obstacles.

Here's a really good Javascript implementation of the A\* Pathfinding Algorithm.

In theory, you could create a JSON object of several different map arrays to hold a whole game world's worth of screens... I suspect the filesize might balloon rather quickly, though.
> 5 votes

---
Tags: javascript, tilemap, rpg, jquery
---


title: Java Slick2d Delta ( time )

text:
# Question
Title: Java Slick2d Delta ( time )
In Java slick2d , i started printing out Delta which is supposed to be the time and it prints out is 16 or 17 forever, so how does this help me if i want to tell an object when it needs to do something, example : IF (createdtime + 60miliseconds \< delta )

60miliseconds after its creation , do something

# Answer
> 4 votes
Delta time is the amount of time since the last update. You're getting 16 or 17 because it has been 16 or 17 milliseconds since the last update. If you want to know how long your game has been running, do something like:

```
long runningTime = 0; //declared outside the update loop

//in update loop put:

runningTime += deltaTime;

if(runningTime > 60)
    //do something every frame after 60 milliseconds.

```

---
Tags: java, slick
---


# Question
Title: implementing a 2d looping using a physics engine
I am implementing a 2d mobile racing game. I have already implemented a 2d terrain using a physics engine (using edges). Now i would like to implement a looping very similar to the one in the old super sonic (http://higherorderfun.com/blog/wp-content/uploads/2012/05/Sonic\_2\_Loop.jpg). The problem is if i use a normal edge the car hits in the edge when going up the ramp (which is completely logical). Does any one have any experiences on how to make a looping using a 2d physics engine (without faking it)? Is it even possible (i know that is possible in 3d).

Thanks for the help!

# Answer
> 3 votes
Implementing layers would work, does that count as "faking it"? For loops you can transition between layers at the top of the loop and at the 'output' end of the loop. The left part of the ramp is in a layer below the right part of the loop:

Red is the back layer, blue is the forward layer. I imagine you can set a zone at the transition point to send your cars back a layer when they pass through that zone. Likewise, at the exit you switch back to the forward layer. When an object is in the forward layer, it ignores collision objects in the back layer and vice versa. For this reason, you'll want to have overlap at the transition points, to ensure you don't have objects falling through the terrain.

Alternatively, you can create a collision object that cares about the angle of incoming objects.

Compare the object's heading with the normal of the collision edge. If they are perpendicular, proceed with normal collision response. If the angle between the normal of the collision edge and heading are off perpendicular by some amount (20 degrees? It'll take some testing), allow the object to pass through the collision edge.

These special edges would be at the left side of the loop and the bottom.

# Answer
> 0 votes
I don't do game development yet, but I read up on it out of curiosity and for the sake of learning. I recently read an article by Patrick Wyatt about overcoming path finding and collision difficulties in the development of Star Craft because they used the old Warcraft engine, which didn't support the isometric view for collision boxes. They did some pretty neat hacks that I think will help you out. Have a look here.

Hope it helps!

---
Tags: 2d, physics
---


# Question
Title: What's a good 2D game engine or framework to work on right now?
Basically, I'm looking for a good, 2D game engine to build a platformer/contra-like shooter on to bolster (and when I say bolster, I really mean start) my portfolio.

I use the words "right now" in the title because I've read through some questions, and I don't really want to use anything like Java's game API for mobile phones from 2003. (Also, XNA is out of the question as I'm already working on a larger scale project in it.)

I'm fairly competent in Java, and have a basic understanding of other languages like C# and Python, but I'm totally unopposed to learning a new language while learning the engine (within reason).

The engine doesn't have to be super powerful, just free and simple enough that someone of my skill level (3rd year CS major) can get a nice horizontal slice out without too many bumps along the way.

# Answer
> 6 votes
There's a ton of links if you ask Google about it, but most of them are things that seem relatively unheard of. I have used one of the top results, Love, for a little while and found it pretty quick to get up and running with. It uses Lua.

There's also Torque 2D, which I've heard decent things about (it is non-free, which I know you mentioned, but it is also relatively cheap, so...). cocos2d is quite popular for the iPhone.

You also have the option of using Unity or Ogre or Irrlicht or any of the other available 3D game/graphics engines to simulate a 2D space, but that may involve more extra work than you want.

# Answer
> 3 votes
FlatRedBall www.flatredball.com would be an example of an 'engine' based on xna.

Hmm...wanted to add a comment to the OP but couldn't...maybe i don't have the rep yet.

# Answer
> 3 votes
If you want to dabble in **HTML5** games I suggest you look in to **Crafty.js**. It is a small but flexible game library that's easy to learn and handles the essentials like *input*, *collisions*, *sprites*, etc.

I think the biggest strength in Crafty is the **component/entity architecture**. It's a great way to structure your games and Crafty makes it very easy to create your own components.

The **best documentation** is probably the Crafty.js source on github.

# Answer
> 0 votes
Slick2D http://slick.cokeandcode.com/ is great for Java with some great Toolings available. Have a look at the Feature List.

The tooling includes: FontEditor, Tiled Map Editor, Sprite/Animation Manager. Additionaly there is support for Phys2D a Java Based Physics Engine.

They are currently working on an easy way to port Slick based games to Android.

# Answer
> 0 votes
I've used Torque products for years now I would defiantly recommend them. The company did go into administration but has come back to life recently with quite a few updates to the product lines. Definitely worth downloading the trial version and taking a look.

---
Tags: 2d
---


# Question
Title: Having problems exporting Genesis + Supersuit in .fbx format from Daz 3D
I created a new scene. Loaded the Michael 5 Hero character. Added the Supersuit. Then posed the M5 character using "M5 Walking 1" pose from the "M5 General Poses" collection.

My problem is that whenever I import the fbx file into another software (like Maya or Unity), my genesis figure appears to be in that pose (M5 Walking 1), but the supersuit still remains in the default T-pose!

Please tell me how to rectify this.

# Answer
> 1 votes
Finally got it to work. Export the character in FBX format with the following attributes checked:

•Figures •Morphs •Embed Textures •Merge Clothing into Figure Skeleton (I was missing this one previously) •Allow Degraded Skinning •Allow Degraded Scaling

---
Tags: fbx
---


title: Geometry problem for area of sight

text:
# Question
Title: Geometry problem for area of sight
My player have a line of sight and all objects between the white lines, turns red. To compute this, the following conditions are met: if the angle between the yellow line and the red line are small or equal to the angle between the yellow line and the white line above, then the object is considered to be inside the line of sight. It also works if the object are below the white line. Here is the code:

```
def _getTeta(obj_1, obj_2):
    deltaX = (obj_1.centerx - obj_2.right)
    deltaY = (obj_2.top - obj_1.centery)
    return math.acos(deltaX / math.sqrt(deltaX**2 + deltaY**2))

```

> Obs.: *centerx* and *right* are X values and *centery* and *top* are Y value; all of them representing values encountered under certain points of each object's rectangle.

Then, I do:

```
if _getTeta(platform.rect, self.rect) <= _getTeta(abovePoint, self.rect):
    return True

```

where **above point** is the point in which forms the white line on the top, and **platform** is the object to be checked.

However, as the second image shows, it doesn't work if the line of sight are inverted in the X axis. The problem is that I don't know how to set values right so it could also work when the player is looking to the left.

Let me know if I'm not being clear in my question! Thanks!

# Answer
> 0 votes
I figured out in a simple way.

First, I set the mouse position with a value relative to the player's position, making the last the center (0,0).

Second, what python was doing is to set a 180 angle degrees in a clock direction above the player and another 180 angle degrees in a clockwise direction below the player. As anyone can see, this makes a huge mess.

The solution was to make a simple calculation with angles:

```
if mouse.y < player.y:
    sightAngle = 2*pi - mouseAngle

```

This basically makes a true 360 angle degree around the player, making the sen() and cos() work properly. And then, the coordinate position of the points is set according to the window's coordinates.

# Answer
> 0 votes
You don't need trigonometric functions for this. With fairly simple vector algebra, this can work for any viewing direction. Consider the normalised vector **n** (the yellow line) and a vector pointing to an object, **x**. The object is in the field of view if: ***n*** *· **x** \> a |**x**|*, where *a* is a number between -1 and 1 indicating the view angle (*cos φ/2 = a*).

In components (2D), using ***n****=(u,v)* and ***x****=(x,y)*:

```
if (u*x + v*y > a * sqrt(x²+y²)) return true;

```

# Answer
> 0 votes
You just nee to use the absolute value of x --\> abs(x)

---
Tags: python, geometry, pygame, line-of-sight
---


# Question
Title: How to make 2d map that isnt based on tiles
I am working on a game, and need to make a 2d map that isnt based on tiles. An example of something similar to what I want is all those racing games like "bike race" where the map is just somewhat a line. While I have made tile based 2d games before, both using map editors and programming myself, I have no idea where to begin to make a map type like that. Are there any programs that are used to make such maps? If not, how might I go about it? Just draw the line in an image editor, and program objects to go over that image, and then set up collision detection on the line so that players can't go through it?

# Answer
Well usually for something like that I would imagine most people use a polygon based (maybe curves) line (see canvas rider/line rider). That could be made in a vector editor or a custom editor. Then, intersection tests would be performed with your bike/etc and the line under the bike.

And, if you wanted to have a graphical background, simply make the line invisible and just do collision detection while drawing the background instead
> 1 votes

# Answer
It's quite simple really. Just store an array of coordinates for the height map. (For instance \[x\]\[y\] , where X is the offset from the start, and y is the height). You can simulate pretty much any map with that but if you need smooth curves it would require some fiddling with it. I can tell you how if you want to.
> 0 votes

# Answer
The big advantage with tiles based map is that it makes collision detection with the world fairly easy: you look at the position and bounds of the object, and if it crosses the boundaries of the tiles it is supposed to be in, there's a collision. In a more complex setting, tiles have walkable and blocked content, in which case you need a little of bit wizardry to detect whether the object tile and the world tile are overlaps to collision. However what you are suggesting is some sort of huge singleton tile map. Instead of a line indicating the world limits, you can use a stencil, with one color walkable and the other blocking. A simple xoring with your object stencils should indicate if a collision happens, and where (handy for sparks). This solution is also valid in a regular tile map. The advantage of a single tile is that graphists can design unique maps, at the cost of a larger memory space used by the map.

Yet another solution is to store the circuit limits as vectorized lines, and use vector calculus to check collisions. This solution is actually compatible with a tile based map, but require some more modeling work to get it right. That's perhaps what you are talking about. The difficult parts are:

* locate which bits of the map needs to be tested for collision. The main idea is to partition the map in small pieces, and use dichotomic search to locate which parts are relevant. Some popular partitioning algorithms are KD tree, quad tree, and BSP. You will have to figure out a way of doing region selection for some of them. R-tree is another solution, which is build around the idea of region selection, but I think that it's a bit harder to implement.
* compute the intersection between the map lines and the object. As suggested in another answer, a good solution is to model the object as a set of triangles, and compute the intersection of the lines with each of them. There's plenty of literature on the topic.
> 0 votes

---
Tags: 2d, physics, maps
---


# Question
Title: Displaying animations during loading screens
Games like Karateka (which uses UDK) seem to be able to asynchronously load GL assets as well as display animation.

The splash is incredibly short, then presumably their glView shows up.

I can think of 2 ways to simultaneously load textures, models and assets into OpenGL:

1) Create 2 contexts: the "real" one (which is doing the loading) and a "fake" one (which will be on a separate viewcontroller.. on a separate thread.) I'm not sure if this will work however as I don't know if you can create a 2nd GL context on *not the main thread*.

2) Cut the load sequence into small, small jobs. Each iteration of your draw loop, load one tiny asset (like a single texture or a single model).
The effect of this is probably a *much* longer total loading time!

Are either of these 2 right or are they both wrong? Is there another way to do it?

# Answer
After some searching, I came across the concept of EAGL Sharegroups.

It seems as though iOS designers really thought things through, because EAGLShareGroup is *exactly* what I need here.

Docs say EAGL Sharegroups are useful "When you want your application to be able to create new OpenGL ES objects on a thread other than the main thread for the renderer. In this case, a second context runs on a separate thread and is devoted to fetching data and creating resources. After the resource is loaded, the first context can bind to the object and use it immediately."

Creating a new context with the same sharegroup is easy:

```
EAGLContext* secondContext = [[EAGLContext alloc] initWithAPI:[firstContext API]
                               sharegroup: [firstContext sharegroup]];

```

It's ok to read the same OpenGL object on multiple contexts with the same sharegroup **provided the object is not being modified.**

While a GL object **is** being modified, **you may not read that object on another context**. So you can't try and render the texture you are loading on one context with the other context until you are 100% sure the first context is done loading first.

After an object has been modified, you have to re-bind it on all contexts to see the changes.

So much for cutting my code up into little bits!!
> 3 votes

---
Tags: ios, multithreading, loading
---


title: Reinhard tone mapping and color space

text:
# Question
Title: Reinhard tone mapping and color space
I found two ways of doing tone mapping (first, second):

```
//Ld - this part of the code is the same for both versions
float lum = dot(rgb, vec3(0.2126f, 0.7152f, 0.0722f));
float L = (scale / averageLum) * lum;
float Ld = (L * (1.0 + L / lumwhite2)) / (1.0 + L);
//first
vec3 xyY = RGBtoxyY(rgb);
xyY.z *= Ld;
rgb = xyYtoRGB(xyY);
//second
rgb = (rgb / lum) * Ld;

```

For an example pixel data above equations produces different results. Which way is correct ?

# Answer
> 6 votes
With tone mapping, there is no "correct" answer. You're trying to reduce an HDR image to an LDR one that somehow visually represents the luminance range present in the original, which is very subjective. Choosing a tone mapping equation is a matter of aesthetic judgement, not physics.

By the way, if you're interested in tone mapping, I would recommend also looking at the equation presented in John Hable's talk, Uncharted 2 HDR Lighting (slide 140 has the equation I'm talking about).

---
Tags: opengl, graphics, glsl, hdr
---


# Question
Title: HDR / Tone Mapping - choosing parameters
I implement HDR in my graphics engine (deferred rendering) based on this document: link I save a luminance in a texture (RGBA16F) this way:

```
const float delta = 1e-6;
vec3 color = texture(texture0, texCoord).xyz;
float luminance = dot(color, vec3(0.2125, 0.7154, 0.0721));
float logLuminance = log(delta + luminance);
fragColor = vec4(logLuminance, logLuminance, 0.0, 0.0);
// first channel stores max luminance during a minification process

```

Then I can calculate an average luminance and find a max luminance.

The delta = 1e-6. Is that a good choice ?

Can I calculate "a" (equation 2) dynamically to achieve better results ?

# Answer
First, the 1e-6 delta: this may well be fine, but it depends on the range of HDR luminances present in your scene. If your typical luminances are on the order of magnitude of 1 or higher, then 1e-6 should be fine, but if you have very dark scenes where the typical luminance can get down to 1e-4 or so, then 1e-6 as a delta might be too large.

As for the value a = 0.18 in the Reinhard et al paper, they indeed mention dynamically adjusting it, but it's not very clear how this is done:

> For low-key or high-key images we allow the user to map the log average to different values of a. We typically vary a from 0.18 up to 0.36 and 0.72 and vary it down to 0.09, and 0.045.

It sounds to me like it's a user control, where the user is explicitly setting the image to appear brighter or darker (higher or lower a). This would be akin to the brightness setting that many games have, although I think that usually just applies a gamma curve to the post-tonemapping LDR image rather than altering the tonemapping equation. In any case, it's not clear how you would choose this value programmatically if you didn't want to make it a user control.
> 2 votes

---
Tags: opengl, hdr
---


title: Switching from OpenGL ES 1.0 to 2.0

text:
# Question
Title: Switching from OpenGL ES 1.0 to 2.0
I have been developing an Android app using OpenGL 1.0 for quite some time using a naive approach to rendering, basically making a call to glColor4f(...) and glDrawArrays(...) with FloatBuffers each frame. I am hitting a point where graphics is becoming a huge bottleneck as I add more UI elements and the number of draw calls increases.

So I'm now looking for the best way to group all of these calls into one (or two or three) draw calls. It looks like the cleanest, most efficient and canonical way to do this is to use VBO objects, available from OpenGL ES 2.0 on. However, this would require a HUGE refactoring on my part to switch my whole graphics backend from ES 1.0 to ES 2.0. I am not sure if this is a good decision, or if there are acceptable ways to group my drawing calls in 1.0 that would work fine for relatively simple 2D data (squares, rounded rectangle TRIANGLE\_FANs, etc.), or if it really might be worth biting the bullet and making the switch. I might also mention that I have a HEAVY reliance on translation and scaling that is so convenient with the fixed pipeline of ES 1.0.

Looking around, I am surprised to find almost NO people in my position, talking about the tradeoffs and complexity at hand for such a switch. Any thought?

# Answer
Vertex Buffer Objects were added already in OpenGL ES 1.1. You can switch to that, which will be a lot smaller change as it doesn't remove any features. OpenGL ES 1.1 is supported since Android 1.6, so you still have practically 100% device coverage and it solves your problem of multiple draw calls.
> 1 votes

---
Tags: android, opengl-es
---


# Question
Title: How do I make multiple instances of an object?
In a game I am working on, I am having an issue with making the player's ship shoot multiple bullets. The bullets have individual X and Y coordinates and velocity for X and Y. When I press "SPACE" to shoot the bullet, only one comes out, and when I release the space bar, the bullet disappears. I want to make multiple bullets without having to make an array since the amount of shots would be limited to the array size.

How do I make multiple instances of an object with data without using an array?

# Answer
> 1 votes
As Sean said, you should use a STL container if you do not want to use a fixed sized array. The problem is that you will be tempted to insert or delete random elements relatively often. Instead of using a fixed sized array, I recommend using a std::vector, which basically is an array (at least in memory) with some additional features. In contrast to std::list, the data lies continuously in memory and thus calculations as physics and collision detection can be done effectively. Furthermore, it automatically does the resizing for your, so you will not have problem if you cannot determine a 'gameplay-implicit limit' for the number of bullets.

Furthermore, as I said, you will be tempted to delete random elements in the vector. Instead, do this: For each bullet, set a boolean alive flag. This will be true if the element of the vector represents a bullet which currently is flying through space and will be false if the element of the vector represents a 'free' slot. Use this 'free' slot when creating new bullets.

---
Tags: c++, directx9
---


title: OpenGL GLSL skinning problem

text:
# Question
Title: OpenGL GLSL skinning problem
This time I've decided to ask a question related to my skinning problem. Two earlier ones were not really related to my problem and I've deleted them.

Ok, first of all, I'm using OpenGL 3, 3ds max, and Delphi to create a skeletal animation demo. I'm using the IGame interface to export meshes from 3ds max to XML - I use the sample included in the SDK.

Now, I'm going to describe as precisely as I can what I do.

**Passing bone weights to the shader**

I'll skip parsing geometry, because it works okay. Now, if a mesh is skinned (using the Physique modifier), the resulting XML contains information about bone influences for each vertex, like so:

```
<Skin VertexID="2" Type="Rigid">
    <Bone BoneID="22" Weight="1,000000"></Bone>
</Skin>
...
<Skin VertexID="14" Type="Blended">
    <Bone BoneID="22" Weight="0,986472"></Bone>
    <Bone BoneID="14" Weight="0,013015"></Bone>
    <Bone BoneID="23" Weight="0,000513"></Bone>
</Skin>
...
<Skin VertexID="31" Type="Blended">
    <Bone BoneID="22" Weight="0,948354"></Bone>
    <Bone BoneID="23" Weight="0,030462"></Bone>
    <Bone BoneID="23" Weight="0,011265"></Bone>
    <Bone BoneID="14" Weight="0,009909"></Bone>
    <Bone BoneID="23" Weight="0,000011"></Bone>
</Skin>

```

My shader assumes that there should be always 4 bones, which influence a single vertex, and as you can see, sometimes there is sulprus/insufficient number of them, so I decided to:

1. Sum up weights of the same bone - take a look at vertex 31 - there are five entries, but after summing them up, we're left with three.
2. Pad the remaining number of weights with zero.

Right now, I have a list of bone IDs/vertex weight pairs, which I pass to the shader like so:

```
const
    MAX_BONES_PER_VERTEX = 4;
type
    TVertexWeight = record
        BoneID: Integer;
        Weight: Single; // standard float
    end;
...
var
  L: TList<TVertexWeight>;
...
glGenBuffers(1, @FBonesVBO);
glBindBuffer(GL_ARRAY_BUFFER, FBonesVBO);
glBufferData(GL_ARRAY_BUFFER, L.ListSize, L.ListPointer, GL_STATIC_DRAW);

glEnableVertexAttribArray(FBoneIDsAttr);
glVertexAttribIPointer(FBoneIDsAttr, MAX_BONES_PER_VERTEX, GL_INT,
    SizeOf(TVertexWeight), PInteger(0));

glEnableVertexAttribArray(FWeightsAttr);
glVertexAttribPointer(FWeightsAttr, MAX_BONES_PER_VERTEX, GL_FLOAT,
    False, SizeOf(TVertexWeight), PInteger(4));

```

I think this part is working fine, because when I hardcode an identity matrix in the shader, the model is rendered in its bind pose.

**Computing bone matrices**

For now, I just want to display the model in a pose which it would be in, let's say, frame 49:

Here's the code I use:

```
procedure CalculateBones(const SequenceName: String; const FrameID: Integer;
    const ABone: TAnimatedMeshBone; const ParentTransform: TBrainMatrix);
var
    Samples: TBrainList<TAnimatedMeshAnimationSample>;
    BoneSample: TAnimatedMeshAnimationSample;
    I: Integer;
    BoneTransform, GlobalTransform: TBrainMatrix;
    Children: TBonesList;
begin
    Samples := TBrainList<TAnimatedMeshAnimationSample>.Create();
    Children := TBonesList.Create();
    try
      FAnims[SequenceName].SamplesByFrame(FrameID, Samples);
      BoneSample := nil;
      for I := 0 to Samples.Count -1 do
        if (Samples[I].Bone.ID = ABone.ID) then
        begin
          BoneSample := Samples[I];
          break;
        end;

      BoneTransform := ABone.OffsetMatrix;
      if (BoneSample <> nil) then
        BoneTransform := BoneSample.Matrix;
      GlobalTransform := Mat4Multiply(ParentTransform, BoneTransform);
      GlobalTransform := Mat4Multiply(GlobalTransform, Mat4Inverse(BoneTransform));

      BoneMatrices.Add(GlobalTransform);

      FBones.BonesByParentID(ABone.ID, Children);
      for I := 0 to Children.Count -1 do
        CalculateBones(SequenceName, FrameID, Children[I], GlobalTransform);
    finally
      Samples.Free();
      Children.Free();
    end;
end;
...
BoneMatrices := TBrainList<TBrainMatrix>.Create();
try
    //  A bone's offset matrix is the bind pose.
    CalculateBones('zhuxian2', 49, FBones.RootBone, FBones.RootBone.OffsetMatrix);
    glUniformMatrix4fv(FShader.GetUniformLocation('boneMatrices'),
        BoneMatrices.Count, False, BoneMatrices.ListPointer);
finally
    BoneMatrices.Free();
end;

```

A bone's `OffsetMatrix` is basically the bind pose (regarding to what the exporter says, it's in object space) of the bone. Now, a `TAnimatedMeshAnimationSample` contains position and rotation (in quaternion) of a bone in the given frame. The `for` loop at the top of `CalculateBones()` basically checks if in the given frame (in this case, `49`th) there's transformation data for the given bone.

After launching the code above, all I get is this: (please ignore the lack of textures for now)

But when I change the initial parent transform from `FBones.RootBone.OffsetMatrix` to `Mat4Identity()` (basically use an identity matrix), the model is displayed in its bind pose:

**Vertex shader code**

```
#version 150

#define MAX_BONES_PER_VERTEX 4
#define MAX_BONES 32

uniform mat4 proj;
uniform mat4 modelview;
uniform mat4 boneMatrices[MAX_BONES];

in vec3 vertex;
in vec3 normal;
in vec2 texCoord;
in ivec4 boneIDs;
in vec4 boneWeights;

out vec4 fragmentColor;

float phong_weightCalc(in vec3 light_pos, in vec3 frag_normal) {
    return max(0.0, dot(frag_normal, light_pos));
}

mat4 getBoneMatrix(int boneIndex) {
    mat4 retMat = mat4(1.0);
    if (boneIDs[boneIndex] != 0) {
        retMat = boneMatrices[boneIDs[boneIndex]];
    }
    return retMat;
}

float getWeight(int boneIndex) {
    float res = 1.0;
    if (boneIDs[boneIndex] != 0) {
        res = boneWeights[boneIndex];
    }
    return res;
}

void main() {
    vec3 EC_Light_location = vec3(0.0, 1.0, 1.0);

    float diffuse_weight = phong_weightCalc(
        normalize(EC_Light_location),
        normalize(normal)
    );

    fragmentColor = clamp(
        (
            // global component
            (vec4(0.2, 0.2, 0.2, 1.0))
            // material's interaction with the direct light from
            // the light.
            + (vec4(0.8, 0.8, 0.8, 1.0) * diffuse_weight)
        ),
        0.0, 1.0);

    float totalWeight = 0.0;
    vec4 PosL = vec4(0.0, 0.0, 0.0, 1.0);
    for (int i = 0; i < MAX_BONES_PER_VERTEX; i++) {
        float w = getWeight(i);
        PosL += w * (vec4(vertex, 1.0) * getBoneMatrix(i));
        totalWeight += w;
    }
    PosL /= totalWeight;
    PosL.w = 1.0;

    gl_Position = proj * modelview * PosL;
}

```

The question is, can someone point out what is wrong with the code?

Thank you very much.

**PS.** If you need any more information, please let me know in the comments.

**Edit 1.** I've changed the vertex shader code a bit - final vertex is calculated in a different way, but still it does not seem to solve my problem.

# Answer
Looking at your screenshot I'd say you need to transpose your bone matrices, that should fix your problem.
> 3 votes

---
Tags: opengl, glsl, skeletal-animation, skinning, delphi
---


# Question
Title: Is this a good approach for me to design the classes in my game?
I was searching for XNA tutorial in Youtube and I found this http://www.youtube.com/watch?v=MxucTn2HYxY

I was wondering if this is a good way to design the overall structure/classes for my game I'm trying to do. Basically, my game is almost the same as what this tutorial teaches ( A top down shooter ) , except that mine has inventory system. And is this some sort of design pattern or something? I can't really identify it IF it is...

For code example,

```
class Obj  {
    public Obj(Vector2 pos) {
        this.pos = pos;
    }
    public virtual void LoadContent(ContentManager Content) {
        // Load Texture , spriteIndex
    }
    public virtual void Update() {
        // Update
    }

    public virtual void Draw(SpriteBatch sb) {
        // draw
    }
}

class Items  {
    public static List<Obj> objList = new List<Obj>();

    public static void Initialize() {
        for (int i = 0 ; i < 64; i++ ) {
            Obj o = new Bullet(Vector2.Zero);
            o.alive = false;
            objList.Add(o);
        }
        objList.Add(new Wall(new Vector2(100, 120)));
        objList.Add(new Wall(new Vector2(550, 130)));
        objList.Add(new Man(new Vector2(50, 50)));
        objList.Add(new Cursor(new Vector2(50, 50)));
    }
}

class Man : Obj  {
    public Man(Vector2 pos) : base(pos)
    {
        pos = this.pos;
        speed = 2;
        spriteName = "P";
    }

    public override void Update() {
        // Update
        base.Update();
    }

    public override void Draw(SpriteBatch sb) {
        // Draw the HUD
        base.Draw(sb);
    }
 }

```

# Answer
The best way to learn good and bad design is to read and write ***lots*** of code, as well as reading books and blog articles and watching videos. Eventually you'll have a feel for (and an opinion on) what's good and what's not. Asking "is this good" on a Q&A site isn't going to help you much.

For readability, I might change the way you're naming things. In general, abbreviations (like `Obj` and `pos`) should be avoided for clarity's sake. And Hungarian notation doesn't add much benefit, especially if you're using tools like Visual Studio and Resharper.

Put some thought into your naming. What is an `Obj` or an `Item`? Can they be any old thing, or are they "game entities" or "inventory items"? Be as specific is possible, because in a year when you come back to this code base, you're going to rely on good naming to understand what the heck is going on.
> 1 votes

---
Tags: xna
---


# Question
Title: XNA clip plane effect makes models black
When using this effect file:

```
float4x4 World;
float4x4 View;
float4x4 Projection;

float4 ClipPlane0;

void vs(inout float4 position : POSITION0, out float4 clipDistances : TEXCOORD0)
{
    clipDistances.x = dot(position, ClipPlane0);
    clipDistances.y = 0;
    clipDistances.z = 0;
    clipDistances.w = 0;

    position = mul(mul(mul(position, World), View), Projection);
}

float4 ps(float4 clipDistances : TEXCOORD0) : COLOR0
{
    clip(clipDistances);

    return float4(0, 0, 0, 0);
}

technique
{
    pass
    {
        VertexShader = compile vs_2_0 vs();
        PixelShader = compile ps_2_0 ps();
    }
}

```

all models using this are rendered black. Is it possible to render them correctly?

# Answer
> 1 votes
Your models are being rendered black because of the line `return float4(0, 0, 0, 0)` in the pixel shader; the return value for this method is the colour (in RBGA) that is being displayed (in your case, black). You are returning the same value irrespective of the model, which is causing your problem.

You need to write some code for your pixel shader to calculate the right colour values for your models. I suggest taking a look at a few tutorials such as this one so that you get the hang of how to write shader code.

---
Tags: xna, effect
---


title: Real Time vs Turn Based (XNA)

text:
# Question
Title: Real Time vs Turn Based (XNA)
What is a more difficult type of game to develop on XNA: A Real Time multiplayer game or a Turn Based multiplayer game? (not client server or peer to peer, just in general)

Any links to articles would be greatly appreciated!

# Answer
> 1 votes
I dont think any of them are any more harder than the other, both of them are hard beacuse it´s multiplayer.

If you just sit down and carefully plan all your design you will mostlikley endup with a overall good devlopment on what ever game you do ( realtime or turnbased ).

---
Tags: xna, multiplayer
---


# Question
Title: Transform translation relative to world space
What is common algorithm for translating a transform matrix relative to world space axis?
E.g. Matrix M is representing some local space.
When I want to translate M relative to it's own local axis, I just do it like
M.Translate(translationVector);

But what should I do when I want to translate same matrix but relatively to world space axis?

# Answer
> 0 votes
pseudo code:

```
Vector mLocation = (M.41, M.42,M.43);

mLocation += normalizedWorldAxis * distanceToMove;

M.41 = mLocation.x;
M.42 = mLocation.y;
M.43 = mLocation.z;

```

# Answer
> 2 votes
In general you do not translate transforms. You translate *points* which are usually represented by *vectors*.

If you're wondering how to generate a transformation that produces a translation relative to the world axis, then you should look into homogeneous coordinates.

---
Tags: matrix, transformation
---


# Question
Title: Animating a background 'pulse' with easing equation
I'm trying to find a suitable easing equation (or other method) to animate an object so that it 'pulses' (imagine a 'spike' on a music visualiser, or see the image I drew badly below)

'v' is the value I'm using to scale. 't1' and 't2' mark the end of a single pulse.

The game I'm working on is a puzzler, but I'd like to have objects in the background pulse in time with user-selected music.

I'm sure it's just a case of knowing what to search for, but any advice would be appreciated on how best to achieve this.

# Answer
My answer is similar to Miro's, but I think the Math ought to be a lot simpler. Of course, the details of your curve make all the difference. If you don't care precisely what the curve looks like, then all you need is the basic sawtooth.

```
var clock = function(x) {
  return (1-x) - floor(1-x);  //I like this method, though not the simplest.
}

var clockVal = clock(time);

```

That yields:

If you want to make it more curvy, raise it to some power:

```
var clockVal = Math.pow(clock(time), 2);
var clockVal = Math.pow(clock(time), 3);

```
> 3 votes

# Answer
I assume that you want to create periodic function so you need to periodize x:

```
p(x) = x/T - floor(x/T)

```

Then you'll create rational function from two linear functions.

```
f(x) = ( a*x + b ) / ( c*x + d )

```

You've got 2 points \[0,V\], \[1,0\] and together you have:

```
f(x) = (V - V * p(x)) / (1 + p(x) * shape)

```
> 2 votes

---
Tags: javascript, animation, easing
---


# Question
Title: Sprite rotation and question about sampler state
I'm not an expert in creating game engines, but I'm doing fine for now. Recently I reached a point that I couldn't solve any of my problems. I have two questions:

1. I'm using `D3DXMatrixTransformation2D` to produce the transformation matrix for my sprites, but I have a problem with rotation. Whenever I try to set a rotation for my sprite, it does turn when there is a fixed value of rotation. If I give 0.5f it won't rotate, but when I set 1, 2, 3, ... it'll work and that's not really cool. And, I searched a lot about `pScalingRotation` but it seems it's hasn't any influence. My rotation's value is fine, but the produced matrix doesn't act the way I expect it to.
2. I want to get a smooth edge for my sprites when they're rotating and I saw `p_device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);`. Where should I set the sampler state? After creating the device or after every update? And, what about texture filters? I use `D3DXCreateTextureFromFileEx` to load textures from file and it has `Filter` and `MipFilter`. Are these related to the sampler state?

# Answer
1. What is the produced rotation matrix when you insert a value like 0.5f? And how doesn't it work, do you mean that 1.5f would produces the same visual result as 1.0f? What happens when you construct a rotation matrix manually? (See here how to construct them)
2. The MAGFILTER (magnification) is the filter used when pixel density in the source texture is lower than the pixel density on screen of the textured object (when the opposite is true the MINFILTER (minification) is used). It will not change the smoothness of the borders of a sprite when its rotated, for that you need to use an anti-aliasing technique.
> 0 votes

---
Tags: directx
---


title: Most Needed Open Source Project

text:
# Question
Title: Most Needed Open Source Project
A few questions on the site have mentioned the need for more open source projects. I agree and wonder what frameworks should be developed.

I'll start the list.

* A geometry kernel, including serialization (JSON, binary, compressed binary), tailored for OpenGL/DirectX
* Gesture recognition

# Answer
I've already complained about this in another question, but having open digital distribution systems would be glorious. This encompasses both patching systems and end-user marketplace type things. Steam handles a lot of this, but is far from an open platform. Even if it wasn't a single shared marketplace like Steam is (or how phone marketplaces are going), having a solution you could easily rebrand and deploy for yourself would be a huge step forward (assuming people actually did things like submit patches upstream and all that FOSS goodness).
> 43 votes

# Answer
Graphics driver develpers. Without working graphics drivers other game-related projects are irrelevant.

AMD and NVIDIA actually do make usable drivers, but I'm talking about open-source drivers. Mesa only supports OpenGL 2.1.

edit: This answer is only applicable to GNU/Linux.
> 5 votes

# Answer
Not a software project, but a documentation one:

**A game technical quality checklist** (like trcs or tcrs)

Many a time the design of a production game has been affected by these quite important documents. Indie games need them as much as professional games developers do, as it's at least a simple assurance that you've done a reasonable job.

**Certification**

There couldn't be a certifying body, but it could be a self certifying thing to start with.

If the checklist was concise, it could more easily become a generally agreed upon checklist. Once agreed upon, it might then become reasonable for distributors to allow peer review to confirm or deny claims whereupon the information becomes part of the distributors basic information package about items in its store.

**Location**

Why not start one on the game dev wiki... http://wiki.gamedev.net/index.php/Main\_Page ?
> 4 votes

# Answer
A generic, cross-platform game editing tool that allows you to edit game content (2D and 3D) for any game engine. It can be supplemented by editing & export plugins for a specific game engine, or for a specific game genre's editing needs (eg. 3D platform game editor, 2D user interface editor, 3D tilemap editor, etc).

Rationale: most open source game engines do not provide editing tools. Most existing game editing tools are proprietary and only work with the vendor's game engine (Torque, Unity, Shiva, etc.), or have a limited use (2D Tilemap editing). If you switch engines or platforms, you usually have to leave whichever tools you were working with behind and either learn or even write a new tool, or work without any tools at all.

What do you think of this idea? Do you think it's desireable? And would it be feasible?
> 4 votes

# Answer
A Geometry kernel also begs for an Animation Kernel, including blending.
> 3 votes

# Answer
A good Flash player, since Adobe seems uninterested / underfunded in really working on theirs on non-Windows OSs, and the existing implementations are lacking (even e.g. ScaleForm has significant problems being "proper Flash" as designers/artists expect).
> 2 votes

# Answer
I guess that open service for custom avatar sprites would be useful especially with the growth of online and mobile HTML5-based games. I described the idea here.
> 1 votes

# Answer
EA STL (or equivalent).
> 1 votes

# Answer
An stl-like collection of templated datastructures often used in games:

* \[hierarchical\] state machines
* quad-/octrees
* bsp trees
* sphere trees
* kd trees
* \[any other useful spatial datastructure not listed\]
* resource managers
* linear/pool/other allocators
* timers
* decision trees

It would be really nice to have theese available in an easy to use form that's known to be well tested and stable.

While open source implementations of some of the data structures listed exist, they're often not templated to use any data type (e.g. you're often forced to use yet another matrix/vector structure), not in a usable state, dead or lack peer review and testing.
> 1 votes

# Answer
Networking.

For starters, a good system for NAT (Network Address Traversal) and routing, to combat any woes with firewalls and proxies. PC gamers should never have to deal with forwarding ports or anything similar.

Even better: An open-source, distributed multiplayer game network (eg. Battle.net, Xbox Live, PSN...). This would essentially be a protocol that anyone can implement, and anyone can run a server - they just communicate with each other to pass around information about who can be found where. Similar to distributed social networks (eg. Diaspora), this keeps any one party from having control, whilst allowing any indie game to seamlessly integrate into it.

Imagine if you could just add your friends as 'friends', and then any game you ever played you could just invite them straight away, no ip addresses, no id lookups, you just take them with you. Basically what B.net/XBL/PSN do already, but open and free for all!
> 0 votes

# Answer
A real MMO platform, ie. one that supplies the middleware, lobby functions, etc, into which you can plug in your engine.
> -2 votes

---
Tags: open-source
---


title: good struct for making items in game

text:
# Question
Title: good struct for making items in game
i am trying to make a java game. i have a spaceShip(player) on left. you can go up and down, and shoot bullets. from right side enemy keep on coming and shoot bullets. you have to avoid them and kill as many you can.
i want random items coming from right side of window. and x-=dx going left slowly.
u start with normal bullets, one bullet per timer.
item1 - get half life bar
item2 - get full life bar
item3 - bullets change - shoot double bullets at same time.
item4 - bullets change - bullet goes up down up down....
i will be only have two types of item. can some one tell me a good struct in oop for this.

i know the basic of oop and game programming but i am still new at it. so try to explain as much as you can plz.

# Answer
When designing an item system, or in reality any system requiring collections of whatever, you should begin by considering what type of functionality is shared by all objects in these collections. For instance, all items may need to be rendered to the screen, all items have a quantity, all items require collision detection, etc. So starting with this, begin creating base classes that contain the similar functionality between items, but allow for unique derivations for customized behavior. Here is an example, written in pseudo code.

This first class represents a base class called Item, which would extend the abstract class renderable. Whenever extending from another class, always ensure you consider whether or not your class "Is A" or "Contains A". For instance, an item "Is A" renderable object, or does it "Contain A" renderable object. Depending on your architecture, this could be different.

This item class implements basic functionality and variables that would be common to all types of items, such as a name, quantity, and the callback OnCollision that is triggered whenever something collides with it.

```
class item implements renderable
{
  string mName;
  int mQuantity;

   Draw();
   Update();
   OnCollision();
}

```

Next is the item class Banana, which is extended from Item. Notice i specified override for the functions within banana, meaning that it is receiving this base functionality from item, but is choosing to override it to provide customized behavior based on whatever banana needs to do.

```
class Banana implements item
{
  overrides Update();
  overrides Draw();
  overrides OnCOllision();
}

```
> 4 votes

---
Tags: oop
---


# Question
Title: Adding local wireles multiplayer mode to my Android game
I've created a little game on Android. Now, I want to add a multiplayer mode which works with bluetooth or WiFi, so you can play together with other "smartphones" in your neighborhood . Which is the best way to offer a fast, good working mulitplayer mode that supports so many devices as possible? I heard about Alljoyn, but Im not quite sure if it fits my needs. Which way do you recommend?

regards Lisa

# Answer
I would consider the requirements of your multiplayer experience. For a quick two week prototype I put together a couple months ago, I was on the ropes about whether or not to support TCP/WiFi connectivity between devices, or simply go with bluetooth. I chose to go with bluetooth due to the reliability of it in comparison with the local network I was dealing with, and the simple data format I was sending (XML). I wrote the bluetooth connectivity using the native android SDK, and was able to get it up and running within a day or two.

Additionally, consider whether or not you will be hosting the game externally, or requiring one of the devices to act as a host. If you plan on having more than a couple of devices connected at once, you may want to consider an external service (or at least extra device) dedicated to managing connections and processing requests.

*edit* also, bluetooth has very limited physical range, thus that may eliminate it as an option immediately.
> 1 votes

---
Tags: android, multiplayer
---


title: Stereo music playing in mono in libGDX

text:
# Question
Title: Stereo music playing in mono in libGDX
I'm trying to get some music to play back in stereo in libGDX, but it seems to be blending the left and right channels so much that it sounds like it was mono.

To test this out I made a sound file that is just me saying "left" in the left channel and "right" in the right channel. After playing this through libGDX's music class it has blended the channels to the point where the difference is only slight. This is much more noticeable with stereo music where the difference is smaller to begin with.

Here are the sounds themselves. The first one is the input file as I recorded it, and the second is the output recorded from the game:

http://www.jimmakesgames.com/leftRightInput.wav

http://www.jimmakesgames.com/leftRightOutput.wav

You can hear the difference very clearly with headphones. I've looked high and low and can't find anything about this. The libGDX audio stuff seems to be pretty much a black box. The only reference I found to setting stereo or mono is with the newAudioDevice method which is only for writing PCM data directly.

I'm pretty desperate at this point, so if anyone can offer some assistance it would be greatly appreciated. Thanks.

# Answer
> 3 votes
I'm not sure how libGDX blends the audio because in the source its precompiled code. However I did try something that may or may not be something that could help you. I took your leftRightInput.wav file and split up the tracks into two separate files. One for the left channel and one for the right channel (I used Audacity). I loaded them both as Music objects then I lowered the right channel's volume a bit to try to better distinguish between the channels.

```
Music left = Gdx.audio.newMusic(Gdx.files.internal("left.wav"));
Music right = Gdx.audio.newMusic(Gdx.files.internal("right.wav"));
right.setVolume(0.5f);
left.play();
right.play();

```

Maybe give this a try and see if it will fit your needs. If not I would suggest posting directly on the libGDX forums and see if they plan to expand on the Music and Sound classes.

---
Tags: libgdx, audio
---


# Question
Title: Understanding marching cubes and voxel data relationships
in case it matters i'm doing all this in unity with C# ...

I think I missed something or maybe don't understand the logic correctly. I have an existing voxel engine that looks very "minecrafty" at the moment, and I want to step it up a bit so it actually looks reasonably good!

So lets say I have a "chunk", and common sense says that a chunk can either be on or off in a voxel world so its basically a "point cloud" (you either render it or you dont). This means my game engine has something like this ...

```
public class Chunk
{
    public Block[,,] Blocks;
    ... other stuff
}

public class Block
{
    public bool Active;
    ... other stuff
}

```

So bring in the marching cubes and part 1 of Paul Bourke's guide (http://paulbourke.net/geometry/polygonise/) says ....

> The first part of the algorithm uses a table (edgeTable) which maps the vertices under the isosurface to the intersecting edges. An 8 bit index is formed where each bit corresponds to a vertex.

```
   cubeindex = 0;
   if (grid.val[0] < isolevel) cubeindex |= 1;
   if (grid.val[1] < isolevel) cubeindex |= 2;
   if (grid.val[2] < isolevel) cubeindex |= 4;
   if (grid.val[3] < isolevel) cubeindex |= 8;
   if (grid.val[4] < isolevel) cubeindex |= 16;
   if (grid.val[5] < isolevel) cubeindex |= 32;
   if (grid.val[6] < isolevel) cubeindex |= 64;
   if (grid.val[7] < isolevel) cubeindex |= 128;

```

Now here's what throws me ... I'm comparing my "grid data" (so basically my block data) to some "isolevel" value. Every implementation i've seen (the easiest being here: http://nucleardevs.wordpress.com/2011/11/17/marching-cubes-sourcecode/) does exactly that but it creates a load of float values using something like simplex or perlin noise and runs through this logic.

floats? not bools?

So ...

Given a Block\[,,\] if i check each blocks state (Active property) and return a simple true or false ... why do i need a float / double value or should I say ... what is the purpose of the float value that requires it to be a float and not a simple boolean?

I gather they are referred to as "densities" which implies that I missed something because i've been thinking of them as the point cloud data to be evaluated and a voxel (to my knowledge) isn't a "density" value its more like a switch (on off).

# Answer
> 3 votes
Using float values allows you to use linear interpolation to enable you to make a mesh that's more accurate to your data. With many of the blocky type terrains you see in games these days, they just decide at what density a voxel is "solid". With noise values ranging between 0 and 1, they decide a value to split the float and round to 1 or 0.

However, many of the blocky voxel games aren't using marching cubes to generate their terrain meshes. Keeping the float values allows your marching cubes more accuracy. As I'm sure you're familiar with the marching cubes algorithm, having the float values allows you to shift the vertices of your triangles along the edges of the cubes depending on the adjacent floating point values.

# Answer
> 4 votes
The density field is used to smooth out the curves. If you populate the field with simple true/false values you get blocky, Minecaft-like terrain. A voxel can be a floating-point value or a boolean value, just like a pixel can be a floating-point value or a boolean value (such as in masks). A pixel is a picture (2D) element; a voxel is a volume (3D) element.

Example using boolean values:

Example using floating-point values:

Also, you shouldn't be representing individual voxels as classes. C# implements these as reference types, meaning a lot of overhead for something that should be plain old data, i.e. a struct.

---
Tags: c#, unity, voxels, marching-cubes
---


# Question
Title: How should I store resources generated at runtime?
I in my game I generate some images at runtime depending upon the size of the text that will go over it. Right now I am storing these in a hashmap using a string resembling the text. The question is, is there are better way to do this? Like some sort of ID system?

Also, I would like to expand this to not only be limited to images for when/if I want to include sounds or other resources.

# Answer
> 1 votes
The hashes seem unnecessary, you could store the pointers in a simple array and just give each image an id ranging from `0` to `n-1`.

While your current system does generate some overhead due to using a hash map, it is probably nothing major. So if it seems to work OK I see little reason to change it.

---
Tags: java, assets
---


# Question
Title: Creating the Animations in C++ from 3DS Max
I'm reading from the FBX format and I'm using Bones to animate an object, and I'm at the point where I have to decide on the code that actually moves the vertexes.

So far I thought on two methods:

Create a **bone** class that has an array of XYZ and an array of vertexes addresses and the weight. The array of XYZ (and rotations' values) will be filled from their positions/rotations at every frame. My model object will have an array of this bones class, and at each call I'll update the vertexes by multiplying the bones' XYZ for the vertexes, something like:

```
for(int i = 0; i < object->bonesCount; i++)
{
    for(int j = 0; j < object->bones[i]->vertexesCount; j++)
    {
        object->bones[i]->vertex[j].xyz *= object->bones[i].xyz; //plus rotation
    }
}

```

And the second method is having an array of vertexes * amount of frames, I do something like the above code and I save each vertexes' positions at every frame in the array, so I don't have to call the loop above (I think it might impact performance), but I'd have much more arrays to work with.

So my questions are, (1) which is the best approach for this, and (2) is there another method I didn't think of? Any info related to this is appreciated, as I have nothing done yet and I'm still elaborating on how it should be before I start coding (I try to avoid doing the first thing I come up with so there's less chances of needing to recode it later).

Thanks!

# Answer
> 1 votes
Usually you don't want to store array of positions of vertexes per frame but rather transformations of joints. This opens room for optimisations like *interpolating* positions between poses and allows you to *blend* animations. Such transformation can be stored in efficient so called "SQT" format (Scale, Quaternion of rotation, Translation vector)

```
struct JointPose
{
   Quaternion m_rotation;
   Vector3 m_translation;
   float m_scale;
};

```

Personally I recommend Game Engine Architecture book by Jason Gregory. Chapter Animations System.

---
Tags: c++, animation, fbx
---


title: Side scrolling: how to do?

text:
# Question
Title: Side scrolling: how to do?
This question is simple, but for me is hard to do! How to implement side (horizontal and vertical) scrolling for (i.e.) a 2d car game ? Both car and background must move. How to ? Thank you!

# Answer
> 2 votes
Actually, your post indicates a very high level of laziness, but considering my novice days, I guess I might answer this.

In a top-down racing game (that is what you call a game that move on all fours, because the view is from the top of the car), basically the car is made to move over the tracks by "faking" track movement. For example: Consider the car is lying on the center of the screen. I push the move up key. We know the car has to move up the track. But what we do in actuality is we dont move the car ,but we move the track downwards. ie. for every movement of the car, the track is moved by the distance to be moved in reverse direction. So when you look at the game from the aerial point of view(top-down) you "believe" the car is moving. This is just the essence of a top-down side-scroller game.

And once you have accomplished this, you might want to add a "feel" to the acceleration. This can be done by adding a "braking factor" to the car at every instant in the gameloop also ensuring that the speed doesn't go negative.

Hoping you'd achieve what you want. Best wishes

# Answer
> 0 votes
I don't like moving the background, what I did for my 2d physics engine was:

* Make a world class.
* Make a car class.
* Position the car relative to the world.
* Make a camera class.
* Position the camera relative to the world.

When you want to move the car, just change it's position relative to the world.

**Note:**

With the camera object you can implement zoom and scrolling easily.

---
Tags: game-design
---


title: What can i use as a 3d Tile map editor?

text:
# Question
Title: What can i use as a 3d Tile map editor?
I need to make grid based levels with 3d models for a dungeon crawler ( as a recent example Legend of Grimrock), but i need to have several layers and place entities with properties and position, angle, etc. I was considering Tiled, using layers as height for each level, but it's very hard to work with and visualize. What can i use for this pourpose? The output format needs to be json, xml, or something i can use on my engine. Ideally i'd want something like Tiled with a 3d visualization/edit mode and support for loading models or at least some visual representation of them.

# Answer
> 0 votes
You can try TuDee:

http://www.diorgo.com/v1/?p=366

I have used it successfully for 3D tile-games. It exports XML, so it is easy to read into whatever game engine you are using. It supports multiple maps (useful for different levels), as well as layers, entities, custom variables, and many other features.

Here is some more info:

http://forums.indiegamer.com/showthread.php?28936-TuDee-a-free-tile-based-map-editor

---
Tags: 3d, tilemap, map-editor, world-editor
---


# Question
Title: How do I create 2D water with dynamic waves?
*New Super Mario Bros* has really cool 2D water that I'd like to learn how to create.

Here's a video showing it. An illustrative part:

Things hitting the water create waves. There are also constant "background" waves. You can get a good look at the constant waves just after 00:50 in the video, when the camera isn't moving.

I assume the splash effects work as in the first part of this tutorial.

However, in *NSMB* the water also has constant waves on the surface, and the splashes look very different. Another difference is that in the tutorial, if you create a splash, it first creates a deep "hole" in the water at the origin of the splash. In new super mario bros this hole is absent or much smaller. I am referring to the splashes that the player creates when jumping in and out of the water.

**How do I create a water surface with constant waves and splashes?**

I am programming in XNA. I've tried this myself, but I couldn't really get the background sine waves to work well together with the dynamic waves.

I am not asking how the developers of *New Super Mario Bros* did this exactly—just interested in how to recreate an effect like it.

# Answer
I tried it.

# Splashes (springs)

As that tutorial mentions, the surface of water is like a wire: If you pull on some point of the wire, the points next to that point will be pulled down too. All points are also attracted back to a baseline.

It's basically lots of vertical springs next to each other that pull on each other also.

I sketched that in Lua using LÖVE and got this:

Looks plausible. Oh Hooke, you handsome genius.

If you want to play with it, here is a JavaScript port courtesy of Phil! My code is at the end of this answer.

# Background waves (stacked sines)

Natural background waves look to me like a bunch of sine waves (with different amplitudes, phases and wavelengths) all summed together. Here's what that looked like when I wrote it:

The interference patterns look pretty plausible.

# *All together now*

So then it's a pretty simple matter to sum together the splash waves and the background waves:

When splashes happen, you can see small grey circles showing where the original background wave would be.

It looks a lot like that video you linked, so I'd consider this a successful experiment.

Here's my `main.lua` (the only file). I think it's quite readable.

```
-- Resolution of simulation
NUM_POINTS = 50
-- Width of simulation
WIDTH = 400
-- Spring constant for forces applied by adjacent points
SPRING_CONSTANT = 0.005
-- Sprint constant for force applied to baseline
SPRING_CONSTANT_BASELINE = 0.005
-- Vertical draw offset of simulation
Y_OFFSET = 300
-- Damping to apply to speed changes
DAMPING = 0.98
-- Number of iterations of point-influences-point to do on wave per step
-- (this makes the waves animate faster)
ITERATIONS = 5

-- Make points to go on the wave
function makeWavePoints(numPoints)
    local t = {}
    for n = 1,numPoints do
        -- This represents a point on the wave
        local newPoint = {
            x    = n / numPoints * WIDTH,
            y    = Y_OFFSET,
            spd = {y=0}, -- speed with vertical component zero
            mass = 1
        }
        t[n] = newPoint
    end
    return t
end

-- A phase difference to apply to each sine
offset = 0

NUM_BACKGROUND_WAVES = 7
BACKGROUND_WAVE_MAX_HEIGHT = 5
BACKGROUND_WAVE_COMPRESSION = 1/5
-- Amounts by which a particular sine is offset
sineOffsets = {}
-- Amounts by which a particular sine is amplified
sineAmplitudes = {}
-- Amounts by which a particular sine is stretched
sineStretches = {}
-- Amounts by which a particular sine's offset is multiplied
offsetStretches = {}
-- Set each sine's values to a reasonable random value
for i=1,NUM_BACKGROUND_WAVES do
    table.insert(sineOffsets, -1 + 2*math.random())
    table.insert(sineAmplitudes, math.random()*BACKGROUND_WAVE_MAX_HEIGHT)
    table.insert(sineStretches, math.random()*BACKGROUND_WAVE_COMPRESSION)
    table.insert(offsetStretches, math.random()*BACKGROUND_WAVE_COMPRESSION)
end
-- This function sums together the sines generated above,
-- given an input value x
function overlapSines(x)
    local result = 0
    for i=1,NUM_BACKGROUND_WAVES do
        result = result
            + sineOffsets[i]
            + sineAmplitudes[i] * math.sin(
                x * sineStretches[i] + offset * offsetStretches[i])
    end
    return result
end

wavePoints = makeWavePoints(NUM_POINTS)

-- Update the positions of each wave point
function updateWavePoints(points, dt)
    for i=1,ITERATIONS do
    for n,p in ipairs(points) do
        -- force to apply to this point
        local force = 0

        -- forces caused by the point immediately to the left or the right
        local forceFromLeft, forceFromRight

        if n == 1 then -- wrap to left-to-right
            local dy = points[# points].y - p.y
            forceFromLeft = SPRING_CONSTANT * dy
        else -- normally
            local dy = points[n-1].y - p.y
            forceFromLeft = SPRING_CONSTANT * dy
        end
        if n == # points then -- wrap to right-to-left
            local dy = points[1].y - p.y
            forceFromRight = SPRING_CONSTANT * dy
        else -- normally
            local dy = points[n+1].y - p.y
            forceFromRight = SPRING_CONSTANT * dy
        end

        -- Also apply force toward the baseline
        local dy = Y_OFFSET - p.y
        forceToBaseline = SPRING_CONSTANT_BASELINE * dy

        -- Sum up forces
        force = force + forceFromLeft
        force = force + forceFromRight
        force = force + forceToBaseline

        -- Calculate acceleration
        local acceleration = force / p.mass

        -- Apply acceleration (with damping)
        p.spd.y = DAMPING * p.spd.y + acceleration

        -- Apply speed
        p.y = p.y + p.spd.y
    end
    end
end

-- Callback when updating
function love.update(dt)
    if love.keyboard.isDown"k" then
        offset = offset + 1
    end

    -- On click: Pick nearest point to mouse position
    if love.mouse.isDown("l") then
        local mouseX, mouseY = love.mouse.getPosition()
        local closestPoint = nil
        local closestDistance = nil
        for _,p in ipairs(wavePoints) do
            local distance = math.abs(mouseX-p.x)
            if closestDistance == nil then
                closestPoint = p
                closestDistance = distance
            else
                if distance <= closestDistance then
                    closestPoint = p
                    closestDistance = distance
                end
            end
        end

        closestPoint.y = love.mouse.getY()
    end

    -- Update positions of points
    updateWavePoints(wavePoints, dt)
end

local circle = love.graphics.circle
local line   = love.graphics.line
local color  = love.graphics.setColor
love.graphics.setBackgroundColor(0xff,0xff,0xff)

-- Callback for drawing
function love.draw(dt)

    -- Draw baseline
    color(0xff,0x33,0x33)
    line(0, Y_OFFSET, WIDTH, Y_OFFSET)

    -- Draw "drop line" from cursor

    local mouseX, mouseY = love.mouse.getPosition()
    line(mouseX, 0, mouseX, Y_OFFSET)
    -- Draw click indicator
    if love.mouse.isDown"l" then
        love.graphics.circle("line", mouseX, mouseY, 20)
    end

    -- Draw overlap wave animation indicator
    if love.keyboard.isDown "k" then
        love.graphics.print("Overlap waves PLAY", 10, Y_OFFSET+50)
    else
        love.graphics.print("Overlap waves PAUSED", 10, Y_OFFSET+50)
    end

    -- Draw points and line
    for n,p in ipairs(wavePoints) do
        -- Draw little grey circles for overlap waves
        color(0xaa,0xaa,0xbb)
        circle("line", p.x, Y_OFFSET + overlapSines(p.x), 2)
        -- Draw blue circles for final wave
        color(0x00,0x33,0xbb)
        circle("line", p.x, p.y + overlapSines(p.x), 4)
        -- Draw lines between circles
        if n == 1 then
        else
            local leftPoint = wavePoints[n-1]
            line(leftPoint.x, leftPoint.y + overlapSines(leftPoint.x), p.x, p.y + overlapSines(p.x))
        end
    end
end

```
> 154 votes

# Answer
For the solution (mathematically speaking you can solve the problem with the solving of differential equations, but im sure they don't do it that way) of creating waves you have 3 possibilities(depending on how detailed it should get):

1. Calculate the waves with the trigonometric functions (most simple and the fastest)
2. Do it like Anko has proposed
3. Solve the differential equations
4. Use texture lookups

## Solution 1

Really simple, for each wave we calculate the (absolute) distance from each point of the surface to the source and we calculate the 'hight' with the formula

`1.0f/(dist*dist) * sin(dist*FactorA + Phase)`

where

* dist is our distance
* FactorA is a value which means how fast/dense the waves should be
* Phase is the Phase of the wave, we need to increment it with time to get an animated wave

Note that we can add as many terms together as we like (superposition principle).

**Pro**

* Its really fast to calculate
* Is easy to implement

**Contra**

* For (simple) reflections on a 1d Surface we need to create "ghost" wave sources to simulate reflections, this is more complicated at 2d surfaces and it is one of the limitations of this simple approach

## Solution 2

**Pro**

* Its simple too
* It allows to calculate reflections easily
* It can be extended to 2d or 3d space relativly easily

**Contra**

* Can get numerically instable if the dumping value is too high
* needs more calculation power than Solution **1** (but not so much like Solution **3**)

## Solution 3

Now i hit a hard wall, this is the most complicated solution.

I didn't implement this one but it is possible to solve these monsters.

Here you can find a presentation about the mathematics of it, its not simple and there exists also differential equations for different kinds of waves.

Here is a not complete list with some differential Equations to solve more special cases (Solitons, Peakons, ...)

**Pro**

* Realistic waves

**Contra**

* For most games not worth the effort
* Needs the most calculation time

## Solution 4

A bit more complicated than solution 1 *but* not so complicated a solution 3.

We use precalculated textures and blend them together, after that we use displacement mapping (actually a method for 2d waves but the principle can also work for 1d waves)

The game sturmovik has used this approach but i don't find the link to the article about it.

**Pro**

* it is more simple than 3
* it gets good looking results (for 2d)
* it can look realistic if the artists good a great job

**Contra**

* difficult to animate
* repeated patterns could get visible on the horizon
> 11 votes

# Answer
To add constant waves add a couple of sine-waves after you have calculated dynamics. For simplicity I would make this displacement a graphical effect only and not let it affect the dynamics themselves but you could try both alternatives and see which works out the best.

To make the "splashhole" smaller I would suggest altering the method Splash(int index, float speed) so that it directly affects not only index but also some of the close vertices, so as to spread out the effect but still have the same "energy". The number of vertices affected could depend on how wide your object is. You'll probably need to tweak the effect a lot before you have a perfect result.

To texture the deeper parts of the water you could either do as described in the article and just make the deeper part "more blue" or you could interpolate between two textures depending on the depth of the water.
> 6 votes

---
Tags: 2d, physics, simulations, water
---


# Question
Title: Rendering a black and white image in OpenGL 1.1
Is there is any way that I can simple disable the color in OpenGL 1.1? Or can I "grey out" textures in LWJGL?

# Answer
> 4 votes
In OpenGL 1.1 there is really no way to do this efficiently. You may be able to do something with glCopyTexSubImage2D to a GL\_LUMINANCE target texture, but (IIRC) that will sum the colour channels during the copy process so you'll lose a good deal of brightness. Or you could load a second (greyscaled) copy of all your textures and use those instead, at the cost of increased video RAM usage. But just being able to say "give me a greyscale output from this" is something that you won't be able to do.

So you're going to have to move up a little. For example, if you have the imaging subset available you could apply a color matrix which would achieve the greyscaling. Better yet, with a fragment shader it's just a simple dotproduct operation.

All of this begs the question - Why are you restricting yourself to OpenGL 1.1? The last hardware that only supported 1.1 was in 1997 or thereabouts, and shaders have been absolutely ubiquitous for a decade or so. These certainly aren't fancy new features that you'd be taking a risk on; they're mainstream even down to the lowest of low-end.

So this isn't the answer you're looking for but then again neither is OpenGL 1.1 - just move up to a higher version and use it's capabilities.

---
Tags: opengl, rendering, lwjgl, color
---


title: simple win32 window wont show

text:
# Question
Title: simple win32 window wont show
The program compiles and runs successfully but does not show a window, it simply ends immediately.

```
#include <Windows.h>

LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);

int WINAPI wWinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPWSTR CmdLine, int CmdShow )
{
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(CmdLine);

    WNDCLASSEX wndClass = {0};

    wndClass.cbSize = sizeof(WNDCLASSEX);
    wndClass.style = CS_HREDRAW | CS_VREDRAW;
    wndClass.lpfnWndProc = WndProc;
    wndClass.hInstance = hInstance;
    wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
    wndClass.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
    wndClass.lpszMenuName= NULL;
    wndClass.lpszClassName= "DX11BookWindowClass";

    if(!RegisterClassEx(&wndClass));
        return -1;

        RECT rc = {0,0,640,480};
        AdjustWindowRect(&rc,WS_OVERLAPPED,FALSE);

        HWND hwnd = CreateWindowA( "DX11BookWindowClass", "FirstWinProgram", WS_OVERLAPPEDWINDOW,
                                CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top,
                                NULL, NULL, hInstance, NULL );

        if(!hwnd)
            return -1;

        ShowWindow(hwnd,CmdShow);

        MSG msg = {0};

        while( msg.message != WM_QUIT )
        {
            if( PeekMessage(&msg,0,0,0,PM_REMOVE) )
            {
                TranslateMessage( &msg );
                DispatchMessage( &msg );
            }
            else
            {
                //Update
                //Draw
            }

        }
        //Demo ShutDown

        return static_cast<int>(msg.wParam);
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    PAINTSTRUCT paintstruct;
    HDC hDC;

    switch(message)
    {
    case WM_PAINT:
        {
        hDC = BeginPaint( hwnd,&paintstruct);
        break;
        }
    case WM_DESTROY:
        {
        PostQuitMessage( 0 );
        break;
        }
    default:
        {
        return DefWindowProc( hwnd, message, wParam, lParam);
        }

    }
    return 0;
}

```

# Answer
oh dear...classic typo

```
if(!RegisterClassEx(&wndClass)); <---- typo, remove the ; that it works
return -1;

```

this means that the program always returns there

work on your coding style (i recommend to use everytime braces)
> 0 votes

---
Tags: c++, directx, game-loop, win32
---


# Question
Title: Level Modeling Workflows in Maya for Unity
I'm wondering what the standard workflow for modeling static levels for Unity (or for that matter, other High-Level engines) is? My somewhat limited knowledge tells me that the best process is modeling the entire static level in Maya, texturing, then baking AO and some static lighting into the scene, then importing the single level asset into unity to add dynamic objects.

Is there another way that I should be doing this that is more efficient in a performance sense or from a workflow point of view?

I know the question is somewhat open ended, but generally i'm asking what the standard workflow for level modeling is.

Thanks!

# Answer
> 0 votes
I am not an real modeling guy and my level design experience is also limited but i honestly give you some guidelines

* Do model each model and instatiate them in your level with the Unity editor

This does have the advantage that you can use your statics for other elvels or that you can alter your level quickly without going into maya and exporting it again into unity.

You can also bake lighting with the unity editor (im not sure if AO works too).

The unity Level editor is just awesome work, so use it.

---
Tags: unity, models, level-design, maya
---


# Question
Title: How to update "dynamicVertexBuffer" correctly with "setdata" on XNA?
I developed a small 3d games xna and uses a "DynamicVertexBuffer" and "DynamicIndexBuffer" to store and draw my vertices. Everything works fine, but my problem is the "Update" function where I update my buffer. Each apel update I have to reset my buffer using the keyword "new DynamicVertexBuffer (...." It goes down the performance and reduce the frames per second of my games.

Do I have to initialize my buffer each time in my function "Update ()"? Is it okay to reset every time my buffer to each call / frame

**I can not find a solution to update correctly my Dynamicbuffer with "setData ()"** function **without having to initialize whenever my buffer just before**. Am I obliged to Reset-"DynamicVertexBuffer" and "DynamicIndexBuffer" before the update? If I call "setData ()" before reset it, I throw an exception:

**Works well but I have initialized every time "dynamicIndexBuffer" and "dynamicVertexBuffer" before update! (Consumes more resources?)**

```
    public override void Update(GameTime gameTime)
    {
                foreach (Octree.Node node in regions[regionIndex].Nodes.Where(n => n.ItemGroup == a).Where(m => arcadia.camera.Frustum.Contains(m.boundingBox) != ContainmentType.Disjoint))
                {
                    //build indices
                    node.Cube.SetUpIndices(indexIndiceBuild);
                    //Add indices tho the collectionList
                    foreach (int indice in node.Cube.Indices)
                    {
                        list_structure_indices.Add(indice);
                    }
                    //Add vertex to the collectionList
                    foreach (VertexPositionTexture posText in node.Cube.Vertices)
                    {
                        vertexPositionStructureCube.Add(posText);
                    }
                    //Add vertexBuffer to the collectionList
                    indexIndiceBuild += 24;
                }
                    //Declare and initialize new buffers
                    //VertexBuffer Initialize again
                    vertexBuffer_cube = new DynamicVertexBuffer(
                    arcadia.Game.GraphicsDevice,
                    VertexPositionTexture.VertexDeclaration,
                    vertexPositionStructureCube.Count,
                    BufferUsage.WriteOnly);

                    //VertexBuffer SetData (update)
                    vertexBuffer_cube.SetData<VertexPositionTexture>(vertexPositionStructureCube.ToArray());
                    //IndexBuffer Initialize again
                    indexBuffer_cube = new DynamicIndexBuffer(Game.GraphicsDevice, IndexElementSize.ThirtyTwoBits, list_structure_indices.Count, BufferUsage.WriteOnly);
                    //IndexBuffer SetData (update)
                    indexBuffer_cube.SetData(list_structure_indices.ToArray());
                    .........
}

```

**I'm just trying to update with "SetData" with new vertices and indices but i throws the exception:** "The array is not the proper size for the Amount of data requested."

```
    public override void Update(GameTime gameTime)
    {
                    .........
                    //Only "setdata()" without initialize buffer again ??
                    //VertexBuffer SetData (update)
                    vertexBuffer_cube.SetData<VertexPositionTexture>(vertexPositionStructureCube.ToArray());

                    //IndexBuffer SetData (update)
                    indexBuffer_cube.SetData(list_structure_indices.ToArray());

                    .........
}

```

# Answer
> -2 votes
Are your vertices changing every update? If not then you don't have to worry about updating them each frame.

---
Tags: xna, vertex, depth-buffer, index-buffer, draw-order
---