title: Manual GLU.gluUnproject

text:
# Question
Title: Manual GLU.gluUnproject
Before I used GLU.gluUnproject to calculate my picking ray in my OpenGL game. Recently I switched to my own calculated matrices, and now I can forget the gluUnproject.

How can I calculate the picking ray with my own matrices?

My picking ray code (for the fixed pipeline):

```
public Ray getPickingRay() {
    FloatBuffer modelBuffer = BufferUtils.createFloatBuffer(16);
    FloatBuffer projBuffer = BufferUtils.createFloatBuffer(16);

    glGetFloat(GL_MODELVIEW_MATRIX, modelBuffer);
    glGetFloat(GL_PROJECTION_MATRIX, projBuffer);

    IntBuffer viewPort = BufferUtils.createIntBuffer(16);
    glGetInteger(GL_VIEWPORT, viewPort);

    FloatBuffer obj_pos = BufferUtils.createFloatBuffer(3);
    float middleX = (Display.getWidth() / 2)-0.01f;
    float middleY = (Display.getHeight() / 2)-0.01f;
    GLU.gluUnProject(middleX, middleY, 1.0f, modelBuffer, projBuffer, viewPort, obj_pos);

    Vector3f objPos = new Vector3f(obj_pos.get(0), obj_pos.get(1), obj_pos.get(2));

    Vector3f.sub(objPos, game.player.position, objPos);

    return new Ray(game.player.position, objPos);
}

```

At first I thought I just could use my own model- and projection matrix, but I have not found a way to manually calculate the GL\_VIEWPORT intBuffer.

Thanks folks.

# Answer
The values you'd get from `glGet` with `GL_VIEWPORT` (that you were previously passing to `glUnProject`) are the same values you have previously used to define the OpenGL viewport size using glViewport.

If, as noted in the referenced documentation, you've never called `glViewport` yourself, the width and height of the viewport are the dimensions of the (client area) of the window (and the X and Y values are both zero). You can therefore use the bounds of the client area of your window in the computation of your pick ray where glUnProject would have used the `GL_VIEWPORT` values.
> 2 votes

---
Tags: opengl, shaders, matrix, lwjgl, picking
---


# Question
Title: How can I prevent a buggy old version of my game from posting scores to the Gamecenter Leaderboards?
I found that an older version of my game has a bug that causes some crazy scores to be posted to the leaderboard. I can delete these scores by editing the acceptable range in iTunesConnect and my latest patch fixes the scores from being submitted again, but that doesn't stop users who haven't updated from posting these bad scores.

Is there a solution? Is there a way to require a minimum app version for gamecenter achievements? Is there a way to delete that leaderboard and simply make a new one for the next version?

The only solution I can think of is to limit the acceptable score range to keep most of the bad scores out, but this could potentially kill a really good legitimate score and still let in lots of bad ones.

# Answer
> 4 votes
I think your only real option here is to create a new leaderboard and update your app. (I believe you can enable/disable specific leaderboards when updating the app.) The new app version would simply not use the old leaderboard, and enable the new one.

The obvious downside here is the loss of previous high scores, but you should probably explain the problem in your update.

---
Tags: leaderboards, game-center, anti-cheat
---


# Question
Title: What are the benefits of binary format when storing map info?
I am developing isometric 2D exploration game. At this moment I faced with a problem where game takes too much disk space. Game's world at this moment is about 1 square kilometer and it's about 50MB.

I need to somehow squeeze it. Should I think about compressing it to archive or maybe there's some kind of game files packing technique?

What about binary? Can someone explain me the magic behind it? I heard that a lot of people use it, but when I tried to use it - it took same amount of space like simple .txt file.

I'm new on file formats, so I would be grateful for any ideas. Thanks.

# Answer
> 8 votes
**Use the organization of the data to your benefit.** You can always be expect the data in the same order, so you know what the next bytes belong to. For example (not specific to your data), when reading in the data, always expect two bytes for tile type, two bytes for lighting information and then two bytes for extra info. So it knows that after 6 bytes, it's time to move onto the next tile. Don't store strings for your tile types, with two bytes you have many thousands of different types. It can take two bytes just to store one character depending on the format.

**Don't store position information**, it should be implied in the tile order. Always store the tile information in chunks, one column at a time (or one row at a time). This allows you to know the position of the next tile, without needing to read it from the byte stream. You read the starting position of the chunk, then the first tile is placed at that position. Then you know the second tile will be placed at the chunk position plus one in the Y direction (if sending column per column).

If your goal is to make the file smaller, you are probably going to have to give up the human readable feature (which is what your current formatting looks like it was designed for).

As for defining tiles as numbers. You just create a "conversion chart" in your code:

```
Decimal : Name     : Byte Value
0       : None     : 0000 0000
1       : Dirt     : 0000 0001
2       : Grass    : 0000 0010
3       : Snow     : 0000 0011
...
230     : Lava     : 1110 0110

```

If you have less than 256 different types of tiles (dirt, grass, sand, etc.), which is likely, you should just write a single byte to store the value of the tile.

When you write the data, make you're writing in a binary format. If you're writing characters as numbers, you're not doing it right. When you read the data back in, you check the byte value against your chart, and load the appropriate tile in to the game.

Look into how your language of choice can write to a byte stream, or write bytes directly. It's clear that you're writing text to your file because you have new lines for each tile. A binary format is probably going to be unreadable for your average text file editor. But your game can read it, so it doesn't matter.

# Answer
> 4 votes
What Byte56 says makes sense.

I'm not sure why you need 2 separate coordinates (chunk coords and xy coords). But since a map is always square, the most basic representation is a 2D array of ascii chars

```
..,,.....@
..,,@@@@@@
...,,,...@
......,..@

```

So there is the specification of a 4x10 map in 40 bytes. A 10,000 x 10,000 map would take 95MB, which isn't that bad. Because of the repetition, simple compression using zlib would probably reduce the size a lot.

To make this work, you can merge the information of tile-type and walkability together. So `@` is an impassible tree, for example, and `.` is (passable) grass, and `,` is (passable) dirt. The world space coordinates of each tile is implied, as each "chunk" here is a fixed size (say 1 world unit x 1 world unit). The bottom left corner of the world could be placed at 0,0.

Using single characters means each tile can represent one of 255 different things. If you want 65,536 different things represented, you could use unicode. If you want more, you could use UTF-32.

To add in items, and NPC's you could use an item layer.

```
.......$$.
..t.......
....W.....
..........

```

Where `.` means empty and `$` means money.

You probably could store the map size and some kind of "key" as to what each character means in the header of this map file format.

---
Tags: file-format, binary
---


title: Opengl shader questions

text:
# Question
Title: Opengl shader questions
I'm currently building a shader that takes a 2D texture sampler and uses UV coordinates to map it. This works fine for all textured objects. However, I'm having a bit of a problem as I'm trying to render a Mesh with no texture and the shader objects just keeps sampling based on the parameters of the last object I rendered. What is a good way to make sure whenever no texture is available it will just treat it as a white texture or something?

One thing I've thought of was creating and binding a white 1x1 texture but that seems overkill.

Related question: I've been wondering about this and I've yet to find an answer: Is it best to make a multi-purpose shader or constantly change the shader program for different objects in the same render update? For instance, should I have just created a shader for non-textured objects?

# Answer
> 2 votes
It sounds to me like you need another shader that doesn't do any texture sampling.

In general, shaders perform poorly when you give them conditional logic. This mainly includes if statements and for loops. So if you have some objects that you want to apply a single texture to, and some that you want to apply none to, it's best to use two different shaders.

Consider all the different functions you might perform in a shader. Different lighting (and different numbers of lights), texturing, coloring, bump/normal mapping... if you were to try to cram all of these things into one shader, you'd have a very messy bit of code, and it would be littered with performance-sucking conditional logic.

Some of these things, like the number of lights or the number of textures used, can be changed with a single line of code, by assuming that the shader compiler will make some optimizations for you. Consider the case of using multiple lights:

```
#define NUM_LIGHTS 8

void main() {
    // ...
    for ( int i=0; i<NUM_LIGHTS; i++ ) {
        // ....
    }
 }

```

In this case, the compiler should perform loop unwinding here and give you branchless code, but you still enjoy readable and maintainable code.

My game engine uses a variable substitution system where I can use shader code like above and replace it to support fixed number of lights very easily. For example, I might have:

```
#define NUM_LIGHTS {0}

```

When I load my shaders, I'll take this specific shader and replace that number numerous times to produce a shader that will handle a very specific number of lights.

# Answer
> 2 votes
The way I do it is build one general-purpose shader program with optional parts sectioned off using preprocessor conditionals. For example, a simple fragment shader with optional texture mapping:

```
#ifdef TEXTURE_MAPPING
    uniform sampler2D uSampler;
#endif

void main()
{
    #ifdef TEXTURE_MAPPING
        vec4 fColor = texture(uSampler, vUV);
    #elif
        vec4 fColor = vec4(1.0);
    #endif
}

```

These flags such as `TEXTURE_MAPPING` or `SPECULAR_SHADING` are defined in the game code when the shader is compiled. In my system, the flags are mapped to a bitfield which is used to look up the desired shader progam object.

Therefore, your material is essentially a bitfield + a program identifier + uniform data. The bitfield governs which uniform data must be present.

---
Tags: opengl, shaders, fragment-shader
---


# Question
Title: Moving a Box2D object in the direction it is facing using applyForce
I'm trying to apply force to a polygon physics object to move it. Whilst I can get it to move upwards easily enough, I'm trying to get it to move in the direction in which it is pointing.

Here's my current movement code -

```
private void controls(){
    if(Gdx.input.isKeyPressed(Keys.D)|| Gdx.input.isKeyPressed(Keys.RIGHT)){
        shipBody.applyAngularImpulse(-Global.ROTATIONSPEED, true);
    }

    if(Gdx.input.isKeyPressed(Keys.A)|| Gdx.input.isKeyPressed(Keys.LEFT)){
        shipBody.applyAngularImpulse(Global.ROTATIONSPEED, true);
    }

    if(Gdx.input.isKeyPressed(Keys.W)|| Gdx.input.isKeyPressed(Keys.UP)){
        shipBody.applyLinearImpulse(Global.IMPULSE,
                                    shipBody.getWorldCenter(), true);
    }

    System.out.println("Ship angle: " + shipBody.getAngle() * (float)(180 / Math.PI));
}

```

`Global.Impulse` is:

`public static final Vector2 IMPULSE = new Vector2(0, 25f * MetersToPixels);`

Whilst this works fine for rotating the ship, when i apply thrust, it just goes vertically up (I understand why this happens, I'm just not entirely sure how to make it move in the direction it's pointing).

# Answer
```
force.X = cos(shipBody.getAngle()));
force.Y = sin(shipBody.getAngle()));

```

Then you'll probably want to normalise that force and then multiply it by a magnitude to keep speed uniform
> 0 votes

---
Tags: java, box2d, libgdx, physics
---


# Question
Title: Do I need any knowledge of Objective C to port a game to iOS using Unity3D?
I have no experience with Objective-C and I know iOS simply as a user of iphone and ipad devices.

Now, I know that Unity3D can port my game to iOS without needing to know Objective C (that's what their docs say). But is it as simple as that? Click to compile, then use distribution profile and upload binaries to iTunes - as simple as that?

I need to know if should I start this process and publish my game this way. I am afraid that I may come across platform-dependent things (like when I code in cocoa-2dx using C++ and I come across hardware specific things).

If anyone has such experience, I would appreciate they share it with me.

# Answer
> 5 votes
Unity compiles your app into a bunch of assembly code with a thin Objective-C layer around it for OS calls and such. Assuming you're not doing any plugin work (e.g. needing to call OS level features for things) you can publish your game without any working knowledge of Objective C. Even if you do need OS level features, there's usually a plugin available that abstracts most of that stuff away for you.

However in my experience getting an the provisioning profile information set up and actually working is probably going to take you longer than learning Objective C anyway. It's usually a pain to get everything set up properly.

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


# Question
Title: Is it still possible to develop for gamecube?
I know the Nintendo gamecube is outdated, but it still one of my favorite systems. Is there any way to still develop games for it? What software would I need? What are the programming languages involved? Thanks guys!

# Answer
> 6 votes
Basically, if something has been created and was commonly used, it doesn't fade into oblivion. So searching google wont hurt.

You code using C++, C, GCC objective C with no Java. For the SDK you could go with the DevkitPPC.

> http://wiibrew.org/wiki/DevkitPPC

# Answer
> 5 votes
**Possible, yes, but at what cost?**

You'll require special hardware. There's a fairly comprehensive list found here. And there are compilers that will work for "popular languages" (most likely C++) (source).

There's also a How To guide that can be found here. The most interesting steps being:

> 4) Find a GameCube software development kit. This kit will allow your team to test the game out on the same specifications that every GameCube runs on. If your game runs inside of the kit, it will run on a GameCube.
>
> 5) Build the programming code in C++, which is used to build programs and games of all kinds because of its powerful backbone. Make sure that the game's world has pre-set rules and that every computer-controlled character has an artificial intelligence that feels realistic.

And of course, the "Things you'll need":

> **Things You'll Need**
>
> * Computer code programmers
> * 3D model creators
> * Audio technicians

This is likely a task that will be fraught with difficulty for very little payoff. Good luck.

---
Tags: nintendo
---


# Question
Title: Colors for villains, good guys and neutrals
I am looking for 4-6 color schemes for three factions, good, evil and neutral (in a space strategy if that matters). I'd like the player to choose which side they want to play and each side will have an optional ally. Each team can have one or two colors (major/minor), if that makes the problem easier.

EDIT: I know that color perception can be subjective, context sensitive and influenced by culture. I am looking for a scheme that majority of players would see as a traditional fight between Good and Evil (Blue and Red comes to mind when having only two colours, two factions).

---

Based on this article about movie faction colour I'd pick:

* Good: Blue (player) + Gold (ally)
* Neutral: White (player) + Grey (ally)
* Evil: Red (player) + Black (ally)

But something doesn't feel right about the scheme. Maybe it's the absence of color and using three shades of gray. Also it will be impossible to create gray and black "lights", "aura" and similar effects.

# Answer
> 7 votes
You can do just like the Firefly Studios have done in their Stronghold series. In the bottom right corner of the picture you can see six colors, that can be easily distinquished. As a player, I do not mind remembering who is my enemy and you can always give the player(s) a chance to assign colors to the teams.

One thing I have to note, is that in the first edition of the Stronghold, The player would always play using the blue colors this his enemies were brown, yellow, red and black. The sequel to the game, Stronghold Crusader had the colors flipped, the player would always use the red color for his/hers units which felt awkward having to switch from one color to other. It took me a few hours to get used to the changes...

You could create trimms for the other players that are allied to the player. Like, if the player is blue his allies will be blue with a gold trimm around his armor/whatever.

You can add a skull next to the evil players, shield next to allies or anything else you might feel that would correspond to the game.

# Answer
> 4 votes
After a lot of thought and inspired by the other answers, I came up with a schema of **6 two color combinations**. I realized that using just one color won't be enough, because I will have to repeat at least one of them, making either good a shade of evil or vice versa (which sounds pretty zen). I've also asked a web designer to help me pick and name the colors. I searched for these color among video games or movie heroes and villains. I've also went through comic book superhereos, anime characters and AD&D famous characters.

The six combinations are from top left:

* Bloodlust, Poison
* Neutrality and the other color I don't know (labour, soil, or something like that)
* Sky, Life

I've added the aura effect. Also the image has transparent background, if you are interested to see it on different color backgrounds.

Also @Sean Middleditch has a good point with shapes.

Just FYI, the colors were simulated for people with deuteranopia, protanopia and tritanopia (three color blidness variants) and they still look recognizable from each other, thanks to the color combinations. But I'd be very much interested how colorblind people classify those colors.

# Answer
> 3 votes
Shades of grey are generally not a good idea to tell players apart, because due to shading, white, grey and black can easily blend into each other.

When two factions form a team, it would be a good idea to give them colors which are close to each other in color spectrum but still distinct colors. I would do it like this:

* Good: Blue and Teal
* Neutral: Green and Yellow
* Evil: Red and Purple

Another option would be to represent the primary faction with a saturated shade and the secondary faction with a more pale shade:

* Good: Dark Blue and Light Blue
* Neutral: Dark Green and Mint Green
* Evil: Red and Pink

But note that the distinction of "good" colors and "evil" colors is not a very strong concept. Color psychology in general is heavily dependent on context and doesn't span cultural borders very well. To give an example: White in western culture stands for purity and cleanness. White in eastern cultures is the color of death and mourning.

# Answer
> 3 votes
I was originally passing on this question, as I feel there are far more important qualities to color choice beyond traditional moral delineations in mainstream American media, such as cultural meanings, historical meanings, theme and "look and feel" of the fiction, color blindness, usability, and more. However, if what is truly desired is a "common" perception of good, evil, and neutrality, then:

## Hue

Every hue has positive associations, but blue and green are almost universally positive, being the colors of a clear sky and plant life. Any habitable land on a temperate day will flourish with blues and greens.

Red has significant negative correlations that transcend culture, largely due to the color of human blood. While doctors and healthcare are often associated with red, so are wounds and recent deaths which can be more universal and pervasive.

Yellow and Orange are unusual colors with multiple positive and negative assocations, especially the association with fire, which can be vital to survival and deadly when uncontrolled. This is why there is often a "neutral" valuation with such colors.

## Saturation

Lighter and brighter colors are often associated with "good". Bright light is the reason for this, as all colors are lighter and brighter on a clear day. Note that "white" is not necessarily associated with daytime, merely with the absence of night, which is one reason why "white" can have very different associations depending on culture.

Conversely, darker and more desaturated colors are associated with "bad". Darkness is the clear association here, as darkness conveys the unknown and unknowable. For the same reason one is much more likely to be scared of the dark than to be scared of the clear daytime, so are darker or greyer colors more likely to evoke negative associations. Black of course is the color of complete darkness, the elimination of the primary sense our species uses, resulting in a color easily associated with negativity, fear, death, and more.

## Conclusion regarding the question of "What is the most common representation in games?"

The most common associations would be one of a few alternatives.

* The classic "blue vs red", with some yellow, grey, or other color for "neutral". A common example of this is Star Wars.
* Green, Yellow, and Red, commonly associated with "Go" "Caution" and "Stop", or stoplights. This extends beyond pure gamer or sci-fi/fantasy culture to many drivers across the world (I'm unaware of any nation/culture that doesn't use this scheme for stoplights)
* Any colors of differing brightness and saturation. You could even use the same hue, as long as the bright and light color represented "Good", a darker and dimmer color was "Neutral", and even darker and greyer was "Bad"/"Evil".
* Combine the associations with hue and saturation with a bright blue and green as "Good", a neutral valued yellow and orange as "Neutral", and either a dark or desaturated red as "Evil"/"Bad", probably combined with "Black" to give you your desired 6 colors, though if you really wanted to stick to colors with actual hues, a dark or desaturated color of any hue would fit in well enough with the rest of the scheme. Yellow could also work, but would leave you short a common "neutral" color.

# Answer
> 1 votes
I like the suggestions from users Philipp and Mikolaj. Another variant came to my mind when I read that you have a neutral team, and that is using "forrest colors". So here is my suggestion:

# Answer
> 1 votes
If I recall my Starcraft to a decent degree...

The player was Red, neutral units were usually either yellow, or some gray, un-themed color, and the enemy's color might vary at times. (Blue confederates, Purple zerg). For the player, you may want to pick whatever color seems to most closely fit the theme of your game's units, then think about other colors for enemies as needed.

---
Tags: game-design, color
---


# Question
Title: Character progression through leveling, skills or items?
I'm working on a design for an RPG game, and I'm having some doubts about the skill and level system. I'm going for a more casual, explorative gaming experience and so thought about lowering the game complexity by simplifying character progression. But I'm having trouble deciding between the following:

* Progression through leveling, no complex skill progression, leveling increases base stats.
* Progression through skills, no leveling or base stat changes, skills progress through usage.
* Progression through items, more focus on stat-changing items, items confer skills, no leveling.

However, I'm uncertain what the effects on gameplay might be in the end. So, my question is this:

**What would be the effects of choosing one of the above alternatives over the others?** (Particularly with regards to the style and feel of the gameplay)

My take on it is that the first sacrifices more frequent rewards and customization in favor of a simpler gameplay; the second sacrifices explicit customization and player control in favor of more frequent rewards and a somewhat simpler gameplay; while the third sacrifices inventory simplicity and a player metric in favor of player control, customization and progression simplicity.

Addendum: I'm not really limiting myself to the above three, they are just the ones I liked most and am primarily interested in.

# Answer
The question is a little abstract so I'm going to make a ton of assumptions here. Holler if any of them are way off of what you are expecting.

Leveling: Normally 'leveling' implies an xp scheme, and xp is granted for doing stuff the game designer wants the player to be doing (fighting monster of the appropriate difficult, completing quests, etc). Normally this is tuned to make the players advancement a function of time. This also allows players of all skill levels to progress similarly through the game. Arbitraty XP + leveling schemes give the greatest flexibility to the designer.

Skills: This scheme results in a positive reinforcement loop on skills, encouraging the player for doing the same thing over and over. This often leads to highly specialized and potentially unique characters, often with the player having a high feeling investment in the character. The downsides are the repetitiveness and that the player might not be able to transition to using/exploring other skills after significant investment in their initial skills.

Items: I can think of 3 ways items are granted these days. (1) Random drop (diablo) - results in the psychological properties of random reward schedules, but can result in frustration due to the randomness. (2) Boss drop/reward (WoW, plants vs zombies) - progression based reward scheme, results in major feeling of accomplishment, and also elitism (both good and bad features), though can have high falloff when the difficulty of the accomplishment is too high. (3) Based on currency (LoL, final fantasy) - this basically turns make the currency a form of XP that's transformed into power thematically via the items, makes it basically like 'leveling' described above.

Many games mix and match progression schemes (along with things like 'player skill', 'distance through the gameworld/story' and others) with the overall goal of keeping the player engaged and having things to look forward to.
> 3 votes

# Answer
You might think about a leveling / XP / Skills system similar to the old Quest for Glory games. At the beginning of the game you choose your character class and are given a pool of points to distribute. You can spend extra points to get skills that your character class would not normally have (giving a mage lock picking ability, or a fighter the ability to cast spells), but those abilities will always be less than those of the class which naturally have the skill (this is controlled in two ways - a fighter with magic has limited spells they can use, a mage with lock picking can only use a basic lockpick, whereas a thief can use a full toolkit which can open things another character wouldn't be able to).

Beyond this initial character creation process, most of the progression happens in the background. You can check your stat sheet to see your progress, but there is no "You've gone up a level" moment. Th skills are leveled by using them - throw rocks to increase throwing, block attacks to increase blocking, etc. Naturally, playing the game you will do these things and your skill will increase, but the stat sheet is never front and center or the be all and end all.

In my opinion, this approach tends to let the player focus more on the story and the actions of the game, rather than just focusing on leveling up. It lends itself to a more narrative approach.
> 3 votes

---
Tags: game-design, game-mechanics, rpg, progression
---


# Question
Title: How many testers should I get for my game?
I made a game for my bachelor final project. How many testers should I get to play-test my game? Is there any theory about that?

Would be really helpful if you can give any citation or source, since most likely my examiner will ask about that.

Thanks!

# Answer
> 6 votes
Get as many as you can reasonably manage. The more prepared and organized you are for testers, the more you'll be able to manage. If you have an automated system set up for collecting data and deploying your game for testing, you'll be able to manage more testers than if you were attempting to manage them manually.

It's also important to get the correct *variety* of play testers. You want play testers who are part of your target audience. You'll likely want your testers to be people who are not connected to you. They're more likely to give you an honest opinion.

Read this question and answers to ensure you're getting the most from your testers. There's also some good information about getting play testers and tips to teach your play testers how to test in this question.

# Answer
> 1 votes
Calculate how much testing will have to be done (as time, say you come up with a figure of 200 hours), then figure out how much time a single tester would spend on the task, and you have a figure for the number of testers you need.
Of course that should take into account retesting bugs they report, duplication (especially with volunteers testing games), people not actually doing the work they sign up for (especially with volunteers testing games, many just want to play something new and shiny before anyone else, and get a free copy at release date as a reward).
There's no magic number, depending on the size and complexity of your system, the number could be anywhere from two or three people (you do want some duplication of effort, to cut chances that someone misses something) working for a few hours over a weekend to dozens of of people working full time for months.
And with consumer products there's the added factor of disparate hardware/software combinations it will run on. It wouldn't do to test a graphics heavy game for example on only 2 computers, both with the exact same videocard, operating system, and drivers.
It will need to be tested on a broad range of hardware/software combinations to determine if it works properly on all of them (or at the very least to be able to mention in your documentation what the hardware/software requirements are to run it).
All of this is true for both games and any other system (and not just for software either).

---
Tags: testing, playtesting
---


title: Why does Mojang write Minecraft in Java

text:
# Question
Title: Why does Mojang write Minecraft in Java
Is there any specific reason why Java was the right choice for Minecraft?

# Answer
I saw a video from GDC 2012 where Markus "Notch" Persson said that he used Java because it's what he felt most productive in, at least at the time. It was only a passing comment though and note that this video is post-Minecraft, so his reasoning may not have been the same when he started Minecraft.

Source: "Back to the Garage: The Return of Indie Development" from about 14:45 in answer to the question "What Tools or Technology Would You Recommend?"
> 11 votes

# Answer
A lot of people hate on Java, but honestly, modern Java is quite good. I mean, sure javac will never be as fast as a C/C++ compiler but if you take an in-depth look on how your Java code gets compiled into what eventually gets read by the JVM, you'll see why it's "slower."

Regardless, Java is a powerful and straight-forward language and I could speculate that he chose it both for the fact that he was comfortable with it and that he recognized that Java has platform-independence. That is, you can write your code (excluding native libraries you may be using) and compile it on that machine and it should be able to run on machines with different architecture, so long as they have the required JDK/JRE installed. And the way that Java handles networking-related tasks makes online(ish) games significantly easier to deal with. It also doesn't require you to explicitly handle all of your memory all of the time, something I find nice. Obviously, some people dislike that and, in all honesty, handling your memory 100% on your own is the "correct" way of doing it, but who does things the correct way these days? We have fast computers, let the garbage collector clean up our mess so we can focus on making fun games instead of the best way to handle dereferenced variables.

Here's some more thoughts, I like the second comment quoting John Carmack: https://stackoverflow.com/questions/1034458/why-arent-video-games-written-in-java
> 4 votes

# Answer
That is a question for the "What If Machine" from Futurama unless they officialy say it somewhere you can never tell. From what I would say it might have been chosen due to the fact that Java is cross platform and it is very easy to install it on Windows, Mac or Linux.

The second reason; the reason I would choose, is the fact that he must have had previous experience with Java. He said that he had worked for king.com. Here is the possible explenation. So from what I understand, he simply dislikes C++.

> https://mojang.com/notch/
>
> Hello
>
> My name is Markus Persson, and I'm a programmer. You can call me "Notch". If you want to, you can email me at notch@mojang.com. Be warned that my spam filter eats far too many real emails, though. What I Do
>
> I currently run my own company called Mojang Specifications, where I'm currently developing a game called Minecraft.
>
> I used to work for Jalbum as a programmer. Or developer. Or code guru. We got to pick our own titles. :D
>
> **\> Before that, I worked for King.com as a game programmer for 4.5 years. I wrote games like Funny Farm, Luxor, and Carnival Shootout. I mostly did actionscript programming there, but also some java for the game verification code. Recently, I've done some work in C++. It's a powerful language and fun, but the retarded compilation system makes me cry a bit.**
>
> I was one of the founders of a unique mmorpg called Wurm Online. I'm no longer active there. I also make music under the name Markus Alexei. It's electronica, and releases are very far apart.
> 1 votes

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


title: XNA Using velocity

text:
# Question
Title: XNA Using velocity
Previously when making games I have just been using a Vector2 as the sprites position and altering that for movement, i.e.:

```
if(right key pressed)
   Position.X += movementspeed * gametime...;

```

However I now have the need to use a velocity vector for movement. So far what i'm doing is:

```
if(right key pressed)
   Velocity.X = movementspeed * gametime...;
...
Position += Velocity;
Velocity = Vector2.Zero; // Set velocity to 0

```

Is this how Velocity is implemented? I.e. setting it to a zero vector after each call of update?

Many thanks

Edit: When I stop pressing the key the sprite must stop moving, hence setting the velocity to zero.

# Answer
> 4 votes
No, velocity is independent from elapsed time, so:

```
if(right key pressed)
    Velocity.X = movementspeed;
else
    Velocity.X = 0;
...
Position += Velocity * deltaTime; // elapsed from last frame

```

# Answer
> 0 votes
So first off: I don't know what kind of game you're making. If it's a top-down RPG, or anything where movement isn't really central to the mechanics, this approach is fine. If it's a Mario-like platformer, you may want to take the indirection one step further.

Try playing a Mario clone somewhere, and you'll notice he works up to full speed, and then takes a few frames to slow down when you let go of Right. This is accomplished through *acceleration*. Here's the pseudocode.

```
Update():
  if (right key is pressed):
    Acceleration = ACCELERATION_CONSTANT
  else if (Velocity != 0):
    // apply a braking force that will bring him back to 0. This should be in the
    // opposite direction he's travelling, but not dependent on the speed he's travelling.
    Acceleration = SMALL_BRAKING_CONSTANT * Vector2.Unit(-Velocity)
  Velocity += Acceleration * time
  Velocity = min(Velocity, VelocityMax) // prevent Mario from going too fast
  // at some point, you might have other influencers on the velocity, like collision
  //detection. In basic games that's often done just by directly correcting position.
  Position += Velocity
  Velocity = 0

```

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


# Question
Title: Is there a game not using meshes for models?
Traditionally, models consist of lots of vertices connected by triangles. That forces the use of a high amount of vertices for detailed organic shapes or makes models kind of blocky. Even though polygon models can be smoothed by subdivision algorithms, this slow, not that exact or still needs a lot of vertices.

Instead, models could be represented by 3 dimensional splines, bezier patches, nurbs or something similar. This way, we would gain perfectly detailed models instead of blocky one with much less vertices. I am not an expert but I assume that a spline could be even rendered faster than its polygon representation. To make the such mathematically perfect shapes more detailed, we could use displacement mapping.

The only big challenge I can see is projecting those splines in the correct perspective. We can simply multiply all vertices with a projection matrix since they are not connected by straight lines. Instead the parameters of a curve must be modified to fit another perspective. I am not sure if there are mathematical straight forward ways to do this.

Are there games using the latter approach?

# Answer
You're looking at points on a continuum as if they're alternatives - Consider resolving a NURB to screen resolution, i.e. each pixel ties to an evaluation of the NURB for that point - the end result is that you're moving from a set of continuous functions to a discrete representation produced by evaluating those functions at *specific* points.

In the most general case, the only way to truly use NURBS and other continuous representations as the *only* graphical elements would be to return to the old X,Y driven analog monitors, and off the top of my head, I think transparency would be a complete beast at that point. Now, this is pretty much the way ray tracing works minus the rendering to a monitor, but remember that ray tracing is certainly not performance oriented, and at the end of the ray tracer, it still comes down to dealing with individual pixels being rendered in an image plane of some defined size.

It's not the projection of the spline or the NURB control points that's the rub, it's the tesselation/rasterization of the surface, i.e. the movement from a continuous to a discrete space.

What you can do is load up on graphics cards, dedicate a few as compute engines processing the NURBS, splines, and other such functionally defined surfaces into extremely high resolution triangles, and then feed the resultant triangles into the cards actually doing the rendering. Technically, at a high enough resolution you're pretty much indistinguishable from volumetric rendering from the perspective of the cards doing the rendering.

One other thing to consider is that evaluation of complex parametric surfaces can be expensive (or really cheap which is what makes sphere's so lovable) and you certainly don't want to pay the butchers bill for repeatedly evaluating a static NURB on every frame - but then the question comes as to where you will store the discrete data and then you're under memory pressure to identify the flat bits to drop the storage bill

So, a better way of looking at it would be to say that, given a world where the basis definition of a shape comes from continuous surfaces, where and when should the discrete representation of that shape be generated - Ray tracers say not until the very end of the pipeline, most interactive applications say as soon as possible and please don't fiddle with it after that :-)
> 4 votes

# Answer
Take a look at raytracing-based graphic engines.

Raytracing theoretically allows any geometrical shape as long as it is possible to calculate where it intersects a line. That's why demos of raytracing engines like spheres so much - perfect spheres are the bane of polygon-based rendering because they can only be approximated. But they are trivial to do perfectly for raytracing-based renderers. On the other hand, raytracing engines can also handle polygons pretty well when needed.

The downside: Current graphic hardware isn't designed for raytracing. They need to be calculated solely on the CPU. This makes high-quality raytracing too slow for most real-time applications. But the current advances in GPGPU technology (performing arbitrary calculations on the video card) are gradually leveling the playing field in this regard.
> 2 votes

# Answer
The Ecstatica series used a combination of dynamic 3D characters superimposed over pre-rendered backgrounds. The dynamic elements (and most of the backgrounds) are comprised of ellipsoids.

While the effect looks funny today it's was running on mid 90s PC hardware without any 3D acceleration. At the time I thought the characters (video) were very well animated compared to other games of the era (video).

I'm not sure how it was implemented but the style has always struck me as unique.
> 1 votes

# Answer
For instance Outcast

There is something called the voxel technology, it uses point cloud data for rendering.

You could read more about it here:

> Is Unlimited Detail real?

No meshes are used here, just points. But as AttackingHobo noted:

* The environment is static. No dynamic lights, animations, or shaders.
* All objects are data heavy both in memory and in storage.
* The amount of unique objects is limited by the amount of memory and storage that the user has.
* Character animation would either have to be standard polygon, use some kind of sparse-voxel character animation technique(computationally heavy), or load a different model for each frame of animation.

So it can not be used with anything that is meant to be dynamic.
> 0 votes

---
Tags: 3d, models, mesh, splines
---


# Question
Title: OpenGL ES 2.0: Texture does not appear to be correct
Here are my shaders...

```
 GLbyte vShaderStr[] = "attribute vec4 vPosition;   \n"
 "attribute vec2 texPosition; \n"
 "attribute vec4 inColor;   \n"
 "varying vec4 fragColor;   \n"
 "varying vec2 v_texCoord;     \n"
 "void main()                 \n"
 "{                           \n"
 "   gl_Position = vPosition; \n"
 "   fragColor = inColor; \n"
 "   v_texCoord = texPosition; \n"
 "}                           \n";

GLbyte fShaderStr[] =
  "precision mediump float;                            \n"
  "varying vec2 v_texCoord;                            \n"
  "uniform sampler2D s_texture;                        \n"
  "void main()                                         \n"
  "{                                                   \n"
  "  gl_FragColor = texture2D( s_texture, v_texCoord );\n"
  "}                                                   \n";

```

And here is my code...

```
GLfloat gObj[18] = {
  0.5f, 0.5f, 0.0f,
  -0.5f, -0.5f, 0.0f,
  0.5f, -0.5f, 0.0f,
  0.5f, 0.5f, 0.0f,
  -0.5f, 0.5f, 0.0f,
  -0.5f, -0.5f, 0.0f
}
...
GLuint textureId;

GLubyte bytePix[4 * 3] ={
        255, 0, 0,
        0, 255, 0,
        0,0, 255,
        255,255,0
};
GLfloat texC[] = {
            0.0f, 0.0f,
            0.0f, 1.0f,
            1.0f, 1.0f,
            1.0f, 0.0f
    };
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(1, &textureId);
glBindTexture(GL_TEXTURE_2D, textureId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_UNSIGNED_BYTE, bytePix);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, gObj);
glVertexAttribPointer(textCoordLoc, 2, GL_FLOAT, GL_FALSE, 0, texC);

glUniform1i(sampler, 0 );
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(textCoordLoc);
glDrawArrays(GL_TRIANGLES, 0, 6);

```

But when I run the app I see the following...

This seems wrong, how can I make it so each quadrant of the square is the color in the texture. Of course I could always be misunderstanding textures in general.

# Answer
> 2 votes
You have six vertices (correctly) but only four texture coordinate pairs, so the last two are undefined. You must specify matching texture coordinates for each vertex, including the repeated ones.

---
Tags: opengl-es2
---


title: Distance between two objects?

text:
# Question
Title: Distance between two objects?
We are trying to determine the distance (a scalar, double) between two objects' surfaces in Bullet. We are new to the Bullet engine, and we've been looking into the demo projects, but couldn't find any good examples.

The closest we have come to implementing this is using the following:

```
btManifoldPoint& pt = contactManifold->getContactPoint(j);
double dist = pt.getDistance();

```

But where do we get the contactManifold object? (We're not even sure this is the right approach.)

We want to calculate distance when a key is pressed, so this is done in the specialKeyboard() function, a function in the Bullet demo framework.

Can anyone provide us with a clear, simple example?

# Answer
Bullet's btCollisionWorld has member functions for ray casts and sweep tests:

btCollisionWorld::rayTest

btCollisionWorld::convexSweepTest

Those should get you started, they are used in bullet's demos.
> 2 votes

# Answer
If you want it to only work on collision:

http://www.bulletphysics.org/mediawiki-1.5.8/index.php/Collision\_Callbacks\_and\_Triggers

Otherwise I think you will need to use raytests etc like Maik says.
> 0 votes

---
Tags: bullet-physics
---


# Question
Title: GLSL Light (Attenuation, Color and intensity) formula
I'm implementing point lights in my Voxel engine, and I'm really struggling to get a good flow of light, from 100% near the light source to 0% at the light radius.

I have 5 arguments for the function:

1. Light color (Vec3)
2. Light intensity (distance from the light till the distance where falloff is 100%)
3. Distance from the light to the fragment
4. The angle from the fragment normal to the light
5. The position of the light

Can anyone push me in the right direction to create a function for the calculating of the fragment color?

Image of one of my experiments:

Edit (current code requested by Byte) **Note that this is just some experiment code from my side. I got the float att from a website, and it kinds works, but far from perfect.**:

```
void main()
{
// Light color
vec3 torchColor = vec3(1.0f, 1.0f, 1.0f);

float lightAdd = 0.0f;
for (int i=0; i<5; i++) {
    vec3 pos = lights[i];
    if (pos.x == 0.0f) continue;

    float dist = distance(vertex_pos, pos);
    if (dist < 9) {
        float att=1.0/(1.0+0.1*dist+0.01*dist*dist);
        vec3 surf2light = normalize(pos - vertex_pos);
        vec3 norm = normalize(normal);
        float dcont=max(0.0,dot(norm,surf2light));
        lightAdd += att*(dcont+0.4);
    }
}

vec3 textureColor = texture2D(texture, texture_coordinate).rgb;
vec3 torch_output = lightAdd * torchColor;

vec3 final_color = ((0.1+torch_output) * textureColor);

gl_FragColor = vec4(final_color, 1.0f);
}

```

# Answer
The attenuation function you've got,

```
att = 1.0 / (1.0 + 0.1*dist + 0.01*dist*dist)

```

is a fairly common one in computer graphics - or, more generally, `1.0 / (1.0 + a*dist + b*dist*dist))` for some tweakable parameters `a` and `b`. To understand how this curve works it's helpful to play with the parameters interactively. This curve is nice because it approaches the physically-correct inverse square law at large distances, but it doesn't shoot up to infinity at short distances. In fact, with `a = 0` it's a pretty good model of a spherical area light.

However, one disadvantage of it is that the light never quite goes to zero at any finite distance. For practical purposes in realtime CG we generally need to cut lights off at a finite distance, as you're doing with the `if (dist < 9)` clause. However, the radius of 9 is too short - with your settings in the attenuation function, the light doesn't get close to zero until dist is around 100.

You can calculate the radius of the light from the `b` parameter in the attenuation function (since the quadratic term dominates at large distances). Let's say you want to cut the light off when the attenuation reaches some value `minLight`, like 0.01. Then set

```
radius = sqrt(1.0 / (b * minLight))

```

That gives a radius of 100 for `b = 0.01` and `minLight = 0.01`. Alternatively, you can set the radius and calculate `b` to match:

```
b = 1.0 / (radius*radius * minLight)

```

For `radius = 9` and `minLight = 0.01`, that gives `b = 1.23`. You can set it up either way, but the key is to make the radius and the attenuation function match so that you don't cut the light off until the attenuation function is already very low, so you won't see a sharp edge.

---

All that said, there are alternative attenuation functions you can use. Another fairly common one is:

```
att = clamp(1.0 - dist/radius, 0.0, 1.0); att *= att

```

or the slightly fancier:

```
att = clamp(1.0 - dist*dist/(radius*radius), 0.0, 1.0); att *= att

```

Play with the parameters for those ones too. These curves have the advantage of going *exactly* to zero at the given radius, while still looking kind of like the natural inverse square law.
> 45 votes

---
Tags: opengl, glsl, lwjgl, lighting, pixel
---


# Question
Title: How do I implement a programming system in my game that is both accessible, powerful, and fast to code in?
I'm currently working on a space-based sandbox game which will heavily feature the ability to custom program your systems. I want to implement this in a way that is both

1. accessible,
2. powerful (bare minimum would be turing-completeness)
3. fast to code in.

Text-based languages generally only satisfy the latter two requirements, and while it's not to difficult to design a visual language which satisfies the first two, visual languages are a pain to program in due to requiring extensive mouse use. While there are some very accessible text-based languages, I want complete non-programmers to be able to ease themselves into programming.

# Answer
Really, the only way to have all the features is to implement multiple interfaces. Accessible and powerful are often two ends of a spectrum. The easiest way to do this is to implement a powerful system, that has an additional interface to allow beginners to interact with the system in a intuitive way.

Allowing for a system that allows beginners to program visually, perhaps something similar to the Lego Mindstorms programming tools:

Where there are drag/drop components. The components have inputs and outputs. Components can be simple things like `AND`, or `OR` gates, or more complex like a test for nearby enemies.

**Ideally the visual representation should be compiling a written language script in the background.** This offers a powerful tool for learning the language too. If a beginner can "write" their program visually, then read the code it produces they're far more likely to understand it and be able to modify the code produced. Eventually being able to write more powerful code than the visual tools alone allow. This fulfills the requirement of easing users into programming.

The backbone of the system, of course, is a written language. The visual tools are just to give users a *fast* way to program something simple, and allow for beginners to get started.

The written language allows for advanced users to do advanced things. And you can even allow users to create their own components, by making custom scripts. Then they can re-use components they made in a quick and easy interface for fast programming.

Good luck! Sounds like a fun project.
> 10 votes

# Answer
You might want to have a look at Google's blockly, they combine the visual elements with recognizable programming terms whilst maintaining a fairly decent level of accessibility.

You can have a look at the Maze demo for inspiration, many of my non-programmer friends were capable of getting most of the way through the puzzles using it, satisfying at least some of your criteria in effect.
> 5 votes

# Answer
I'm surprised this hasn't been mentioned before, but MIT's Scratch uses a block interface that is fast to code in. It allows users to create their own functions and can get surprisingly complex for a language that was built to teach kids how to code.

Stencyl is another example of block coding that does something more similar to what you're wanting. Coding with blocks like these is much more efficient and less time-consuming than visual programming interfaces like those used by Lego NXT. Stencyl allows users to code in either Actionscript or blocks.

I apologize for the lack of pictures, I don't have enough reputation to post images yet.
> 4 votes

# Answer
BPEL programming language has visual representation and many tools that work with it. It is a workflow language, not a programming language, but it is turing-complete. It is verbose, but it is easy to write for both programmers and business people and it's easily translatable from visual to textual form. I don't think it would make a good game-language, but it can serve as a source of inspiration. And given the amount of BPEL engines and tools, it should be possible to reuse some ideas and/or code.

BPEL-like language will not feel like programming, more like routing and connecting systems. So you can have a targeting system connected to a gun system with some logic in between.
> 2 votes

# Answer
Consider this approach:

1. Make sure, your script logic is expressable in simple rule-based mechanics. For example, you have "Trigger" that occur during gameplay associated with "Conditions" that must be fullfilled and then "Actions" are executed (shamelessly stolen from Starcraft 2 Editor).
2. Then provide an UI where you can drag'n'drop some predefined Actions/Conditions/Triggers around and so construct 90% of the use cases people usually want to do.
3. Now get some powerfull and popular scripting engine integrated like Lua, Python or C#
4. Finally write a couple of dozends of these Actions/Conditions/Triggers yourself in that language. Make sure the customizing user can copy-paste, edit and integrate these and new Actions within your drag'n'drop editor easily.
5. You probably want to be able to parametrize your Triggers, Conditions and Actions and so you need a couple of more primitives than these three, e.g. "GameObject", "Position", "Number" or "String". In the UI, you'll need some dialogs to assign these parameters, but that's still a lot less work than if you would have to be able to construct whole scripts via UI operations.

That's about the quickest way I can think of to get all the candy with no too much pain. You get the click'n'drag noobs as well as the vim-geeks on board. And if you keep the mechanics simple (e.g. Trigger -\> Condition -\> Action), then you don't have to spend the man-years in developing an UI for an powerfull and still easy-to-use graphical script editor.

Some examples to clearify what I mean:

* Trigger could be: "Game Framework Initialized", "Game loaded", "Unit created", "Unit destroyed", "Player damaged" and so on. Triggers usually have some parameters (e.g. Unit created gets the GameObject that has been created)
* Conditions are all standard boolean and basic arithmatic conditions (and/or/not/equals/greater...) plus some typical conditions you find in your game like "Unit is at full health" or "At least two Player are connected". Conditions usually have parameter which the user need to fill in (using UI)
* Actions are scripts that also may take some simple parameter. like "Pan the camera to XXX", "Kill Unit Y", "Game over", "Execute Trigger" and "Call Actions X, Y, Z... in a sequence"
> 1 votes

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


# Question
Title: Direct3D9 depth write without depth test
In OpenGL and Direct3D11 depth write is disabled if depth test is disabled. To enable depth write with out depth test in gl you must enable depth test with depth func always.

OpenGL

> Even if the depth buffer exists and the depth mask is non-zero, the depth buffer is not updated if the depth test is disabled. In order to unconditionally write to the depth buffer, the depth test should be enabled and set to GL\_ALWAYS (see glDepthFunc).

Direct3D11

> DepthEnable and StencilEnable enable (and disable) depth and stencil testing. Set DepthEnable to FALSE to disable depth testing and prevent writing to the depth buffer. Set StencilEnable to FALSE to disable stencil testing and prevent writing to the stencil buffer (when DepthEnable is FALSE and StencilEnable is TRUE, the depth test always passes in the stencil operation).

I can't find any documentation on this behavior for d3d9.

In Direct3D9 if D3DRS\_ZENABLE is set to D3DZB\_FALSE and D3DRS\_ZWRITEENABLE is set to TRUE is the depth buffer written to?

# Answer
> 3 votes
The closest answer I can find is from the DXSDK article "Depth Buffers (Direct3D 9)"; relevant portion extracted (with some parts about the color buffer and w-buffers removed):

> At the beginning of the test, the depth value in the depth buffer is set to the largest possible value for the scene. Each polygon in the scene is tested to see if it intersects with the current coordinate (x,y) on the rendering surface. If it does, the depth value at the current point is tested to see if it is smaller than the depth value stored in the depth buffer. If the depth of the polygon value is smaller, it is stored in the depth buffer...

This implies that depth buffer writing is part of the depth test itself, and that if the depth test is disabled then writing is therefore not done.

I could whip up a quick test program, but that of course would only be valid for my hardware and drivers. So given the apparent lack of a more definitive statement, I'd be inclined to play safe and assume that the behaviour is the same as D3D10/11 and OpenGL - after all, setting the depth comparison to always and writing to true is absolutely guaranteed to produce the desired result, whereas relying on it writing with the test disabled puts you in the clutches of how hardware vendors have decided to interpret this unfortunate vagueness.

# Answer
> 2 votes
Disclaimer: I've never used D3D9, only D3D10/11 and OpenGL.

See D3DRENDERSTATETYPE enum values and D3DCMPFUNC. Specifically, look at `D3DRS_ZFUNC` and try setting it to `D3DCMP_ALWAYS` with `D3DRS_ZENABLE` set to true, similar to what the GL docs indicate do. See also Depth Buffering State (Direct3D 9)

---
Tags: directx9, depth-buffer
---


title: Playing Time and value for purchases

text:
# Question
Title: Playing Time and value for purchases
I realize this is a nebulous question with no hard and fast answer. Just curious if there are any rules of thumb regarding playing times for a game/puzzle mobile app. Of course, value cannot be judged just by hours or minutes, but also by the quality of play and player skill... but let's leave that for another discussion.

Given a pick up and play freemium puzzle app (say each level takes an average of about a minute to play): What would be a reasonable and fair breakdown of free playing time vs. purchased playing time? My playing time estimates are based on a player with fairly good skills. The nature of the puzzles allow repeated additional re-playing to improve scores.

My current thinking is about 3 hours free play, with additional level packs priced at $1 for every additional 2 hours of play. I'd like my players to keep coming back for more, so I'd like to make sure the paid play is priced fairly (another nebulous term :).

# Answer
> 2 votes
Really the solution here is playtesting with follow up questionnaires. From each tester, ensure you collect:

* How long each level takes to complete
* How many levels they play
* How well they rate the game play
* How much they think a fair price is

Then just crunch the numbers and find averages. With this data you can get fair price per hour played (along with some other useful information). You could also weight the inputs based on how players rated the game, so people who liked it matter more to your statistics.

---
Tags: user-experience, free-to-play, pricing
---


title: Making a game "resize-safe"

text:
# Question
Title: Making a game "resize-safe"
It's one thing to get the graphics aligned perfectly, it's another to do this for every single resolution and not take too much time and/or make the code unreadable due to size. Games like Battlefield 3 and Minecraft seem to manage this. But what do they do to keep things from stretching or going off the screen? I don't know any algorithms to do this. I'd like some help on this topic. I've always programmed games that only handle a single resolution, so help would be appreciate.

# Answer
> 8 votes
The standard 3D pipeline is completely agnostic to screen resolution. For most projection matrix algorithms, including the "standard" ones in GL/D3D, an aspect ratio is part of the matrix allowing the projection to properly cope with different "shapes" of resolution. Just be sure to pass in the current resolution to the viewport setting routines calls and the current aspect ratio to the projection matrix routines and 3D is more or less automatically resolution-independent. The 3D projection/math all works in a normalized coordinate system where the upper-left corner of your screen is `(-1,-1)` and the bottom-right is `(+1,+1)`. This is then mapped to the viewport which is defined by the resolution of the area you're drawing to (typically the whole client window), which is basically just the hardware mapping those NDC ranges to pixel coordinates. So long as the viewport's aspect ratio matches the one in the projection matrix the image won't be stretched; otherwise the projection matrix might be mapping 3D coordinates to a differently-shaped rectangle than what's actually being draw to.

For the 2D elements, these are specified independently of the screen. E.g. a compass in the upper right is located with its upper-right corner at `(0.95, 0.05)` or some such, and its size can be specified to be a ratio of the vertical or horizontal resolution as most appropriate. The GUI might be specified in pixels which is mapped back to those ratios for GPU rendering (which then maps them back to pixels for final rasterization). Point is, just don't use fixed offsets for 2D elements, rather use relative coordinates and sizes to the corners/sides of the viewport and then the 2D elements will properly place themselves no matter what the resolution or aspect ratio is.

With very very little effort a game can Just Work(tm) at any resolution.

---
Tags: opengl, game-design, game-mechanics, window-management
---


title: Detect Car Wheel Position?

text:
# Question
Title: Detect Car Wheel Position?
I have an image:

I want to detect wheel empty position dynamically, is it possible?

If not possible please let me know, my work involves PHP/XML/Actionscript where actionscript get image url from xml generated by PHP,

User uploads car image through php admin panel, then passes url to actionscript through XML and actionscript should load image and let him choose the wheel and test on the car.

If you have another solution let me know?

# Answer
This is a problem from computer vision and the keywords your want to search are "pattern recognition". If you would like to make it fully automated, try OpenCV library. You basically want to define the arc and then look for it. I am quite sure the library can provide this functionality, but it doesn't have a port to Actionscript. You can look into the source codes, but the algorithms are not easy.

---

But personaly I'd let the users pick the wheel areas for me. Simply load the image, display it and let the user click on the picture twice to set the positions (and size) of wheels. A lot of image reconginiton/manipulation software does it this way to detect eyes in faces etc.
> 1 votes

---
Tags: actionscript-3
---


# Question
Title: What tools/software are used to make the environments/levels/maps in games?
This question has probably been answered before but I've not been able to find the answer, since I'm not able to frame the question with brevity.

So the whole question is :- The worlds/levels that you see in games like Crysis, Assassin's Creed, etc, what do the designers and developers use to create them? Do they use the tools present inside the engine (whether proprietary or in-house) or a separate software that exports these worlds as an importable object for the game engine to use to load models into it, etc?

I know this is a very general question but I have been curious regarding this for some time. I have used Unity in the past and it had a terrain toolkit that could be used to make the terrain, and I'm pretty sure it had completely to do with my lack of skill but I wasn't even close to making an environment that looked like the ones you see these days.

# Answer
Typically, in both triple-A and indie games, the developers will develop a set of tools for map and level for their game themselves. Take The Elder Scrolls V: Skyrim as an example, the creation kit is basically a level editor as with it you're able to edit the world of Skyrim. When the develops made the world and levels of Skyrim that would have used a slightly different version of the creation kit (since I think they altered it for public release).

A lot of games nowadays are developed using the Unreal Game Engine (both indie and triple-A), which has its own editor http://www.unrealengine.com/features/editor/

And since you mentioned Crysis. Crytek have developed their own engine and development kit called the CryENGINE, which they obviously used to build Crysis, you can read about it here: http://www.crytek.com/cryengine/cryengine3/overview
> 5 votes

# Answer
From my very limited experience as a game developer and somewhat bigger experience as gamer:

* If you write a game from scratch or you just use some graphics framework, you can adopt some existing level format and just implement a loader.
* You can implement your own level format and create an editor (levels, maps, campaigns, etc) that will suit all your needs. I believe this is the way of the big games. Sometimes they will release the editor along the game which is usually very welcome in the community. I spend many hours with Heroes of Might and Magic III map editor!
* Engines usually have some way of loading data from few level formats. I am using AndEgine that has its own format and also implements TMX map file format that can be very easily extended to a fully functional level format.
> 2 votes

---
Tags: game-design, level-design, world-editor
---


title: Need a Push in the right Direction

text:
# Question
Title: Need a Push in the right Direction
I know this been asked a millions of time.

First off my Dabbled in a few languages,like Java,C#,Android,Python and unity even though that's not really a language.My Programming is Level as at far below Amateur.

I been conflicted and a bit confused on what to choose.I know there is no Perfect Language.

So here is what i need help with "LONG TERM GOAL"

Web Game/Program 2d Graphics Simple/Pixel Interactive like a chat room/mmo Compatible with most Browsers

Now I need help what to really invest months to years into learning. Do i learn Unity,Flash or something Else. What do the expert suggest i go with.What ever it is I wanna learn with a full focus. I am all over the place and its leading me to be a Jack of Nothing.

I Also realize i am not making games for long time i start with hello world and simple chat room or make a simple tic-tac-toe game.I need step 1 rather then then starting at step 234.

Thank you for any Guidance Much Appreciated.

# Answer
I'm not a professional, but I started right where you are.

First off, it really doesn't matter what language you choose, just pick one and stick with it. If you've been programming for a while, and you understand the core concepts, you should be able to switch between languages relatively quickly.

Once you understand core concepts of programming, learn core of game design. Learn theory, and teach yourself the language dependent parts separately. The language independent parts are MUCH more important. Once you've created some basic games in the language you've chosen (I suggest doing ALL of these: http://lazyfoo.net/articles/article01/index.php) you should nail down what you want, pick a language, pick libraries/tools, and start learning all the quirks of those.

For example: You want to make a web game. If by that you mean a game that will be embedded in a web page, I'd say pick Java or Unity.

Most professional games are written in C/C++, but they are doing something VERY different that from what you want.

If that is indeed what you want long term, start learning that. Every language CAN do what you want, you just need to stick to one for a while.

In summary: 1. Pick a language and learn it. 2. Learn basic game architecture and how to apply it to your chosen language. 3. Make and finish games. \- This is important to do early on. Its encouraging. 4. Begin work on your project.

Hope this helps, Best, Peter
> 0 votes

---
Tags: 2d, browser-based-games, web
---


title: Simple Optimized Blur Shader

text:
# Question
Title: Simple Optimized Blur Shader
I have a vertex-fragment shader that use the Unity3D GrabPass functionality (it grabs the screen). And I apply my GrabPass to have a transparent effect.

```
GrabPass {
    "_GrabTex"
}

sampler2D   _GrabTex;

// float4 grabPassPos : TEXCOORD4 is used to apply the grabbed texture in
// the right place and is calculated in the vertex
half4 transparent = tex2Dproj(_GrabTex, UNITY_PROJ_COORD(IN.grabPassPos));
half4 baseColor = transparent;
return baseColor;

```

I am searching a simple way of blurring my grabbed texture. I don't know how to apply my blur because it's a tex2Dproj and I don't know where to apply it.
I am searching for a one pass optimized simple blur but I don't know if it's possible.
I know a bit about Gaussian and Box blur which seems to be the simplest but how can I apply them in a tex2Dproj ?

Thanks a lot !

# Answer
> 3 votes
I don't have pretty much any experience with Unity, so this might not be the most efficient way to do it (and my coordinate calculation might actually be wrong). But it should give you some idea:

All you have to do is evaluate the color at different pixels/coordinates and blend them together, probably doing so based on their actual brightness.

For a simple kernel like

```
0 1 0
1 2 1
0 1 0

```

This is quite trivial:

```
// First get the colors at all these positions.
// Note that the offsets (0.1f/0) might not be the perfect values for you.
// If you want to blur exactly 1 pixel distance you'd use "1 / screenwidth" or "1 / screenheight" here.
float2 centercoord = UNITY_PROJ_COORD(IN.grabPassPos);
half4 top = tex2Dproj(_GrabTex, centercoord + float2(0, -.01f));
half4 bottom = tex2Dproj(_GrabTex, centercoord + float2(0, .01f));
half4 left = tex2Dproj(_GrabTex, centercoord + float2(-.01f, 0));
half4 right = tex2Dproj(_GrabTex, centercoord + float2(.01f, 0));
half4 center = tex2Dproj(_GrabTex, centercoord);

// Now blend the colors together, using the weightings from the kernel (see above).
return (top + bottom + left + right + center + center) / 6.0f;

```

For more complex kernels you'd most likely want to use an array containing the kernel values and do everything in a loop.

---
Tags: opengl, unity, directx, shaders, glsl
---


title: How does Application.genuine work?

text:
# Question
Title: How does Application.genuine work?
In Unity, does anyone know exactly what is behind the scenes of Application.genuine?

More specifically, I would like to understand its exact process so I can understand:

1. If I can use it safely without "false negatives".
2. If it considers text (or other) assets stored in a Resources folder (e.g. my level config files).

Just for context, I want to say that my target platform is iOS.

# Answer
I assume it's just using a checksum over the binary to determine whether there have been any modifications. I don't think it would verify/check any external resources. Have you tried some black box testing with it?

To say for sure you'd have to look into the source code, which again might be something people with the source code license might not be allowed to reveal. You could use a disassembler to track the code, but that's probably quite a bit tedious to do.
> 2 votes

---
Tags: unity
---


title: Best way to keep track of game objects

text:
# Question
Title: Best way to keep track of game objects
I'm not exactly sure how I should ask this question, and so the title may be misleading - I am not asking if I should use a list or a stack or a vector or a queue - but how I should go about keeping track of said storage object.

For example, let's say I have some object that would represent the game itself, and the game used state objects to tell what state it was in(IE, playing, paused, titlescreen, gameover screen, etc etc):

```
class Game
{
    //Constructors and what not
    private:
    stack<States*> states;
};

```

And then each state would keep track of the objects that it contained.

```
class States
{
    //Constructors and whatnot
    private:
    list<Mob*> listOfMobs;
    list<Bullet*> listOfBullets;
};

```

Now, what if I have a Mob spawn new Mobs, or have a Mob fire a bullet? I definitely don't want to pass the State itself down to all Mobs - I'd have dozens(or more) of copies of the State wandering around, which does not seem very wise. In the same sense, passing down the list of Mobs or bullets does not seem like the best idea either. So, how should I handle this? I don't want to use global variables, and in the same way I wouldn't like to use a singleton pattern to keep track of it all - but I don't see very many other options. I might just be stuck thinking inside the proverbial box, though. How does everyone else handle tracking the objects in their game?

# Answer
Your question seems indeed a bit confusing. I assume you are asking about the problem, how some specific code piece (e.g. the function responsible for firing a bullet within the mob unit) should get to the information about "how to fire the bullet" and "what bullet type" and so on?

Here are some solutions:

**Just use globals and get over it ;)**

In gaming development (and also in many other code development areas outside of universities ;)), people are usually very pragmatic (some call this "old-fashioned" :)). You see global variables and "global manager" very often.

So for example if a unit needs to fire a bullet with some sparkles, its common to just write something like this (yes, even hardcoded values. But usually these are only ID's for the real values stored in some table etc..):

```
BulletManager::instance->FireBullet("biggun.bullet");
ParticleEffectManager::instance->SpawnParticle("smoke.xml");

```

That doesn't mean that game developer don't know about the risks or problems behind it and in many post-mortem meetings, the need for "less global stuff" is expressed by at least one of the coders ;).

Said that, there are a couple of other ways how to solve this kind of problem - academic and real-world ones:

**Pass the stuff to the constructor**

Just pass down relevant managers (or "states" as you call it) to the objects, usually via Constructor or as setter right after construction. (This is sometimes called "dependency injection", as the "tools get injected into the object"). Every object remembers the managers it needs to perform its work. Yes, you already said that this sounds weird and memory wastefull, but stop a second and think about the real impact. You have how many mobs? 1000? 5000 at maximum? Each mob stores 5 pointer is how much memory? Usually irrelevant. (If you scream "cache misses" now: Nobody said the pointer have to be stored together with the other objects properties. You should always consider grouping data in memory together that needs to be processed together. That is as true for Position vectors as it is for pointer to scenes.)

One common mistake with this approach is, to "pass things to create the tools".

Coder start to complain that their mob constructor now takes 20 arguments, because they need to pass 5 to create or parametrize the particle engine, 10 to forward to the physic engine to raycast, and another 5 to pass to their created Bullets. And for every tweak in one of the subsystems, they need to touch dozends of constructors and do hundrets of lines of boilerplate blabla...

Don't do this. Pass the *tools* instead. So for this example, your would send only 3 parameter: A particle spawner, a physic engine handler and a BulletFactory.

Usually, this design leads to a lot fewer global "manager" instances and a lot more "personalized factories" that can spawn particles for this particular unit (or even this particular use within the unit).

**Pass as arguments when calling the function**

If the storage of the pointer within each object is too much or you often need to use different contextes with the same object, then you might pass the relevant information to the function that does the work.

This approach is by far most often used for library functions.

**Know someone who knows it**

You can hide the complexity of how to get all the things you need in other classes like the base class or an single passed "context" class. I think this is some kind of compromise between the first answer (global statics) and the others.
> 6 votes

# Answer
What's wrong with just making it a global? Making a game is significantly more important and rewarding that adhering to academic purity. Just get the job done.

That said, another option is to store a pointer to the owning State in the game object. It's wasteful if you're just using it to avoid having a single global pointer but it can be a boon if you have multiple States and need to access the specific State owning that game object.

This way, for instance, the Mob can ensure it spawns a Bullet in the correct State in the event you have more than one active a time (there's various uses for this).
> 3 votes

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


# Question
Title: How to find the bottleneck in a typical OpenGL game?
I am working on a little game engine. All major features are implemented yet, despite game logic which I assume not to be such a computational effort. The framerate is at least around 40 FPS, most of the time above 60 FPS.

I would like to speed up my engine now. There are several performance heavy tasks, like physics simulation and collision detection where I use Bullet Physics for, geometry drawing and texturing, deferred lighting, post effects like SSAO. Later on maybe character animation and artificial intelligence may add up.

How to find the bottleneck in such a typical OpenGL game? I am not familiar with profilers, and I have no idea how to use them, especially with asynchronous code like Bullet Physics.

# Answer
Profiling (and adjusting code where necessary). There's different profiling software available (your compiler might provide built-in hooks for this or bring the tools like GCC and MSVC do) that won't require you to actually edit or modify your code just to take measurements.

The easiest - and most generic way to do it (which will require modifications of your codebase) - would be adding several measurements on your own, e.g. track how long it takes to render backgrounds, track how long it takes to render objects, track how long it takes to process shaders, etc.

For example, this page shows you some example screenshots on how this is presented when using the Unreal Engine 3. You don't need any fancy things for this, you don't even have to print it on screen (just log it somewhere).

One important thing to note: If you're running Windows, make sure you don't write anything to the console window; or at least try not to flush the output too often (e.g. by using `std::endl`). This can slow you down quite a bit compared to any real work being done.
> 1 votes

---
Tags: c++, opengl, 3d, performance, profiling
---


# Question
Title: How to avoid "Blob-Systems" in an entity component system?
Currently I am facing the following problem:

I am trying to write a pong clone by using an *entity component system* (ECS). I wrote the "framework" all by myself. So there is a class which manages the entities with all the components. Then there are the component classes themselves. And last there are my systems which just get all the entities which have components which the system needs.

So for example my movement system looks for all entities which have a position component and a movement component. The position component just holds the position and the movement component holds the speed.

But the actual problem is my collision system. This class is like a logical blob. I have so much special cases in this class.

For example: My paddles can collide with the borders. If this happens their speed is set to zero. My ball can as well collide with the borders. But in this case its speed is just mirrored at the normal of the border so it is reflected. To do this I gave the ball an extra physics component which just tells: "Hey, this thing does not stop, it reflects." So actually, the physics component has no real data. It is an empty class which is just there to tell the system if an object reflects or stops.

Then there comes this: I want to render some particles when the ball collides with the paddles or the borders. So I think the ball has to get another component which tells the collision system to create particle on collision.
Then I want to have power ups which can collide with the paddles but not with the borders. If that happens the power-ups have to disappear. So I would need much more cases and components (to tell the system that some entities can only collide with certain others, bot not with all even if some others are actually able to collide, furthermore the collision system had to apply the power-ups to the paddles, etc., etc., etc.).

I see that the entity component system is a good thing because it is flexible and you do not have problems with inheritance. But I am totally stuck currently.

*Am I thinking too complicated? How should I cope with this problem?*

Sure, I have to create systems which are actually responsible for "post-collision", so the collision system only tells "Yes, we have a collision in the last frame" and then there is a bunch of "post-collision" systems which all require different (combinations of) components and then change the components. For example there would be a movement post-collision system which stops things which have to stop when collision happens. Then a physics post-collision-system which reflects things, etc.

But this does not seem to be a proper solution to me either, because for example:

1. My movement post-collision system would need entities which have a position component, a movement component and collision component. Then it would set the speed of the entity to zero.
2. The physics post-collision system would need entities which have a position component, a movement component, a collision component and a physics component. Then it would reflect the speed vector.

The problem is obvious: Movement post-collision needs entities which are a subset of the entities in physics post-collision system. So two post-collision systems would operate on the same data, the effect being: Although an entity has a physics component, it speed would be zero after a collision.

How are these problems solved in general in an entity component system? Are those problems even usual or am I doing something wrong? If yes, what and how should it be done instead?

# Answer
> 12 votes
Yes, you're thinking too complicated.

It sounds like a lot of your problems could be solved with a **messaging system** and some additional attributes that allow you to specify some **filters**, and finally not worrying about being so strict with entities/components.

Messaging will help you with some aspects like triggering particles, powerups, and so on. For example, you could have a world object that subscribes to particle events and creates particles at the position described in the event.

Filters will help you a lot in collisions. Filters can define if an object collides with another, and what response it will have. You add some attributes to your physics component that defines what type of physics body it is, what other types of physics bodies it collides with and what the response should be. For example, a ball physics object collides with a paddle physics object and responds with reflection and particles.

Finally, don't be so strict about your implementation. If you can find a way to make it work, but it's not really EC system, do it. Like in my example above, the particles to not need to be managed by a system or part of the EC system at all. It's more important to finish the game than it is to strictly follow a method that's already pretty poorly defined.

# Answer
> 13 votes
You are over-complicating things. I would go so far as to say that even using component-based design is just overkill for such a simple game. Do things the way that makes your game quick and easy to develop. Components help with iteration in larger projects with a huge variety of behaviors and game object configurations but their benefit to such a simple well-defined game is more questionable. I did a talk last year about this: you can build fun little games in a few hours if you focus on *making a game* instead of *adhering to an architecture*. Inheritance breaks down when you have 100 or even 20 different types of objects but it works just fine if you only have a handful.

Assuming you want to keep using components for learning purposes, there's some obvious problems with your approach that stand out.

First, don't make your components so small. There's no reason to have fine-grained components like 'movement'. There is no generic movement in your game. You have paddles, whose movement is tightly tied to input or AI (and don't really use velocity, acceleration, restitution, etc.), and you have the ball, which has a well-defined movement algorithm. Just have a PaddleController component and a BouncingBall component or something along those lines. If/when you get a more complicated game then you can worry about having a more generic PhysicsBody component (which in 'real' engines is basically just a link between the game object and whatever internal API object is used by Havok/PhysX/Bullet/Box2D/etc.) that handles a wider variety of situations.

Even a 'position' component is questionable though certainly not uncommon. Physics engines typically have their own internal idea of where an object is, graphics might have an interpolated representation, and AI might have yet another representation of the same data in a different state. It can be advantageous to just give let each system manage its own idea of the transform in the system's own components and then ensure there's smooth communication between system. See the BitSquid blog post on event streams.

For custom physics engines remember that you are allowed to have data on your components. Maybe a generic Pong physics component has data indicating which axes it can move on (say, `vec2(0,1)` as a multiplier for paddles which can only move on the Y axis and `vec2(1,1)` for the ball indicating it can move however), a flag or float indicating bounciness (the ball would typically be at `1.0` and paddles at `0.0`), acceleration characteristics, velocity, and so on. Trying to split this up into a bazillion different micro-components for each piece of highly-related data is counter to what ECS were originally meant to do. Keep things that are used together in the same component where possible and only split them up when there is a large difference in how each game object uses that data. There's an argument to make that for Pong the physics between the ball and the paddles is different enough to be separate components, but for a larger game, there's little reason to try to make 20 components to do what works just fine in 1-3.

Remember, if/when your version of ECS gets in the way, do what you need to actually make your game and forget dogged adherence to a design pattern/architecture.

# Answer
> -1 votes
Edit: I posted this answer below back in 2013. Now, as I learned more about the "S" in an ECS, I came to the opposite conclusion. So treat my answer below as an "historical statement". ;)

---

In my opinion \*), your biggest problem with Components is this: Components are NOT here to *tell* anyone else what to do. Components are here to DO things. You don't have a component just to hold the memory of some thing and then have other components operate on this. You want components that DO stuff with the data they got.

If you see yourself testing for the presence of other components (and then call functions there), then this is a clear sign, that either one of two things are true:

* You actually want to invert the dependency: The other component should listen to events/messages/broadcasts/hooks/howeveryounamethem to execute their logic in response of your current component. The current component does not even have to know that there is an "other" component. This is most often the case, if you find yourself calling different components (even in different else/case blocks) with functionality that is not really connected to your current method. Think of all these `Invalidate()` or `SetDirty()` calls to other components.
* You may have too many components. If two components just can not live without each other and constantly need to retrieve data and call methods to each other, then just merge them. Obviously, the functionality they provide are so entangled, that its actually really only one thing.

By the way, these applies to all kinds of systems, not only Entity/Component systems, but also to classic inheritance with simple "GameObject"s or even library functions.

\*) Really only *mine*. Opinions heavily vary about *Whats Da Real Component Systemz* (TM)

---
Tags: architecture, component-based, entity-system
---


# Question
Title: How to get independent from GLEW dll file
I'm literally an absolute noob in GL. I just wrote my first GLEW piece of code yesterday:

```
#include <stdio.h>
#include <stdlib.h>
#include <GL/glew.h>
#include <GL/glfw.h>

int main(void)
{
    glfwInit();
    glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4);
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 3);
    glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwOpenWindow(640, 480, 8, 8, 8, 0, 24, 0, GLFW_WINDOW);

    glewInit();

    glfwSetWindowTitle("OpenGL Rules!");
    glfwEnable( GLFW_STICKY_KEYS );

    do{
    glfwSwapBuffers();
    }while( glfwGetKey( GLFW_KEY_ESC ) != GLFW_PRESS && glfwGetWindowParam( GLFW_OPENED ) );
}

```

This compiles just fine with (using mingw on win8 x64):

```
gcc opengl.c -lglfw -lglew32 -lopengl32

```

However, in order to run the output, I have to copy the glew32.dll to the same directory from which I'm running the program. Is there a way to get independent from the dll? Like, compiling once and using without having to carry the dll around?

# Answer
> 5 votes
You need to `#define GLEW_STATIC` before you #include the GLEW headers, then link to `glew32s` instead of `glew32` and you'll statically link to GLEW.

According to http://glew.sourceforge.net/install.html you can also directly use the glew.c and glew.h files in your own project, but I haven't tried that; the GLEW\_STATIC method works well enough.

---
Tags: opengl, mingw
---


title: Logic For Puzzle Game - How do I do it?

text:
# Question
Title: Logic For Puzzle Game - How do I do it?
**What is the game all about?**

It's a puzzle game. I am using AndEngine to build it on Android platform (currently). I have divided the game into various World, with each World containing various Levels.

**What is the Issue?**

The purpose of the game is to drag-and-drop the broken pieces into the "drop" area (a.k.a. holder) and form the circle. I've developed the basic 2 levels of the game. This is the third level. Where there are 3 pieces as different objects. I've to drop all 3 pieces into the drop. The issue is how do I know that all the broken pieces have filled the holder? I'm using AndEngine for the first time and have very little idea how this can be done. Tapping on any broken object would rotate it by 90 degrees. So there can be 4 possible solutions for each of them).

Also, the logic should hold true for any shape, any number of broken pieces, any number of holders.

Below is a picture of level 3. There are 3 pieces named 1, 2 and 3 at different positions. All the pieces must be placed inside the circle.

**Ideas that I've thought about**

We've thought to solve this using:

1. Area of the holder is filled -\> But how do I programmatically do that?
2. Take center coordinates of each broken piece and find the distance from the center of the circle. Verify this in all the 4 conditions (all 4 rotations by 90 degree each). -\> I'm trying to figure this out.
3. See if all the broken pieces are used in the holder area -\> What if there are more than one holder?

Any technical help or any references would be really great.

# Answer
> 1 votes
There are different approaches for this, especially considering there might be different solutions (like rotating the correct solutions).

If you're indeed looking into a rather limited amount of possible rotations and positions you'll just have to verify the given solution matches the expected result following a few rules:

* The order tiles are verified/considered must always be constant for the same puzzle.
* Tile coordinates are rounded to some extend (you'd probably want some snap-in system anyway).
* If there's no fixed offset (i.e. it shouldn't matter where the completed shape is), use the first tile's coordinates as offset.
* Each and every tile has a unique identifier (like a letter or string) unique to its combination of size and shape (same size and shape results in the same identifier).
* The whole solution given by the player is (behind the scenes) always rotated till the first tile isn't considered rotated at all.
* Now just compare all tiles and ensure they have the correct orientation and position.

For the last thing to check, the easiest way might be creating two strings, one based on your solution and one on the current state of the game:

* For each tile add the following to the string:
    + Tile identifier
    + Separator
    + Tile position
    + Separator
    + Tile rotation
    + Separator
* The result could be something like this: `A|0,0|0|B|3,1|0|B|1,3|1|C|2,2|3...`
* Now if the string generated based on the player's solution and your pregenerated solution match, the puzzle is solved.

As an alternative, you can of course compare the different values on their own using some loop and multiple comparisons or create one string with positions and one with rotations, etc.

# Answer
> 1 votes
Out of my gut feeling, I would go for your first idea: "Area of the holder is filled"

That's how I would approach it:

Get a tiled representation of your play area. Like 40x40 tiles or so. Every tile gets the "number of shapes occupying this".

You will need a routine that finds all tiles a current shape is touching, for example the easiest is probably "for each tile, test if tile center is inside shape".

Whenever you move or drop one of the shapes, run the routine to remove it from the current tiles before moving the shape. The re-run it again when the shape has been placed to increase the use counter.

You are finished, when all tiles in your target zone have exactly an count of 1.

If you want to forbid the player to overlap shapes at any time, you can use the very same routine to test for these overlaps.

If overlaps are OK for you (as long as the end-result doesn't overlap), you actually don't need to check any tile outside the holder area. This will probably considerably speedup the testing.

Keep the actual number of X/Y tiles some constant, so that you can easily change it. You might want to experiment with the size of the tiles later. They should be tiny enough to not give wrong results and big enough to be still performant and allow for some small inaccuracy.

The big advantage here is, that you can go nuts with your shapes. You can have any number of target zones and even can make overlapping target zones (where the end shapes need to overlap too etc..).

---
Tags: android, andengine, puzzle
---


# Question
Title: How to get max viewable X-Value in Viewport
How can I calculate or get the farthest X-Value of a Viewport during gameplay?

Say a model is moving in from the right-hand side (beyond Viewport) and starting from a certain X-Value it is visible on the viewport. I'd like get that certain X-Value.

But the more I zoom out (Z-Axis) the greater the farthest visible X gets (*Max X*). How could I approach this?

# Answer
> 1 votes
**What you probably want to use is the `BoundingFrustum` class** (MSDN).

A bounding frustum gives you a volume shaped like this:

A bounding frustum created with your projection matrix will contain the volume you are interested in. You can then use the various `Intersects` or `Contains` overloads to test against various shapes (`BoundingBox` and `BoundingSphere`) that you can use to approximate the volume of your 3D model for culling purposes.

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