title: Objective-C or C++ for iOS games?

text:
# Question
Title: Objective-C or C++ for iOS games?
I'm pretty confident programming in Objective-C and C++, but I find Objective-C to be somewhat easier to use and more flexible and dynamic in nature.

What would be the pros and cons when using C++ instead of Obj-C for writing games in iOS? Or rather, are there any known problems with using Obj-C as compared to C++?

For instance, I *suspect* there might be performance issues with Obj-C compared to code written in C/C++.

# Answer
One big upside to C++: If you decide to do so, it'll be relatively easy to port to Android/PC/DS/PSP/(insert platform of choice here). Objective-C will lock you into iOS until you decide to rewrite the entire game.
> 21 votes

# Answer
There are no real pros or cons here, at least none that should force a programmer comfortable in one language to have to use the other.

Performance shouldn't be an issue. It's unlikely that you'd write any heavy lifting with lots of messaging in the inner loops if you're a good Obj-C programmer, which means you'll really be writing those inner loops in C. If you're not a low level programmer, chances are the heavy lifting will be done by whatever libraries you chose to defer that too, and you'll be at the mercy of whatever they've chosen to do.

Portability *is* a real issue, if you care about it. If not, then meh. Being cross platform isn't the end all be all. Being successful on one first would be nice :) You can always port later. If you're not carefully planning to be cross platform from day 1 anyway, just being in the same language won't get you very far: there are plenty of further real differences between platforms that need addressing.

Finishing the project is more important that fretting about the tech, and if you're more productive in Obj-C then stay in Obj-C.

My preference? I'm a C++ guy. I like Obj-C just fine, but I'm happy in C++, and I *do* write cross platform code.
> 16 votes

# Answer
There are no performance issues with Obj-C over C++. Both are compiled code, and recall that Obj-C is a superset of C, and Obj-C++ is a superset of C++, which is great when you want to mix Obj-C and C++ in the same program (easy to do and XCode has nice support for the C++ side). All language combinations support OpenGL, so any serious graphics work is fine and the library support is ok with Apple regardless of language.

That said, what is the purpose of your game?

* If you are solely writing for IOS, then don't worry and write in whatever language or combination you feel more comfortable in. For me, this happens to be Obj-C++ with STL since that's my favorite part of C++. Since I prefer Obj-C slightly over C++, I tend to use this option.
* If you are writing with the goal of porting to another device, write in C++ with a translation layer to Obj-C to deal with any device-specific stuff (graphics, input, camera, ...), where the calls are made to entry-points in your application.
* If you are a purest and want just one language, write in Obj-C.

Others have talked about other libraries (physics and such). There are absolutely no problems with accessing any of that from any of the language choices you are talking about (Obj-C, C++, or Obj-C++). You will also not have any performance issues with those libraries in any language.

A caveat: There is a pointer indirection call with message passing. I'm not sure how much you can interpret that as overhead, since I'm pretty sure that's exactly the same as an inherited C++ method call. Can anyone clarify this?

Hope that helps,

Lee.
> 4 votes

# Answer
It depends on exactly *what* you are programming. If it's mainly game logic using existing physics and graphics engines, i can safely say i don't see any reason to use c or c++ if you're more comfortable with obj-c. If you are going to be rolling out rendering or physics classes i would probably write those using c or c++. Cocos2d - which is a wonderful and one of the most popular iOS game libraries is written in obj-c.

Check out this read - the relevant part is "division of labor", might help you to decide when to code in a higher level language and when to use lower level: Managed code in games

While objective-c overhead should be no where near C# and isn't even managed (on iOS), i believe the logic still applies, and devices running iOS are also no where near as strong as the PC that would be interpreting MSIL :)
> 1 votes

# Answer
This study says to really get the performance in a CPU intensive game, you have to use C. The linked article is complete with a XCode project that you can run.

I believe the **bottom line** is: Use Objective-C where you must interact with the iPhone's functions (after all, putting trampolines everywhere can't be good for anyone), but when it comes to loops, things like vector object classes, or intensive array access, stick with C++ STL or C arrays to get good performance.

I mean it would be totally silly to see `position = [[Vector3 alloc] init] ;`. You're just asking for a performance hit if you use references counts on basic objects like a position vector.

See also these comparisons,
> 1 votes

---
Tags: c++, ios, performance, objective-c
---


# Question
Title: Is there a cross-platform special directory I can use for game save files?
I'm developing with LWJGL and Java on a Windows 7 laptop. I've successfully set up saving to the `%appdata%\gamename\saves\` or long form `c:\users\user\appdata\roaming\gamename\saves\` folder by using `File dir = new File(System.getenv("APPDATA") + "\\gamename\\saves\\");`.

I have hobbyist level experience with Linux, and zero experience with OSX. My game will be fully cross platform.

Is `System.getenv("APPDATA");` cross platform? If so, where does it point to on Linux or OSX? Is there a *best practices* alternative that I should use?

# Answer
> 7 votes
I'm using this code on my game right now:

```
System.getProperty("user.home");

```

Simple and efficient.

It's a user dependent directory, which is perfectly fine for storing save files. I'm using it to download and store assets, though.

# Answer
> 12 votes
There is no such directory; `%APPDATA%` is Windows-specific. You'll have to abstract it yourself: create your own `GetSaveGameDirectory` function that returns an appropriate path on whatever operating system you're running on. You can typically make this determination at compile time with preprocessor checks against the appropriate macros in C (and it's ilk). I'm not entirely sure of the best way to do so in Java.

On Windows, an `%APPDATA%` subdirectory for your company or game is appropriate. On the Mac, `~/Library/Application Support/Your Game` is common although Apple's guidelines recommend against storing "user data" there (it should go to the `~/Documents` directory) -- it depends primarily on whether or not you prompt the user to select a directory).

On general \*nix systems you'll probably find less standardization -- perhaps a hidden directory within `~`, such as `~/.yourgame`? Certainly this is the common practice for configuration files. An actual \*nix user will probably need to chime in on whether or not this an appropriate game save location.

For the best results, do not hardcode the path to the directory based on the English string, but use the OS API to access the directory. This will help ensure your game runs properly on non-English version of the OS. For example, on Windows, use SHGetKnownFolderPath or an equivalent wrapper, if possible.

# Answer
> 2 votes
On Linux, the only standardized path would be the `XDG_DATA_HOME` and `XDG_CONFIG_HOME` directories. Use the environmental variables with those names if they exist, otherwise default to `$HOME/.local/share/<appname>/` for user-data (saves, progress, player profile) and `$HOME/.config/<appname>/` for configuration. Deleting the latter directory should in theory not affect user provided data other than resetting everything to default settings. You have also got `XDG_CACHE_DIR` (`$HOME/.cache/<appname>`) for non-essential/temporary files.

Dumping everything in `$HOME/.<appname>` just clutters up the user’s home folder, and they might not appreciate that. It is a mostly deprecated practice with the new Free Desktop standardization initiative.

# Answer
> 1 votes
**Windows**:

* %UserProfile%\Documents\Saved Games\GAMENAME\

**Linux**:

* ~/Saved Games/GAMENAME/

**OSX**:

* ~/Documents/Saved Games/GAMENAME/

As Josh mentioned, don't hardcode paths - use the OS API to use the correct path:-)

# Answer
> -4 votes
I think the best out of all places to place game data would be your game's installation folder, IE:

```
    %Install%/Saves/

```

Where %install% would be something like C:\programfiles\yourgame\ or ~/apps/yourgame/

---
Tags: java, lwjgl, storage, filesystem
---


title: Designing a simple snake A.I

text:
# Question
Title: Designing a simple snake A.I
I've looked at some stuff online regarding this specific topic, and a lot of the info that I read involved graphs and path finding.

I really don't want to get involved in something too complex & out of my level, and also I don't need my snake to be that intelligent (it will be a large board with the snake not growing in size on every munch).

How could you structure a simpler AI for the snake that gets the job done relatively well? I would be able to get the snake to move towards the food item correctly, but my issue is that I'm not sure how to deal with the snake colliding with itself. Say the snake has a look ahead, and it finds that its tail is in the way, it could change direction, but what happens next?

Any ideas on how to tackle this? Should the snake build an instruction set from every square, or should it think on the go?

# Answer
> 1 votes
A simple set of rules should let your snake navigate the majority of situations. If you need code, let me know and provide some of your methods/variables so I can fill in the blanks.

---

New piece of food shows up. Snake figures if it needs to go + or - X, and the same for Y. On the first turn snake starts heading to the food's X (by moving along the Y axis).

If the snake encounters itself while moving Y, it makes a turn in the correct X direction (it remembered whether it needs to go +X or -X), and heads straight until it reaches a square and doesn't detect its tail to the side anymore. If it detects more body ahead, it turns to the free direction, continuing until it detects an opening to the side and can return back to its course. (It "wall hugs" its tail until the tail runs out and it can get back on course.)

Once the snake reaches the correct X coordinate, it begins moving along the X to get to the correct Y coordinate.

If the snake encounters itself while moving X, it makes a turn toward the Y direction it first remembered for this piece, and checks for open space similarly to the Y movement.

---

Now the snake will **only** suicide if it runs into its tail **and** turns in the *same* direction the tail is "moving" (causing the snake to spiral until it runs out of space). This however will never happen if the snake makes sure to turn toward the direction it originally needed to, to get the current piece of food. Why? Because of where the previous piece of food was - the snake will only run into its tail if it has to double-back along the X or the Y to get the piece, so you can usually be assured the snake was previously moving in the *opposite* X or Y to get to the piece you just picked up.

I believe this will break down if the snake has to double back for multiple pieces in a row, *and* the distance between all the multiple pieces happens to be shorter than the total length of the snake. But hey, you said "simple" and "relatively" well.

---
Tags: c++, game-design, ai
---


title: rotating model around own Y-axis XNA

text:
# Question
Title: rotating model around own Y-axis XNA
I'm have trouble with my model rotating around it's own Y-axis. The model is a person.

When I test my world, the model is loaded at a position of **0, 0, 0**. When I rotate my model from there, the model rotates like normal. The problem comes **AFTER** I moved the model to a new position.

If I move the the model forward, left, etc, then try to rotate it on it's own Y-Axis, the model will rotate, but still around the original position in a circular manner (think of yourself swing around on a rope, but always facing outward from the center).

Does anyone know how to keep the center point of rotation updated?

# Answer
> 2 votes
Instead of applying matrices as `translate * rotation`, try doing `rotation * translate`

---
Tags: xna-4.0, models, rotation
---


# Question
Title: OpenGL Shading Program Object Memory Requirement
gDEbugger states that OpenGL's program objects only occupy an insignificant amount of memory. How much is this actually? I don't know if the stuff I looked up in mesa is actually that I was looking for but it requires 16KB \[Edit: false, confusing struct names, less than 1KB immediate, some further behind pointers\] per program object. Not quite insignificant.

So is it recommended to create a unique program object for each object of the scene? Or to share a single program object and set the scene's object's custom variables just before its draw call?

# Answer
An OpenGL program consists of at least a vertex and a fragment shader that are compiled and linked. Once you want to use a program, you must link it. You can create a program manager/shader manager/material manager (call it however you want, equip it with whatever functionality you need). This program manager keeps a map of all vertex-fragment shader pairs that do appear in the materials your objects use. You should group your objects by program and not recompile-relink the program each time you draw an object. You can use the program manager to check whether a certain program is the active one. That active program will be responsible for the shading of any object that issues render calls.

Now, the attributes and uniforms need their own managers. Usually, keeping maps to manage them is a good idea. For uniforms, you could keep two kind of maps:

* a *global uniforms* map that stores data that's scene specific (specific to all or most objects in a scene, perhaps to some objects groups). They represent data such as lights, environment/weather factors, etc. An object has an associated program. That program will query the global uniforms for the existence of a certain variable and try to get its value from that global map of uniforms. If it cannot find it, then maybe that uniform is object specific.
* an *object uniforms* map that stores data which is local and accompanies an object instance. For example, you have some cars in your scene, each having an uniform called "reflectivity". That uniform is car specific, one care is more matte than the others, etc.. You get your uniform value by querying the object's uniforms map whenever a certain program is active and does require a value for an uniform.

If an active program cannot find an uniform in neither places, you should decide whether you supply default values in the program/material file or if you somehow forbid such a possibility by throwing exceptions.
> 1 votes

# Answer
1k (or even 16k) *is* actually an incredibly insignificant amount for modern GPU memory sizes - a 512x512 RGBA texture (which you would likely use on many objects) weighs in at over 750k, by comparison.

I think you're confusing how you should create program objects though. There's no way you'd create one for each scene object; instead you create one for each object type, or material type, and reuse it where possible. This is not so much to do with memory saving as it is to do with reducing shader changes (which can be a very expensive operation).

Going back to the texture comparison I made, it's much the same thing. You don't have a separate set of textures for each object, you have a single set of textures which get shared by multiple objects. Same deal with shaders.

Despite that, many modern (or not so modern) games easily end up with hundreds of shaders, so you can see that it's not that big a deal.
> 1 votes

# Answer
> So is it recommended to create a unique program object for each object of the scene? Or to share a single program object and set the scene's object's custom variables just before its draw call?

No, but not for reasons of memory consumption.

The only reason you would have for creating a program for every object would be to avoid uniform changes. Now consider the fact that pretty much every program that uses GLSL, or even Direct3D, has uniform changes as part of what is needed to render other stuff.

In short: you don't need it. Especially not nowadays with uniform buffers and the like to make changing global uniforms pretty simple.
> 1 votes

---
Tags: opengl
---


# Question
Title: Move model forward base on model orientation
My model rotates on it's own Y-axis regardless of where it is in the world. Here are the controls for the left ThumbStick:

UP (move model forward on Z-Axis) DOWN (move model backward on Z-Axis) LEFT & RIGHT (strafe to either side)

The problem is adjusting the direction the model's orientation UP and DOWN if the player should also rotate the player while moving forward or backwards.

An example what Im trying to achieve would be a car doing donuts. The car is always facing the current direction that it interprets as forward (or rear as backwards) in relation to it's local rotation.

Here is how Im calling the movement:

```
            // Rotate model with Right Thumbstick along X-Axis
            modelRotation -= pController.ThumbSticks.Right.X * mRotSpeed;

            // Move Forward
            if (pController.IsButtonDown(Buttons.LeftThumbstickUp))
            {
                modelPosition.Z -= -pController.ThumbSticks.Left.Y * speed;
            }

            // Move Backward
            if (pController.IsButtonDown(Buttons.LeftThumbstickDown))
            {
                modelPosition.Z += pController.ThumbSticks.Left.Y * speed;
            }
            // Strafe Left
            if (pController.IsButtonDown(Buttons.LeftThumbstickLeft))
            {
                modelPosition.X += -pController.ThumbSticks.Left.X * speed;
            }
            // Strafe Right
            if (pController.IsButtonDown(Buttons.LeftThumbstickRight))
            {
                modelPosition.X -= pController.ThumbSticks.Left.X * speed;
            }
            // DeadZone
            if (!pController.IsButtonDown(Buttons.LeftThumbstickUp) &&
                !pController.IsButtonDown(Buttons.LeftThumbstickDown) &&
                !pController.IsButtonDown(Buttons.LeftThumbstickLeft) &&
                !pController.IsButtonDown(Buttons.LeftThumbstickRight))
            {

            }

```

# Answer
> 0 votes
Found the answer.

For those that run into the same problem, here it is to keep your 3d model facing the direction of travel/rotation (XBox360 controller):

```
            // Move Forward
            if (pController.IsButtonDown(Buttons.LeftThumbstickUp))
            {
                speedx = -(float)(Math.Sin(modelRotation)) * forwardSpeed;
                speedz = -(float)(Math.Cos(modelRotation)) * forwardSpeed;

                modelPosition += Vector3.Forward * speedz;
                modelPosition += Vector3.Left * speedx;
            }

```

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


# Question
Title: Reacting to rectangle on rectangle collisions
I don't know how to react to collisions between two axis aligned rectangles that have x, y, width and height values (x and y are from the centre of the box) to make them simply not overlap.

I figured I'd just make them move away from each other depending on how far they intersect in the opposite direction (left, right, up or down) of where they collided. If I check for collisions only on the x axis or only on the y axis it works fine, but when checking for both collisions crazy stuff happens.

This code executes when the first box collides with the second. It's in lua but feel free to answer in anything that isn't to too counter-intuitive.

```
if box1.x < box2.x then
    box1.x = box2.x - (box1.width / 2) - (box2.width / 2)
end

if box1.x > box2.x then
    box1.x = box1.x - (box1.x - box2.x - (box1.width / 2) - (box2.width / 2))
end

if box1.y < box2.y then
    box1.y = box2.y - (box1.height / 2) - (box2.height / 2)
end

if box1.y > box2.y then
    box1.y = box1.y - (box1.y - box2.y - (box1.height / 2) - (box2.height / 2))
end

```

# Answer
> 3 votes
The thing is that the boxes only actually overlap if they overlap on both axes. You can therefore compute the overlap on both axes, then decide whether to move the boxes.

First compute how far apart the box centres are:

```
local dx = box2.x - box1.x
local dy = box2.y - box1.y

```

Then compute how far apart they *should* be at least (in absolute value):

```
local dw = (box2.width + box1.width) / 2
local dh = (box2.height + box1.height) / 2

```

Now a bit of maths tells us the excess in both directions:

```
local movex = math.max(dw - math.max(dx, 0), 0) - math.max(dw + math.min(dx, 0), 0)
local movey = math.max(dh - math.max(dy, 0), 0) - math.max(dh + math.min(dy, 0), 0)

```

And you can finally move the boxes away from each other if needed, either in the X or in the Y direction. If both `movex` and `movey` are zero then the boxes don't move:

```
if math.abs(movex) <= math.abs(movey) then
    box1.x -= movex / 2
    box2.x += movex - movex / 2
else
    box1.y -= movey / 2
    box2.y += movey - movey / 2
end

```

---
Tags: collision-detection
---


title: Technical manager vs. Lead programmer

text:
# Question
Title: Technical manager vs. Lead programmer
Can anyone explain the responsibilities of the `Technical manager`and the `Lead programmer`, in team ?

Suppose a medium-size team with about 10-15 persons .

# Answer
Varies from team to team.

A `technical manager` can have the responsibility of the planning, execution and closing of any project development.

A `lead programmer`, responsibilities vary from company to company, but in general he or she is responsible for the underlying architecture for the software program, as well as for overseeing the work being done by any other software engineers working on the project. A lead programmer will typically also act as a mentor for new or lower-level software developers or programmers, as well as for all the members on the development team.
> 3 votes

---
Tags: project-management, management
---


# Question
Title: Unity3D: default parameters in C# script
Accordingly to this thread, it seems that default parameters aren't supported by `C#` script in `Unity3D` environment.

Declaring an optional parameter in a C# scirpt makes `Mono` Ide complaint about it:

```
void Foo(int first, int second = 10) // this line is marked as wrong inside Mono IDE

```

Anyway if I ignore the error message of `Mono` and run the script in Unity, it works without notify any error inside Unity Console.

Could anyone clarify a little bit this issue? Particularly:

* Are default parameters allowed inside C# scripts?
* If yes, are they supported by all platforms?
* Why Mono complains about them if the actually works?

# Answer
1. As of Unity 3.1, default arguments are supported in C#. As Mono Develop doesn't support them, so if you're using the debugger you need to select Tools \> Preferences \> Unity \> Debugger and turn off "Build project in MonoDevelop".
2. Yes supported.
3. As before C# 4.0, doesn't allow for default parameters. For this reason it was not at Unity3D. Mono complains why, Mono can answer the best. But I think they will add at next version.
> 2 votes

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


# Question
Title: What technologies are used for Game development now days?
Whenever I ask a question about game development in an online forum I always get suggestions like learning line drawing algorithms, bit level image manipulation and video decompression etc.

However looking at games like God of War 3, I find it hard to believe that these games could be developed using such low level techniques.

The sheer awesomeness of such games defy any comprehensible(for me) programming methodology.

Besides the gaming hardware is really a monster now days. So it stands to reason that the developers would work at a higher level of abstraction.

What is the latest development methodology in the gaming industry? How is it that a team of 30-35 developers (of which most is management and marketing fluff) able to make such mind boggling games?

# Answer
> 5 votes
Well often light-weight-frameworks like libGCM or PSGL (those are a few examples on the PS3). The Xbox uses DirectX (but the Xbox version exposes more hardware features and is lighter since there is only a simple OS between hardware and software). On the PC it is usually standard OpenGL or DirectX.

Higher-level frameworks called engines are often used as well. There are engines that take care of almost anything. Think of the Unreal engine by Epic, Source by Valve, or Frostbyte by Dice. There are also specialized engines that take care of subsystems, for example engines that take care of all the sounds stuff (Miles) or all the video stuff (Bink).

So these frameworks and engines give you the abstraction that a programmer needs to skip the trivials and get straight to business. Still your assumption that just 30 devs are working on AAA games, and that most of these are in a managing role, is wrong. Usually there are tons of devs working on modifying the engines, a dozen working on the tool chain, a dozen working on the gameplay, and then some few more scattered elsewhere. Note that these numbers are an educated guess (I've interned at a subcontractor of Ubisoft) and can differ greatly depending on the project.

Please note that I've tried to find as much links as possible to give you some more background info, do check them, they are all unique and interesting links.

---
Tags: game-design, architecture, software-engineering
---


# Question
Title: Correct way to use Farseer Physics in XNA
I am using Farseer Physics for my 2D sidescroller game and I'm not sure how to proceed with it. I currently have a Sprite class (handles nothing but graphics), a GameObject class (contains specific object info like hit points), a World object which contains the list of Bodies, and a Level object which contains all of these objects.

Originally I was trying to keep track of the Sprites, GameObjects, and Bodies separately because I felt that would provide loose coupling but it quickly became a headache.

So my new idea was to add a Sprite member to the GameObject class but I'm still not sure how to maintain the Bodies because they have to communicate with GameObject.

Specifically, my issue is this: The position of the Body is used to draw the Sprite inside of the Level. In order to do that I would have to maintain a link between GameObjects and Bodies. Is this correct or is there a better way to architect my game?

If any of this is unclear please ask and I'll try to clarify. Thank you in advance for any help.

# Answer
What I do is add a `Texture2D` directly to my game objects. I have another class called an `AnimationController` which manages my source rectangle/frames/timing for drawing animations from the texture. I suppose this would be similar to what your `Sprite` class does.

If my game object will have a physics body (i.e. players, enemies, etc.), I add a `Body` property to it as well. If my game object doesn't have a physics body, then it will just have a regular `Vector2 Position` property (in world units).

Now, my game objects usually have `Update` and `Draw` methods. If it has a physics body, I draw the texture at the `Body.Position` or otherwise at `this.Position` using the source rect from my `AnimationController`. In the `Update` I update the `AnimationController` so it can switch frames and whatnot and then do whatever else for the object.

So, I would say add `Sprite` and `Body` fields/properties to your game objects that need them and let the game objects decide how to use them.

Remember, you can always go back and refactor the code later. You don't want to get stuck in a rut where you're spending more time *thinking* about programming your game than actually programming it.
> 3 votes

---
Tags: xna, physics, farseer-physics-engine
---


# Question
Title: should users be asked to submit high score to leaderboard?
If a user gets a new high score in a game, should they be asked before having their score submitted to the leaderboard? Originally I was just going to submit their score to the leaderboard without prompting them, but a friend told me that it is preferred that the user be asked.

thanks

# Answer
> 6 votes
You should ask the user before publishing the high scores for 2 reasons:

* Some users don't want their scores uploaded (by principle, or to avoid being spied on) even if it doesn't make any sense for most people.
* Some countries have very strong data protection laws and you can get into trouble if you submit user data without user's permission, Even more so if you don't allow users to access their own data or to erase these data.

You can avoid asking the user's permission in some cases. For example if the user logged-in to a system, explicitly granting the permission to upload and use data. If you are using this system to submit data you have implicitly the right to do so. Some examples would be Apple's Game Center, Microsoft's Xbox Live, openfeint, crystal...

Otherwise you should always ask the user at least when he launches the game of when trying to upload the data for the first time.

---

**edit**: this answer by Marcks Thomas reminded me of another way of doing this. I worked with companies which automatically upload various anonymous usage data (not sure about high scores though) even if the user has not explicitly given his permission in game. This behavior is documented in the user agreement. But the user can opt-out, in the options there is a checkbox to disable that data upload. So at no point there are questions popping up about data uploads.

I think this is the least intrusive way of doing high scores. But it requires providing a user agreement and notifying the user about it at launch.

---

Disclaimer: I am not a lawyer and this answer is no way legal advice.

# Answer
> 8 votes
Always unless they choose to opt out. You should never publish something that can possibly be individually identifying without asking. For people like your friend simply put in a check box that says "Don't ask again" or something along those lines.

# Answer
> 4 votes
As far as legal issues go, the usual remarks apply. Laws are not universal, your mileage may vary etcetera, etcetera. If you are required to obtain the user's permission to publish his score, it doesn't follow you need to ask. Permission can be implied by simply playing the game, as long as the player is informed of this, for instance through your terms of service. Once again, one paragraph of legal advice is bound to cut corners all over the place.

Most answers so far have been focussing on these legal issues, but from a gaming perspective, there are very few reasons to pose the question whether scores should be submitted. Obviously, the less you bug the player, the better. Interrupting gameplay to register the user's preference adds no enjoyment to your game, regardless of which option the player would click. Assuming the score should or should not be submitted is intrinsicly better than prompting, but you risk getting it wrong.

By automatically submitting the high score, getting it wrong is not such a bad thing though. Players simply uninterested in competing on the leaderboard, will not be harmed by their own achievement being on there. After all, it might just as well have been someone elses. Other players may however still benefit from the score being on there, as it allows them to compete with it. The leaderboard will be more competitive and fairer; it is not limited to a non-representative selection.

Moreover, showing the leaderboard with the player's name on it, might awaken his interest to compete, even if he would not have posted his score, had he been given the option. Perhaps he realises his score was far better than expected, giving a sense of reward, or quite the opposite, letting the player know there is a lot of room for improvement. Perhaps he sees he has beaten a friend, or that he has been beaten by one, inspring him to play again. All experiences he would have otherwise missed out on. Worst case scenario: the player looks at the list and doesn't care at all.

A leaderboard can definitely make your game more interesting. If it does, you should probably just go ahead and get the player to participate. If it doesn't, you probably shouldn't even have one.

# Answer
> 1 votes
if it is a simple username and score, there's no harm in that. If the username can trace back to something like their email or other personal info then i would ask. If you have an options menu you can have a choice in there, and when they create a profile on the game you can ask once which way they want it.

The less you pester them with it the better

---
Tags: leaderboards
---


# Question
Title: Best Source Engine Tutorial Books/Sites?
I want to get into Source Development. Anyone know any good sites for tutorials on it? I already know a few.. Just thought I would ask incase you guys know of any that might be better.
Thanks :)

# Answer
> 0 votes
**I'd recommend you start browsing through the official steam forum and valve's developer wiki:**

**You can also find tutorials here:**

---
Tags: c++
---


title: Smarty templating system really needed?

text:
# Question
Title: Smarty templating system really needed?
Is smarty templating system really needed for creating a browser-based game?

Do I need anything else than SQL, PHP, and JS knowledge? \

Note: I also know HTML/CSS so I'd like to work on the game template only after the Database and Coding is done...

# Answer
> 1 votes
Smarty is not needed in the sense that you cannot implement a browser-game without it.

In my opinion, a template engine has three main advantages:

* It helps to enforce MVC. Smarty does this quite well, since you can use native PHP only in plugin functions. (The {php} tag is deprecated from Smarty 3.) If you are new to MVC design, it is worth using Smarty just because of the learning effect it provides.
* It makes designing view files easier and more secure for non-programmers. This is valuable whenever you have designated frontend-designers who don't know PHP, but still need structs like if-statements, loops, etc. The Smarty syntax is easy to pick up for anybody who already knows HTML, plus you can be (/ make) sure that those designers don't manipulate the objects and variables that you pass to your templates.
* It provides caching functionality (as well as a couple of non-essential goodies like widgets and handy functions for presentation purposes).

Note that Smarty is not the only engine that provides these advantages, so it is not needed even if you decide to use a template engine.

If you are experienced with MVC software design, don't have any non-programmers for your view files, and already got caching functionality, then don't use Smarty. It will just make your code (a little) slower, and, more important, it will restrict your flexibility by taking away the option to use native PHP in your view files.

---
Tags: php, browser
---


# Question
Title: Algorithmically generating neon layers on pixel grid
> **Possible Duplicate:**
> How to achieve a Neon-Light effect?

In an attempt at a screensaver I am making, I am a fan of neo-like graphics, which, of course, look great against a black background. As I understand it, neon, graphically speaking, is essentially a gradient of a color, brightest in the center, and gets darker proceeding outward. Although, more accurate is similar, but separating it into tubes and glow. The tubes are mostly white, while the glow is where most of the color is seen. Well... the tubes could also be a light variant of the color, you could say. The glow is darker.

Anyhow, my question is, how could you generate such things given an initial pattern of pixels that would be the tubes? For example, let's say I want to make a neon 'H'. I, via the libraries, can attain the rectangles of pixels which represent it, but I want to make it look neonized. How could I algorithmically achieve such an effect given a base tube shape and base color?

EDIT: ok, I mistated that. Got a bit distracted. My purpose for this was similar to a neon effect, but not. Sorry about that. What I am looking for is something like this:

Start with a pattern of pixels:

```
[!][!][!][!][!][!][!][!]
[!][!][O][!][!][!][!][!]
[!][!][O][O][!][!][!][!]
[!][!][!][!][O][!][!][!]
[!][!][!][!][!][!][!][!]

```

How to I find the U pixels?

```
[!][E][E][E][!][!][!][!]
[!][E][O][E][E][!][!][!]
[!][E][O][O][E][E][!][!]
[!][E][E][E][O][E][!][!]
[!][!][!][E][E][E][!][!]

```

Sorry if that looks bad.

# Answer
If you have a higher-resolution image of your “tube” than your example suggests, then the solution is a matter of very basic image-processing. The first thing to try to generate the glow would be a *Gaussian blur* of your “tube” shape. Then draw the blur output (possibly with a brightness adjustment) followed by the tubes. If you find that the glow is too weak, or if you are working with very thin lines, try a morphological *dilate* operation before the blur (possibly even applying it to the tubes to thicken them).

Combinations of these and related effects, as well as small offsets, can also automatically generate a decent impression of a shiny glass tube.

All of the above are standard image-processing operators and any decent image-processing library should make it easy to perform them.

---

If you are *really* working with single-pixel tubes with tight corners and want to produce a single-pixel glow as your example suggests, then your problem more closely resembles a tile-based graphics problem — choosing transition tiles — and you should approach it that way.

---

If none of the above is what you meant, then I recommend clarifying your question. Even the roughest of actual prototype graphics or even freehand sketches of what you're trying to achieve would help greatly.
> 0 votes

---
Tags: c++, graphics
---


# Question
Title: sprite animation system height recalculating has some issues
Basically, the way it works is that it update the frame to show every let's say 24 ticks and every time the frame update, it recalculates the height and width of the new sprite to render so that my gravity logics and stuff works well. But the problem i am having now is a bit hard to explain in words only, therefore i will use this picture to assist me

The picture

So what i need basically is that if let's say i froze the sprite at the first frame, then unfreeze it and freeze it at the second frame, have the second frame's sprite (let's say it's a prone move) simply stand on the foothold without starting the gravity and when switching back, have the first sprite go back on the foothold like normal without being under the foothold.

I had 2 ideas on doing this but I'm not sure it's the most efficient ways to do it so i wanna hear your inputs.

# Answer
> 0 votes
Fixed my problem, not sure if it will still function effectively in the future but it seems like a pretty good way to me

(i added a currentFoothold defenition the entity with for the object Foothold and when the entity isOnGround, set that foothold object to the foothold he currently is standing on, naturally. When recalculating height, if the entity isOnGround && foothold != null set the entity's Y coordinate to the foothold's Y coordinate in the map)

# Answer
> 0 votes
Make your current `getWidth()` and `getHeight()` methods like this.

```
public int getWidth(){
    return currentImage.getWidth(null);
}

public int getHeight(){
    return currentImage.getHeight(null);
}

```

This makes you depends on the `Java API` to know these parameters. Instead of measuring them all the time, it simply calls the methods of the current image object. Make sure you call them only on the `Current Image`.

For reference see `https://code.google.com/p/game-engine-for-java/source/browse/src/com/gej/graphics/Animation.java`

It's free to use and is my own class.

---
Tags: java, collision-detection
---


# Question
Title: Java and Eclipse setup properly, how do I install JOGL or LWJGL?
I have my Java environment installed alongside Eclipse, and I was successfully able to create and run a new project (simple System.out.println("Yay I work!");

I have the OpenGL SuperBible, and I primarily want to code 3D things (I'll take my time using the book to learn how to draw shapes in 3D space, etc..)

Can you help me get setup with OpenGL in Java? I dont really need LWJGL, although I WILL make games eventually. I just can't even figure out with all of these terrible (and old) tutorials floating around on the net how to install either JOGL or LWJGL.

If you can give me a hand with that, I'd appreciate it. I'd like to feel I contributed by having this page show the answer to the question, so that other poor souls googling for this same information can benefit.

# Answer
> 1 votes
Found a great site which should help with the setup of JOGL http://jogamp.org/wiki/index.php/Jogl\_Tutorial#Justin.27s\_Getting\_Started\_with\_JOGL\_2\_Tutorials and here for LWJGL in Eclipse: http://lwjgl.org/installation.php#eclipse

# Answer
> 1 votes
Full up to date LWJGL instructions and tutorials can be found on the LWJGL Wiki http://wiki.lwjgl.org/ this includes how to set it up with Eclipse, Netbeans, etc and has tutorials that cover the basics of LWJGL.

# Answer
> 0 votes
i found a nice resourve at http://www3.ntu.edu.sg/home/ehchua/programming/opengl/JOGL2.0.html. it shows how to make an eclipse user library from the downloads.

---
Tags: 3d, opengl, java
---


title: Connect camera class to game

text:
# Question
Title: Connect camera class to game
I've been following a tutorial on making a free camera for a 3D model. What the camera class does is allow the player to move and rotate in respects to the model's current position using the right thumbstick of an XBox360 controller.

Here is the code:

http://pastebin.com/xb4eznMi

Can someone explain to me how to connect this to my model in my Game class?

# Answer
By quickly skimming over the code it seems to be used like this:

```
  class MyGame : Microsoft.Xna.Framework.Game
  {
     Camera camera;

     public MyGame()
     {
        camera = new Camera(this);
        Components.Add(camera);
     }

     // ...
     // use camera.View and camera.Projection
  }

```
> 2 votes

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


title: Box2d -- get free space

text:
# Question
Title: Box2d -- get free space
I am developing a little Game with something like particles, where every particle is represented by a box2d Body.

To insert new particles I need to find a place in the b2World where no bodies reside. How can I obtain this?

greeting...

# Answer
Depending on the density of the particles this can be a pretty hard problem to solve.

If the density of particles is low you have a good chance that a (semi-random) position is free. And something like this would be viable. (pseudo code of course)

```
bool placed = false;
Vector2 position = (50,50); // rough indication of where we want to insert the particle
while(!placed)
{
    // Slightly randomize the position so that we try a different position
    // near the intended position every iteration.
    float direction = A random number between 0 and 2*PI;
    float length = A random number between 0 and a chosen maximum displacement
    Vector2 displacement = (sin(direction), cos(direction)) * length;
    Vector2 tryPosition = position + displacement;

    // Iterate over all the bodies already in the simulation.
    // Note that you can get the bounds of a body using its shape list.
    if there are no bodies at tryPosition
    {
        placed = true;
        Add the particle
    }
}

```

But be wary, there are a few problems with this algorithm. There is a chance that it will take a long time (or maybe even forever) before a free position is found, and the chances of it taking a very long time increase with the density of particles.

A second solution is more work but is guaranteed to finish.

You divide the world in cells (this is called spatial partitioning). You select a cell where you want to place the new particle. In the image below the cell where we, at first, want to place the new particle is colored blue:

As you can see the cell marked blue is occupied by an existing particle (the red circle). So we can't place a new particle here. We mark the cell as occupied and continue to spiral out:

We continue to spiral out (no randomness here, we just rotate clockwise around the already checked cells) until we find the solution:

As you can see we will always find a place to put the new particle that is as close as possible to the intended space.

Note that since we know which places we have checked the algorithm can in the end even give up telling us there are no free places. So it has a guaranteed runtime of O(maxNumberOfParticles * numberOfCells) before it has placed a new particle or has given up.

Now you have to make a decision on the size of the cell. Too large and you might miss free spaces, too small and finding a solution will take a long time. Another decision you have to make is if you want to cache a list of occupied cells to use in further frames (you will have to update part of it whenever a particle moves) or that just doing this when you spawn a new particle is good enough (in that case you won't even need a list, it's implied that a cell is occupied by the algorithm continuing).
> 2 votes

---
Tags: box2d
---


# Question
Title: D3DXMatrixDecompose gives different quaternion than D3DXQuaternionRotationMatrix
In trying to solve this problem, I tracked down the problem to the conversion of the rotation matrix to quaternion. In particular, consider the following matrix:

```
-0.02099178 0.9997436  -0.008475631 0
 0.995325   0.02009799 -0.09446743  0
 0.09427284 0.01041905  0.9954919   0
 0          0           0           1

```

`SlimDX.Quaternion.RotationMatrix` (which calls D3DXQuaternionRotationMatrix gives a different answer than `SlimDX.Matrix.Decompose` (which uses D3DXMatrixDecompose). The answers they give (after being normalized) are:

```
                            X            Y             Z            W
Quaternion.RotationMatrix   -0.05244324  0.05137424    0.002209336   0.9972991
Matrix.Decompose             0.6989997   0.7135442    -0.03674842   -0.03006023

```

Which are totally different (note the signs of X, Z, and W are different). Note that these aren't q/-q (two quaternions that represent the same rotation); they face completely different directions.

I've noticed that with matrices for rotations very close to that one (successive frames in the animation) that the `Matrix.Decompose` version gives a solution that flips around wildly and occasionally goes into the desired position, while the `Quaternion.RotationMatrix` version gives solutions that are stable but go in the wrong direction. This is only for the right arm in my animation -- for the left arm, both functions give the correct solution, which is the same quaternion within error tolerances.

This makes me think that there's some sort of numeric instability or weird stuff with signs going on. I tried implementing this and then this, but both gave me a completely incorrect solution (even for the matricies where the SlimDX ones were working correctly) -- maybe the rows and columns are flipped?

# Answer
> 6 votes
The problem is neither of the conversion functions, the problem is the input matrix. It is not an affine transformation matrix, because the rotational part is not a pure rotation matrix, it has one or more flipping/negated axis in it.

Only Rotation matrices can be converted to quaternions. More specifically rotation matrices are orthogonal matrices with determinant 1, other input matrices will give wrong results.

A) The input:

```
-0.02099178 0.9997436  -0.008475631
 0.995325   0.02009799 -0.09446743
 0.09427284 0.01041905  0.9954919

Determinant: -1

```

B) Which is basically:

```
0   1   0
1   0   0
0   0   1

Determinant: -1

```

C) One can never reach this matrix by just rotating the identity matrix:

```
1   0   0
0   1   0
0   0   1

Determinant: 1

```

You can see that only the x- and y-axis are swapped in B) compared to C), the z-axis remains the same compared to the identity matrix. This is not possible with a pure rotation, there is also flipping/mirroring involved which makes it no longer a rotation matrix (determinant != 1).

A pure rotation that swaps the x- and y-axis would have to have a negative z-axis like this:

```
0   1   0
1   0   0
0   0  -1

Determinant: 1

```

So how did you create this matrix? It is not a valid rotation matrix that you can use as input for a conversion to a quaternion!

---
Tags: mathematics, directx, matrix, slimdx, quaternion
---


# Question
Title: How to check battery usage of an iPhone/Android app?
I think the title says Enough. For example Unity can generate you a report how much CPU/GPU power it's using or how fast it's going to drain device battery, but what about the applications developed using Cocos2d or the ones you develop directly using OpenGL? How should you profile them? In general what should you profile? or Should I simply run the application and wait for it's battery to run out?

# Answer
> 2 votes
On the iPhone, you can go to Settings \> Developer \> Energy Diagnostics and turn logging on. You can then use the *Energy Diagnostics* template in Instruments to analyze the data from this log. It will break it down into several kinds of events and graph it over time, correlate it with CPU and network spikes, and generally work like any other Instruments session.

As far as I know (and I have looked, but not exhaustively) there is no equivalent tool for Android. There are some third-party apps that can sample battery across a long period of time to give you an idea of what the discharge curve looks like if you do choose to run your program for a long time. On shorter time scales DDMS can help you figure out some details like your general CPU usage and network usage, which you can then work on batching or reducing. But this is just general optimization help and a big step removed from detailed energy consumption data.

---
Tags: android, iphone, performance, profiling
---


title: Fourth texture = segmentation fault

text:
# Question
Title: Fourth texture = segmentation fault
I keep on getting **segmentation fault** each time I **load fourth texture** \- what type of texture, I mean filename, does not matter. I checked value of `GL_TEXTURES_STACK_SIZE` which turned out to be **10** so quite more than **4**, isn't it?

Here're code fragments:

funciton to load texture from *png*

```
static GLuint gl_loadTexture(const char filename[]) {
    static int iTexNum = 1;
    GLuint texture = 0;
    img_s *img = NULL;

    img = img_loadPNG(filename);
    if (img) {
        glGenTextures(iTexNum++, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
        glTexImage2D(GL_TEXTURE_2D, 0, img->iGlFormat, img->uiWidth, img->uiHeight, 0, img->iGlFormat, GL_UNSIGNED_BYTE, img->p_ubaData);
        img_free(img); //it may cause errors on windows
    } else printf("Error: loading texture '%s' failed!\n", filename);

    return texture;
}

```

actual loading

```
static GLuint textures[4];

static void gl_init() {
    (...) //setting up OpenGL

    /* loading textures */
    textures[0] = gl_loadTexture("images/background.png");
    textures[1] = gl_loadTexture("images/spaceship.png");
    textures[2] = gl_loadTexture("images/asteroid.png");
    textures[3] = gl_loadTexture("images/asteroid2.png"); //this is causing SegFault no matter which file I load!
}

```

Any ideas?

Problem is present on both Linux and Windows.

# Answer
I am not sure, but change this:

```
glGenTextures(iTexNum++, &texture);

```

into this:

```
glGenTextures(1, &texture);

```

Here is written:

> void glGenTextures( GLsizei n, GLuint\* textures );
>
> n - Specifies the number of texture names to be generated.
>
> textures - Specifies an array in which the generated texture names are stored.

You are generating 1,2,3,4,... texture names instead of one, so `glGenTextures()` is trying to write to array ( `texture[0]` \- `texture[3]` ), but you are passing single element `GLuint texture = 0;`, so you get segmentation fault.

And, please delete this double post.
> 2 votes

---
Tags: c++, opengl, textures
---


# Question
Title: How do I write an interface for the keyboard and mouse input?
I have started to develop a simple 3D engine. I use OpenGL for rendering, and it is developed for Windows. It is all written in C.

How do I write an interface for the keyboard and mouse input? I would like to keep it as simple as possible - in contrast to the native Win32 input system.

# Answer
> 2 votes
There is more than one one way to skin the cat. If I understand correctly, you want to be able to take input from keyboard and mouse and use that to control stuff in your engine. But to write such interface from scratch, by yourself, would not only be a classic case of reinventing the wheel, but also, a very tedious task (think about it... you want to be able to support PS/2 and USB mice, as well as keyboards and you must admit, testing whether there's something present in a particular port, polling through USB hubs and ports... it's too much hassle when there's already available software to do that for you, right?)

So you will save much time using an already developed interface/framework of that kind. Such a component is a part of already mentioned FreeGLUT, but there is also SDL, which handles not only that, but also window manipulation, threading and more. Check it out. Pay attention to SDL\_event struct and SDL\_PollEvent function.

# Answer
> 1 votes
There are frameworks like FreeGLUT that give a basic input/output abilities with keyboard and mouse, but if you want more there are the Visual C++ APIs for Windows.

---
Tags: input, c
---


title: Tangent to a circle through a point

text:
# Question
Title: Tangent to a circle through a point
I'm trying to figure out how to calculate the following angle:

I know center (**p1**) and radius (**r**) of a circle. Given a point **p3** I want to calculate the angle **a** such as the tangent (**tan**) of the circle at point **p4**, points in **p3** direction.

Here's a figure:

Doesn anyone know how to do that?

# Answer
Let `b` be the angle between vectors `p1p2` and `p1p3`. Its value can be computed as:

```
b = pi - atan2(p1p3.y, p1p3.x)

```

The angle between `p1p4` and `p1p3` is `b-a`. Since `p1p3p4` is a right-angled triangle, we know that `cos(b-a)` is the distance `p1p4` divided by the distance `p1p3`.

The answer is then:

```
a = pi - atan2(p1p3.y, p1p3.x) - acos(r / length(p1p3))

```

Replacing the second `-` with `+` will give you the second possible solution.
> 5 votes

# Answer
I was going to calculate this, then I failed, then I googled, then I found people who failed multiple times as well. But in the end some seem to have gotten it right :).

Read this entire thread, it should lead you to the correct algorithm.
> -1 votes

---
Tags: mathematics, angles
---


title: Architects into videogames

text:
# Question
Title: Architects into videogames
I'm an architecture student in my last year. I've always been interested in videogames design. I use 3d Max and Photoshop on a daily basis, and I was thinking about aiming for a career in videogames, starting as a level/environment designer.

How should approach it? Is it worthy to spend some time learning UDK or CryEngine? Should I try a smaller but more general software? I know some programming already.

Finally, will my skills as an architect be something valuable in the indusrty?

Thanks in advance.

# Answer
The most important thing that you have to do is to be able to show something. You need to build up a really strong portfolio, and this is gonna take a long time. There are a lot of people out there who would like the same job and they usually come from a moddeler/animation background so they will usually outclass you in any tool (they'vebeen using it for years) until you've spent hundreds, or even thousands, of hours using those tools as well. However being an architect you do have some pretty unique insights which, if you act smart, could be helpful to get noticed.

I would advice to try out a few tools. You need a modeling program to create the 3D models. As mentioned Blender is a fine and free option that is actually used in the game industry, but try out a few tools and use the one you find most comfortable to work with. The methodologies and techniques are often shared between products so you can quickly learn how to use another program if a job requires it. Getting prepped is not about learning tools but learning techniques. (Also don't worry to much about licensing, your boss will worry about that, unless if you want to go Indie, I think all tools allow snapshots for your portfolio but it's not a bad idea to skim the EULA).

For actually designing levels. So placing enemies, etc.. you can indeed use UDK or CryEngine or another game engine that has a neat level editor. Again all the above holds: techniques are more important than tools.

Unrelated to your question, but do a bit of soul searching. Why do you want to be in the game industry, it's great here but you have a slight disadvantage to make up in a really competitive industry. I don't want to discourage you, follow your dreams! But why did you want to become an architect in the first place and why change paths now? I image these are hard questions for yourself, you have so much options at the end of your study, be sure to check each one. Ask yourself where do you want to be in 10 years? (\*note that you almost always get that question when applying for a job :P). Good luck!
> 5 votes

# Answer
If you are ok with:

* paying money or finding a job in the industry
* make you work useless and confined in 1 single environment and confined in only the platforms supported by that engine

you will be fine with a commercial solution, otherwise if you want the maximum flexibility and you have the know-how, you probably want to code your own stuff and avoid spending money and legal issues.

Also all the software that you mentioned offers legal problems when it comes to using them on the job, some of them offers more complex issues, because for example the UDK, it's not really free for every use, if you are going to use it in the place where you work, you have to pay, no matter what you are producing with it. There are also nasty things like the standard Autodesk EULA allows Autodesk to basically fetch your computer for data without explicit warnings ans in "silent mode".

If i was you, i would switch to Blender and Gimp, this 2 are really powerful software, with a rich set of APIs and 0 legal issues, and they are free.
> -7 votes

---
Tags: game-industry, level-design, career
---


# Question
Title: Why doesn't light continuous on my model?
I created a basic textured cube model with Blender to practice modeling, and then I imported it into Unity. After I put up some lighting it looks pretty ugly. The light is not continuous on a row of textured cubes:

What is more odd, the light on the blocks that makes up the floor **is** continuous. What am I doing wrong?

This is what it looks like without textures:

If I did not know that these are perfect cubes, I'd say there is a slight curve on surface. I also tried lightening the texture but it also didn't help:

I just simply exported the model from Blender and did not set up any normals or things like that. However, I also did not do anything special with the floor brick model.

Checked the normals and they seem to point to the right direction.

Also I don't really see the difference between the two models. On the textures panel I also set the projection to flat:

I checked the different panels in Blender and the only normal-related option on the "Object Data" panel is this "Auto Smooth" and it is turned off by default:

# Answer
From the no-texture picture, I'm pretty sure the problem is that your cube models have inappropriate normals. You need to tell Blender that your cube edges are intended to be sharp, not smooth — what you have now are cubes that are acting like six-sided approximations of spheres.

I don't know Blender so I can't tell you exactly how to accomplish this, but it might be called "flat" instead of "smooth" faces or normals, or there might be a way to "break" a particular edge. Your floor-tile model appears to have correct normals, so perhaps you should see what's different about it.
> 7 votes

# Answer
A couple of suggestions as to what the problem may be:

a) Have you checked if all the face normals of the mesh are pointing in the right direction? Its quite straightforward to do this in Blender)

b) Have you applied the right UV mapping? Unity exports all the texture data based on how you set things up in Blender. Look at the Texture panel in Blender, especially the 'Mapping' panel under Textures (ideally, it ought to be set to UV.

(P.S. what is the policy here on attachments or posting links to project files, say a Dropbox or Google Drive link in the question? This should be so simple to fix if I could just see all the files.)
> 4 votes

---
Tags: 3d, unity, blender, 3d-meshes, lighting
---


# Question
Title: Inverting matrix then decomposing gives different quaternion than decomposing then inverting the quat
I'm getting different signs when I convert a matrix to quaternion and invert that, versus when I invert a matrix and then get the quaternion from it:

```
Quaternion a = Quaternion.Invert(getRotation(m));
Quaternion b = getRotation(Matrix.Invert(m));

```

I would expect a and b to be identical (or inverses of each other). However, it looks like q1 = (x, y, -z, -w) while q2 = (-x, -y, w, z). In other words, the Z and W components have been switched for some reason.

Note: `getRotation()` decomposes the transform matrix and returns just the rotation part of it (I've tried normalizing the result; it does nothing). The matrix `m` is a complete transform matrix and contains a translation (and possibly a scale) as well as a rotation. I'm using D3DXMatrixDecompose to do the actual decomposition.

# Answer
> 0 votes
The problem turned out to be one of numerical stability. I was able to solve the problem by ortho-normalizing the input rotation matrix before doing the operation.

# Answer
> 5 votes
Expressing rotations with quaternions can be done from an axis-angle representation, but not in a single way. For that same axis angle (w, a) pair, you get two quaternions performing the same task. One has its components based directly on the *w* vector and the *a* angle, the other has the same components, but negated. This is normal, since they describe the same rotation while the axis is pointing 180 degrees the other way and the angle is, this time, negated.

My hunch is that exactly this 1-to-1 failed mapping is what messes up things (i.e. the signs!!, not your weird rotations). It should not yield different rotation operations! Your `getRotation` function is the origin of those problems, but, I repeat, if **q1** is approximately equal to **-q2**, then everything should be ok.

# Answer
> 5 votes
Rotating a point `p` using a quaternion `q` is done with `q * [0, p] / q`. Replacing `q` with `-q` has absolutely no effect on the result.

If your rotations "go the wrong direction" when the sign of the quaternion changes, then the problem lies in the way you use the quaternions to rotate points.

---
Tags: mathematics, matrix, rotation, quaternion, transformation
---


# Question
Title: How to programatically retarget animations from one skeleton to another?
I'm trying to write code to transfer animations that were designed for one skeleton to look correct on another skeleton. The source animations consist only of rotations except for translations on the root (they're the mocap animations from the CMU motion capture database). Many 3D applications (eg Maya) have this facility built-in, but I'm trying to write a (very simple) version of it for my game.

I've done some work on bone mapping, and because the skeletons are hierarchically similar (bipeds), I can do 1:1 bone mapping for everything but the spine (can work on that later). The problem, however, is that the base skeleton/bind poses are different, and the bones are different scales (shorter/longer), so if I just copy the rotation straight over it looks very strange.

I've attempted a number of things similar to lorancou's solution below to no avail (ie multiplying each frame in the animation by a bone-specific multiplier). If anyone has any resources on stuff like this (papers, source code, etc), that would be really helpful.

# Answer
> 11 votes
The problem was one of numerical stability. Approx 30 hours of work on this over the course of 2 months, only to figure out I was doing it right from the very start. When I ortho-normalized the rotation matrices before plugging them into the retarget code, the simple solution of multiplying source * inverse(target) worked perfectly. Of course, there's a lot more to retargeting than that (in particular, taking into account the different shapes of the skeleton, ie shoulder width, etc). Here's the code I'm using for the simple, naieve approach, if anyone is curious:

```
    public static SkeletalAnimation retarget(SkeletalAnimation animation, Skeleton target, string boneMapFilePath)
    {
        if(animation == null) throw new ArgumentNullException("animation");
        if(target == null) throw new ArgumentNullException("target");

        Skeleton source = animation.skeleton;
        if(source == target) return animation;

        int nSourceBones = source.count;
        int nTargetBones = target.count;
        int nFrames = animation.nFrames;
        AnimationData[] sourceData = animation.data;
        Matrix[] sourceTransforms = new Matrix[nSourceBones];
        Matrix[] targetTransforms = new Matrix[nTargetBones];
        AnimationData[] temp = new AnimationData[nSourceBones];
        AnimationData[] targetData = new AnimationData[nTargetBones * nFrames];

        // Get a map where map[iTargetBone] = iSourceBone or -1 if no such bone
        int[] map = parseBoneMap(source, target, boneMapFilePath);

        for(int iFrame = 0; iFrame < nFrames; iFrame++)
        {
            int sourceBase = iFrame * nSourceBones;
            int targetBase = iFrame * nTargetBones;

            // Copy the root translation and rotation directly over
            AnimationData rootData = targetData[targetBase] = sourceData[sourceBase];

            // Get the source pose for this frame
            Array.Copy(sourceData, sourceBase, temp, 0, nSourceBones);
            source.getAbsoluteTransforms(temp, sourceTransforms);

            // Rotate target bones to face that direction
            Matrix m;
            AnimationData.toMatrix(ref rootData, out m);
            Matrix.Multiply(ref m, ref target.relatives[0], out targetTransforms[0]);
            for(int iTargetBone = 1; iTargetBone < nTargetBones; iTargetBone++)
            {
                int targetIndex = targetBase + iTargetBone;
                int iTargetParent = target.hierarchy[iTargetBone];
                int iSourceBone = map[iTargetBone];
                if(iSourceBone <= 0)
                {
                    targetData[targetIndex].rotation = Quaternion.Identity;
                    Matrix.Multiply(ref target.relatives[iTargetBone], ref targetTransforms[iTargetParent], out targetTransforms[iTargetBone]);
                }
                else
                {
                    Matrix currentTransform, inverseCurrent, sourceTransform, final, m2;
                    Quaternion rot;

                    // Get the "current" transformation (transform that would be applied if rot is Quaternion.Identity)
                    Matrix.Multiply(ref target.relatives[iTargetBone], ref targetTransforms[iTargetParent], out currentTransform);
                    Math2.orthoNormalize(ref currentTransform);
                    Matrix.Invert(ref currentTransform, out inverseCurrent);
                    Math2.orthoNormalize(ref inverseCurrent);

                    // Get the final rotation
                    Math2.orthoNormalize(ref sourceTransforms[iSourceBone], out sourceTransform);
                    Matrix.Multiply(ref sourceTransform, ref inverseCurrent, out final);
                    Math2.orthoNormalize(ref final);
                    Quaternion.RotationMatrix(ref final, out rot);

                    // Calculate this bone's absolute position to use as next bone's parent
                    targetData[targetIndex].rotation = rot;
                    Matrix.RotationQuaternion(ref rot, out m);
                    Matrix.Multiply(ref m, ref target.relatives[iTargetBone], out m2);
                    Matrix.Multiply(ref m2, ref targetTransforms[iTargetParent], out targetTransforms[iTargetBone]);
                }
            }
        }

        return new SkeletalAnimation(target, targetData, animation.fps, nFrames);
    }

```

# Answer
> 5 votes
I believe that your easiest option is simply to match the original bind pose with your new skeleton if you've got the possibility (if your new skeleton isn't skinned yet).

If you can't do that, here's something you could try. This is just intuition, I'm probably overlooking lots of things, but it might help you to find the light. For each bone:

* In your "old" bind pose, you've got one quaternion that describes the *relative* rotation of this bone compared to its *parent* bone. Here's a hint for how to find it. Let's call it `q_old`.
* Ibid. for your "new" bind pose, let's call it `q_new`.
* You can find the relative rotation from the "new" bind pose to the "old" bin pose, as described here. That's `q_new_to_old = inverse(q_new) * q_old`.
* Then in one animation key, you've got your one quaternion that transforms that bone from the "old" bind pose to an animated pose. Let's call this one `q_anim`.

Instead of using `q_anim` directly, try using `q_new_to_old * q_anim`. This should "cancel" the orientation differences between the bind poses, before applying the animation.

It might do the trick.

**EDIT**

Your code above seems to follow the logic I'm describing here, but something's inverted. Instead of doing this:

```
multipliers[iSourceBone] = Quaternion.Invert(sourceBoneRot) * targetBoneRot;

```

You could try that:

```
multipliers[iSourceBone] = Quaternion.Invert(targetBoneRot) * sourceBoneRot;

```

I think that you need to transform from your target to your source before applying the source animation, to get the same final orientation.

---
Tags: 3d, animation, skeletal-animation
---


# Question
Title: Any link / tutorial of how to develop MVC pattern?
I want to learn how to develop a MVC pattern, but i can't find any site in where they focus it to Games and not to Browser / Windows calculator.

Would anyone please link me a tutorial of how to develop MVC patter for games?

Thank you very much

# Answer
> 2 votes
Take a look at Game Coding Complete. McShaffry makes use of the MVC architecture and explains its uses well.

The basic gist of it in terms of games is usually:

*Model*
This is your game logic. Game state changes, scripted events, rulesets, etc.

*View*
This is mainly the rendering aspect of the game. If you wanted to be cross-platform and support more graphics APIs, you'd just need to change the View portion of the game without touching any of the other code.

*Controller*
Pretty much what it sounds like. This section handles the input events that affect the game state (Model) and in turn what happens on screen (View). You can be a bit clever with this for AI, for example. You could have a PlayerController and an AIController that both send input events to the Model code.

Similarly, the View can be AI sensors in order to observe the environment to make decisions (a heavily subsidised version of the player's view).

Hope that helps.

---
Tags: mvc
---


# Question
Title: How can I easily create cloud texture maps?
I am making 3d planets in my game; these will be viewed as "globes". Some of them will need cloud layers. I looked at various Blender tutorials for creating "earth", and for their cloud layers they use earth cloud maps from NASA.

However I will be creating a fictional universe with many procedurally-generated planets. So I would like to use many variations.

I'm hoping there's a way to procedurally generate cloud maps such as the NASA link. I will also need to create gas giants, so I will also need other kinds of cloud texture maps.

If that is too difficult, I could fall back to creating several variations of cloud maps. For example, 3 for earth-like, 3 for gas giants, etc.

So how do I statically create ***or*** programmatically generate such cloud maps?

# Answer
> 19 votes
Cloud generation is fun! I'll cover both offline and runtime methods.

## Pre-rendered clouds

If you want to pre-render your cloud textures offline, look no further than Photoshop (or Gimp, if you prefer). Both programs can easily generate cloud patterns. Menu items tend to move around between releases, but as of Gimp 2.8.2 the core command you're looking for is `Filters -> Render -> Clouds -> Solid Noise`. You'll need to create a new blank image before the command is enabled. I encourage you to experiment with the noise parameters, but just as one example, here's what happens if you set "Random Seed" to 1, "Detail" to 4, "X Size" to 4.0, "Y Size" to 8.0, disable "Randomize" and "Turbulent", and enable "Tilable":

One further step I definitely recommend is editing the image's levels (`Colors -> Levels...` in Gimp). By dragging the endpoints around, you can effectively change the level of cloud cover from "fully overcast" to "not a cloud in the sky".

Other interesting possibilities:

* Use the "Dodge" and "Burn" tools to manually brighten/darken portions of the image.
* Warp the cloud image to suggest wind patterns. Try Gimp's `Filters -> Distorts -> Whirl and Pinch...` command, or for more control use `Filters -> Distorts -> IWarp...` with the Deform Mode set to "Swirl". Keep it subtle, though -- too much warping tends to blur the high-frequency detail out of the image.
* Add multiple independent cloud layers to simulate different types of clouds, from thin and wispy to big & chunky (I'm sure they have proper scientific names, but damnit Jim, I'm a programmer, not a meteorologist!). In this case, you'd probably want to save each layer as a separate image so you can animate them independently at runtime.

It really depends on your artistic vision. Go nuts! When you're finished, remember to export the texture as a single-channel grayscale image, so you can use the same cloud data for your color and alpha channel at runtime.

## Runtime cloud generation

Generating unlimited cloud patterns at runtime is a bit more involved, but still totally feasible. It's a huge topic, and this will only cover the broad strokes.

Basically you're going to replicate Gimp's "Solid Noise" command in your shader code, using a noise function like the canonical Perlin Noise to generate infinite, smooth, deterministic, (optionally) periodic noise volumes. Your question didn't specify which rendering API you're targeting, so I can't get too specific here; chapter 26 of "GPU Gems 2" covers a variant of Perlin noise in (somewhat dated) HLSL and CgFX, or you can use this drop-in GLSL noise function. By sampling a 2D slice of a 3D noise volume, you get something like the Gimp "Solid Noise" command with Detail=0. The lower the distance between your noise volume samples, the lower-frequency ("smoother") your noise will be. To increase the level of high-frequency detail, start with a base low-frequency noise pattern and add additional higher-frequency "octaves" of noise, where each "octave" is a different slice of the 3D noise volume with a larger sampling distance and lower amplitude. A visual example of this process (which I found by Googling "multi-octave Perlin noise") can be found here.

As a huge added bonus, cloud textures generated in this fashion can very easily be animated! Add a time-based offset to your 3D noise function sample coordinates, and you'll get extremely convincing cloud motion (as seen in this video, for example). This is because the noise function is smooth in all three dimensions; scrolling the texture in the U/V direction causes the clouds to move around the planet, while scrolling in the W (perpendicular) direction has the effect of slowly "evolving" the clouds.

Warping clouds at runtime is possible as well, for hurricane-like effects. Results can actually be much higher quality than the naïve Gimp warp filters, which (as mentioned earlier) can lead to an overly blurry texture. One technique you definitely want to look into is "flow maps", as described by Alex Vlachos of Valve (SIGGRAPH 2010 slides) or Carlos Gonzalez of Naughty Dog (GDC 2012 slides). The basic idea is that you paint a vector field (the "flow map") and use it to distort and scroll the cloud texture at runtime, while periodically cross-fading between two different cloud textures when the distortion distance gets too high.

## Which method to use?

Pre-rendering cloud textures in Gimp/Photoshop is extremely easy; you can generate a new texture in a few seconds once you get the hang of it. The runtime code is trivial, and very fast. However, more unique cloud textures means higher disk space requirements (also, a larger/slower download) and more VRAM usage at runtime.

Runtime cloud generation is much more difficult at first, but once you get it working it has several clear advantages over pre-rendered cloud textures. You can generate an infinite variety of realistic animated cloud patterns without using any additional disk space or VRAM. However, the runtime cost of evaluating multiple 3D noise functions per-pixel can be steep; your cloud pixel shaders will be much slower than they in the pre-rendered case.

**TL;DR:** definitely start by using pre-rendered clouds, and switch to runtime procedural clouds if you need the extra variety (or want an extra programming challenge).

---
Tags: graphics, procedural-generation
---


# Question
Title: "Unable to create OpenGL 3.3 context (flags 0, profile 1)"
Trying to run any of the well-known McKesson's tutorials on a friend's laptop results in the aforementioned exception.

I read that in order to run applications which use OpenGL 3.3 you must at least have an ATI HD or Nvidia 8xxx GPU series. He has an ATI HD class graphics processor which eliminates (maybe) this issue. Also, I read that this error may result in having old drivers. He updated his drivers but that didn't solve the problem.

The tutorials are built as said in the book introduction and glsdk is installed.

If more information is needed, say so and I will provide it.

What are the other reasons for this kind of exception? And how can I fix them?

# Answer
> 3 votes
Your problem is most likely the fact that, by default, your system launches most programs using the Intel300 chipset or some other integrated graphics card. The simplest solution is to right-click the .exe which is created after building and select "Run graphics processor" and select the ATI/Nvidia card. You can also change the default chipset to ATI/Nvidia so you dont have to do this everytime you want to test a file but know that it may cause heating/battery problems on your system. This is all in Windows 7 by the way.

---
Tags: c++, opengl
---


# Question
Title: Why does my 3D model not translate the way I expect?
In my first image, my model displays correctly:

But when I move the model's position along the Z-axis (forward) I get this, yet the Y-axis doesnt change. An if I keep going, the model disappears into the ground:

Any suggestions as to how I can get the model to translate properly visually? Here is how Im calling the model and the terrain in `draw()`:

```
cameraPosition = new Vector3(camX, camY, camZ);

        // Copy any parent transforms.
        Matrix[] transforms = new Matrix[mShockwave.Bones.Count];
        mShockwave.CopyAbsoluteBoneTransformsTo(transforms);
        Matrix[] ttransforms = new Matrix[terrain.Bones.Count];
        terrain.CopyAbsoluteBoneTransformsTo(ttransforms);

        // Draw the model. A model can have multiple meshes, so loop.
        foreach (ModelMesh mesh in mShockwave.Meshes)
        {
            // This is where the mesh orientation is set, as well
            // as our camera and projection.
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.EnableDefaultLighting();
                effect.PreferPerPixelLighting = true;
                effect.World = transforms[mesh.ParentBone.Index] *
                    Matrix.CreateRotationY(modelRotation)
                    * Matrix.CreateTranslation(modelPosition);
                // Looking at the model (picture shouldnt change other than rotation)
                effect.View = Matrix.CreateLookAt(cameraPosition,
                    modelPosition, Vector3.Up);
                effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                    MathHelper.ToRadians(45.0f), aspectRatio,
                    1.0f, 10000.0f);
                effect.TextureEnabled = true;
            }

            // Draw the mesh, using the effects set above.
            prepare3d();
            mesh.Draw();
        }

        //Terrain test
        foreach (ModelMesh meshT in terrain.Meshes)
        {

            foreach (BasicEffect effect in meshT.Effects)
            {
                effect.EnableDefaultLighting();
                effect.PreferPerPixelLighting = true;
                effect.World = ttransforms[meshT.ParentBone.Index] *
                    Matrix.CreateRotationY(0)
                    * Matrix.CreateTranslation(terrainPosition);
                // Looking at the model (picture shouldnt change other than rotation)
                effect.View = Matrix.CreateLookAt(cameraPosition,
                    terrainPosition, Vector3.Up);
                effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                    MathHelper.ToRadians(45.0f), aspectRatio,
                    1.0f, 10000.0f);
                effect.TextureEnabled = true;
            }

            // Draw the mesh, using the effects set above.
            prepare3d();
            meshT.Draw();
            DrawText();
        }
        base.Draw(gameTime);
    }

```

I'm suspecting that there may be something wrong with how I'm handling my camera. The model rotates fine on its Y-axis.

# Answer
I had an bug in my camera. I was translating in `Vector3.Up` and `Vector3.Right` at the same time within my input class. Both were set to one thumbstick. Removing `Vector3.Right` from the thumbstick for movement in the cardinal directions resolved the problem.
> 0 votes

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


title: Pathfinding and BSP with Box2D

text:
# Question
Title: Pathfinding and BSP with Box2D
I'm looking into implementing AI in my 2D side-scrolling platformer, and I'm looking into using algorithms such as A\*. For many kinds of pathfinding, we need some sort of grid or systems of nodes or polygon areas. My problem is that I am using Box2d for physics and I am not sure how best to create a structure that my AI can use besides placing individual nodes manually (something I really want to avoid) and using some sort of steering behavior.

My level design is tile-based with each tile being about half of the height/width of my main character. The tiles are not all square (some are sloped). I'd like to have a system that can see what the terrain looks like for pathfinding and also keep track of the positions of other actors such as enemies. I'd like to avoid directly placing any nodes into my level design except for possible endpoints or goals.

This question is related: How do you do AI path following within a 2d physics engine like farseer/box2d?, but it doesn't specify what kind of structure I could use instead of a list of nodes. I'm looking for some kind of grid or type of BSP that I can query for algorithms like A\*.

**EDIT:** I am looking for a data structure that meets the following requirements:

* Can be searched by algorithms like A\*
* Can keep track of objects that move around
* Can keep track of objects of different shapes and sizes
* Does not require me to manually create paths or place nodes

When I first load my level, I have a 2D array (actually just a width, height, and string of ints), but this doesn't allow me to track objects that move not to mention other shortcomings.

# Answer
> 3 votes
Do you really need path-finding? Most enemy behavior for a 2D platformer can be implemented with some simple rules and sensors. Eg. Have a sensor in front of the entity that detects a hole or a wall and change direction or jump when something like this happens.

You'll need path-finding if your enemy needs to find the fastest route to different targets (eg. a power-up that he wants to snatch away from the player, or the player himself). If you just need a static path from A to B, you could draw that in the level-editor or do path-finding offline (eg. load the level data, perform path-finding on level grid, write the path-data to another file or into the level-file).

Since your level is tile-based, you already have a grid... for every (walkable) tile you place, you can add a node to your data-structure. Ideally this happens when you parse/load the level data. If your entities are able to jump, things get slightly more complicated, but a naive solution would be to add all "air" tiles (reachable with a jump) above walkable tiles to the path finding-structure so that these can also be searched.

---
Tags: java, ai, box2d, path-finding
---


title: Central renderer for a given scene

text:
# Question
Title: Central renderer for a given scene
When creating a central rendering system for all game objects in a given scene I am trying to work out the best way to go about passing the scene to the render system to be rendered.

If I have a scene managed by an arbitrary structure, i.e., an octree, bsp trees, quad-tree, kd tree, etc. What is the best way to pass this to the render system?

The obvious problem is that if simply given the root node of the structure, the render system would require an intrinsic knowledge of the structure in order to traverse the structure.

My solution to this is to clip all objects outside the frustum in the scene manager and then create a list of the objects which are left and pass this simple list to the render system, be it an array, a vector, a linked list, etc. (This would be a structure required by the render system as a means to know which objects should be rendered). The list would of course attempt to minimise OpenGL state changes by grouping objects that require the same rendering operations to be performed on them.

I have been thinking a lot about this and started searching various terms on here and followed any additional information/links but I have not really found a definitive answer. The case may be that there is no definitive answer but I would appreciate some advice and tips.

My question is, is this a reasonable solution to the problem? Are there any improvements that I could make? Are there any caveats I should know about?

Side question: Am I right in assuming that octrees, bsp trees, etc are all forms of BVH?

# Answer
Here goes, hope I can answer all of your questions as some of them don't have a definitive answer but are more a personal preference. Also, some of it depends on things like the platform you develop for, how important speed is, how important extensibility is, etc.

> When creating a central rendering system for all game objects in a given scene I am trying to work out the best way to go about passing the scene to the render system to be rendered.

Great start, but with one note. There is absolutely nothing wrong with a generalized system for rendering, but keep in mind that any generalized system is almost always a slower system and more important, costs a lot of extra code to write and maintain. There are cases where foregoing such systems for the simplest in place solution (in your case, no rendering manager or a render manager with intrinsic knowledge of the game) might be the best solution. That being said, go for it and write a complex system if you need it, or if you just feel like it. Just think about the reasons for everything you do.

> If I have a scene managed by an arbitrary structure, i.e., an octree, bsp trees, quad-tree, kd tree, etc. What is the best way to pass this to the render system?
>
> The obvious problem is that if simply given the root node of the structure, the render system would require an intrinsic knowledge of the structure in order to traverse the structure.
>
> My solution to this is to clip all objects outside the frustum in the scene manager and then create a list of the objects which are left and pass this simple list to the render system, be it an array, a vector, a linked list, etc. (This would be a structure required by the render system as a means to know which objects should be rendered).

Good idea! I don't have much to say against this system, but since you asked for improvements and caveats, let's go through some.

First of, a good idea would be to keep a separate data structure for the objects in the scene and the renderable objects. Objects in the scene might be complete classes with lots of data on object state necessary for gameplay but totally irrelevant for rendering. So create a very simple struct for renderables, just add pointers to the data you need for rendering, or even simpler, make it a struct with two fields, a sort key and a pointer/index/id to the render data structure that resides somewhere else in memory.

Second, store your data in a way that makes multiple passes easy. You never want to render your scene just once, you may need multiple passes for certain graphical algorithms. Also, not every pass needs the same objects. To give a hypothetical example, you first render your shadow map from the light perspective (different objects visible/culled), then you want to render a quick depth pass with all opaque geometry to fill the depth buffer, then you render your main pass, followed by particles at a different resolution, and in the end you need to do some post processing using the scene you just rendered. If you want to do deferred rendering, that adds some more passes with different settings and objects.

Third, data may need to be sorted differently for each pass. For filling the depth buffer, you may want to sort front-to-back, for particles you may want to render back to front.

As a solution to some of these issues, you could decouple clipping/culling from the scene manager and add it to the chain, so you just pass all objects from the scene manager through the clipping manager which only adds visible objects to the render queue. This might also make it easier to optimize culling by first storing all objects to be rendered in an array and then going through them sequentially, which might be more efficient in terms of cache usage etc. Then again, maybe you already do this in a very efficient manner in your scene manager, which I can imagine if you use an octree or something like that. Up to you.

What comes to my mind right now is a solution where you create different buckets for different render passes. Each bucket could have its own culling system and have an efficient tree structure that automatically sorts data when it's added (trees are great for that). So the scene manager just walks through its set of objects to be rendered and adds a "Render Struct" to the render manager. This render struct is now copied and passed to each bucket. If it gets through the culling system, it's added to the tree.

Then again, this is a really complex solution, maybe it's waaaay to complex for your situation. Also, I have no idea if all the things I just said are actually that efficient. It all depends, as always, on the data and what you need to do with it. So, know your data and always profile/test your code to see if the beautiful and complex generic system you worked so hard on is that much faster than the simple and fast solution (note that I'm not advocating quick and dirty solutions, simple and fast does not mean it's a hack! You should never use hacks!)

> The list would of course attempt to minimise OpenGL state changes by grouping objects that require the same rendering operations to be performed on them.

That's pretty old advice actually. It's bandied around a lot, but it's origins lie in the very first generations of GPUs. It was definitely good advice back 10 years ago, but there isn't much advice from those days that's still true today so I would want to do some further research on that if I were you, before you base your rendering code on that.

> I have been thinking a lot about this and started searching various terms on here and followed any additional information/links but I have not really found a definitive answer. The case may be that there is no definitive answer but I would appreciate some advice and tips.

There is no definitive answer to anything in the world of computer science and gaming. Ideas that were great 10 years ago are useless now, and the latest and greatest innovations of today will be outdated 5 or 10 years from now. The reason is simple and two-fold: data and architecture. Both change constantly. What works on an ARM system with limited CPU power and memory may be useless on a 3+ GHz quad core with 8 GB of RAM. What works on a close to metal PowerPC based console may be useless on an Android game that runs JIT-ed bytecode. So architecture changes, but data used in games changes a lot too. How many objects in your game? How many polygons, how many lights, what kind of shaders do you use. How many objects change and how much of the scene is static?

> My question is, is this a reasonable solution to the problem? Are there any improvements that I could make? Are there any caveats I should know about?

Know your data and your architecture through and through and you will be able to tell what the best solutions are. Not sure, then profile it! Never assume, always measure. So is your solution a good one? It certainly is, but there are also cases where it might be overkill, either because your data does not need a complex solution like that, or because it might kill performance if you use low-power hardware. It might also be too general where a system tailored to your scene could be a lot faster. You know your situation better than anyone, so you tell us :) Hope this helps!
> 2 votes

# Answer
The best way? No such thing. Depends on the needs of your game.

As for a good way, there are two.

* There's a common scene structure that the renderer draws and does some caching internally, if necessary - this works great for simple games but might add unnecessary overhead on AAA-like games.
* Renderer is a factory of the associated items (meshes, lights etc.). This lets you associate rendering caches with per-instance data easier at the cost of manually managing these items everywhere.

There are also a few things to avoid:

* Do not mix scene graphs in the renderer as the renderer does not need to care about them. Culling doesn't care if a Handle is a child of Door. Performance suffers from such things. Batching such constructs is impossible if you render the tree top-down. Want to hierarchially stick items together? Just send the calculated world matrices to the renderables.
* Don't use retrieval-based interfaces like GetAllRenderables() - they unnecessarily slow down the processing with extra copies of the data. Store the data as you're going to process it.

P.S. I'd suggest you avoid using Ogre, Irrlicht and such "engines" as examples. They're so poor that no one who's serious about game development uses them.

---

Since I've posted something controversial here, I'm adding some explanations (which I shouldn't really but I guess there's no harm in being explicit about things).

Irrlicht: scene nodes are renderables. As I've noted above, this leads to poor batching possibilities, let alone obvious problems with having a component system built with the engine (like not having a place for such things - but hey, *it's supposed to be a -game- engine...*). There's also a problem with logical grouping of code in the sense that all rendering code is scattered all over the source code.

Ogre: it's so overdesigned (?) and so heavy that the code is unreadable and compiles slowly. Whatever problem they had come upon, they just applied an STL container on it. Well, it's not Boost but it's still bad. Such a design is guaranteed to be slow because of the insane amount of memory allocations required. Multimap? Seriously? Just use a sorted array (vector)... And the in-code documentation really doesn't help anyone understand what happens under the hood, which is why people actually refer to source code of any API.

If this is not enough, just ask me in the comments.
> 1 votes

# Answer
You can take OGRE 3D as reference. It allows API user to use arbitary scene management data structure.

One thing i learnt when going down this road is that the more genric the rendering engine, the less optimisation and less efficiently it will run. At some point when dealing with more advanced rendering, will definitely complicate things a lot. e.g. billboards, UI, particle system, tranparency, color picking, stencils, multiple viewports, render to some-other-buffer-or-file. Perhaps placing a limit somewhere is not too bad.

You might already be thinking to create an abstract SceneManager from which all scene management strutures are derived, and let the renderer query it through its interface methods such as an `Renderable* getRenderables() function` (C/C++). You might also want to make your SceneManager graphics API agnostic at the same time.

But really, when you have so many possible types of Renderables, I don't know if you still can easily "minimise OpenGL state" changes and still have both worlds.

The last time I did it, there were 2 options: create a very all-encompassing SceneManager interface; or just make OpenGL state changes calls from inside SceneManager.

I would be interested to see how you approached it.
> 0 votes

---
Tags: architecture, rendering, software-engineering
---