# Question
Title: How do I create a curved line or filled circle or generally a circle using C++/SDL?
Hello I've been trying for ages to make a pixel circle using the putpixel function provided by SDL main website here is that function :

```
void putpixel(int x,int y , int color , SDL_Surface* surface)
{
    unsigned int *ptr = static_cast <unsigned int *> (surface->pixels);

    int offset = y * (surface->pitch/sizeof(unsigned int));

    ptr[offset + x] = color;
}

```

and my question is how do I curve a line or create an circle arc of pixels or any other curved shape then a rectangle or singular pixel or line.

for example here are some pictures

filled pixel circle below enter link description here

now my idea was too

change the x and y value of the pixel position using + and - to create the curves but in practice didn't provide the correct results

what my results are in this is to be able to create a circle that is made out of pixels only nothing else.

thank you for anyone who takes the time to read this question

thanks! :D

# Answer
> 1 votes
To draw a circle one pixel at at time, you can do something like this

```
int centrex=100,centrey=100;// centre of circle in pixel coords
int radius=50;

float two_pi=6.283f;

float angle_inc=1.0f/radius;
for(float angle=0.0f; angle<= two_pi;angle+=angle_inc){
    xpos=centrex+radius*cos(angle);
    ypos=centrey+radius*sin(angle);
    putpixel(x,pos,ypos,surface);

```

}

This method considers a circle like a bicycle wheel and draws a pixel at the end of each spoke. This is not the most efficient way to draw a circle using pixels (checkout the midpoint algorithm). But it will get you started.

# Answer
> 0 votes
For curves you can use Bezier Curve. The parametric equation is what you are looking for ;)

Using Bezier Curves, you can draw lines too, all you have to do is use the Linear Bezier Curve.

For circles, you can also use parametric equations, and a quick Google returned me this awesome website: Link!.

But one can also use something like Midpoint Circle for filled circles. See this question: https://stackoverflow.com/questions/1201200/fast-algorithm-for-drawing-filled-circles

# Answer
> 0 votes
Read up on Bresenham's algorithms. First here for a line drawing algorithm, and once you understand how that works here for the actual circle algorithm.

---
Tags: c++, pixel
---


title: Zelda like multiplayer combat

text:
# Question
Title: Zelda like multiplayer combat
I have in mind coding a multiplayer game with a similar combat to zelda's. Since i will use flash, i'm limited to use TCP. My question is, is this goal possible? It's not as fast-paced as some shooters, but i'm not sure if it's too much for tcp?

tl;dr: TCP for zelda-like multiplayer combat style?

# Answer
> 1 votes
Why don't you try it out in a simple test project? TCP is a data stream, to avoid clogging up the stream (the "packets" will sit there untill they are read) you should call the receive function untill there is no data left to read. If you can sent 1024 bytes packages every frame without to much delay, then you should be good.

note: I know packet/package is not the right terminology for TCP, but I couldn't think of the right way to describe it.

# Answer
> 0 votes
Look : http://playerio.com/

Instead of TCP or Socket, MongoDB,CouchDB, NoSQL or PlayerIO's BigDB's database solutions are better than that.

---
Tags: flash, multiplayer, actionscript-3, rpg
---


title: HTML5 Canvas Game Timer

text:
# Question
Title: HTML5 Canvas Game Timer
How to create good timer for HTML5 Canvas games? I am using RequestAnimationFrame( http://paulirish.com/2011/requestanimationframe-for-smart-animating/ )

But object's move too fast.

Something like my code is:

http://pastebin.com/bSHCTMmq

But if I press UP\_ARROW player don't move one pixel, but move 5, 8, or 10 or more or less pixels. How to do if I press UP\_ARROW player move 1 pixel?

Thanks for help.

# Answer
> 2 votes
The player is moving 1 pixel, but because you are constantly polling for input, you get the 'isdown' response every frame. So in the space of 1 second, you have moved 60 pixels, assuming frame rate holds and you held down the key for the whole second.

What you would need to do is only perform the movement code, *as soon* as the key was pressed, that way the player will need to release the key to be able to move again. Something like this should do the trick.

```
Player.prototype.init = function() {
    this.pressed = {};  // List of pressed keys
};

Player.prototype.update = function() {
    if ( !keyboard.up()) {
        delete this.pressed[ 'up'];  // No longer pressed, so remove
    }
    if ( keyboard.up() && !this.pressed[ 'up']) {
        this.pressed[ 'up'] = true; // Set to pressed so the event doesn't fire again
        this.y --;
    }
};

```

I suggest altering your input class so that it would be handled for you, but the code is pretty much identical.

# Answer
> 0 votes
The problem here is you're moving it according to the frame-rate and not frame-rate independent.

If you read this article you'll understand how to implement delta time steps. Now, with this in mind you'll have what you need to ACTUALLY move the player correctly. If you want the player to move 32 pixels per SECOND, you would do something like....

```
   if( keyboard.up() ) {
     this.y -= 32 * gameTime;
}

```

This will move the player 32 pixels every second, regardless of the frame-rate in the browser. This is ideal as you are now guaranteed 32 pixels on every browser, machine and configuration available. If you don't do this, you are subject to frame-rate fluctuation.

# Answer
> 0 votes
I made an answer on a related matter that might interest you :

How can I detect and compensate for system related lag?

( maybe i could copy-paste it here for reader convenience... )

---
Tags: javascript, html5, html-canvas, timer
---


# Question
Title: Which will be faster? Switching shaders or ignore that some cases don't need full code?
I have two types of 2d objects:

In first case (for about 70% of objects), I need that code in the shader:

```
float2 texCoord = input.TexCoord + textureCoord.xy

```

But in the second case I have to use:

```
float2 texCoord = fmod(input.TexCoord, texCoordM.xy - textureCoord.xy) + textureCoord.xy

```

I can use second code also for first case, but it will be a little slower (`fmod` is useless here, input.TexCoord will be always lower than `textureCoord.xy - textureCoord.xy` for sure).

**My question is, which way will be faster:**

1. Making two independent shaders for both types of rectangles, group rectangles by types and switch shaders during rendering.
2. Make one shader and use some if statement.
3. Make one shader and ignore that sometimes (70% of cases) I don't need to use `fmod`.

# Answer
My inclination would be to go for option 3. Yes, I accept ktodisco's rationale behind suggesting option 1, but you're potentially going to need to do extra work to sort all your geometry, and it will kill you if you ever need to implement translucency (where your sort will need to be by depth rather than by shader used). Option 3 will be slightly slower for sure (although your GPU and/or driver may be able to optimize the fmod call internally depending on the params passed) but it's a huge win on code simplicity, and - all other things being equal - code simplicity would nail it for me.
> 2 votes

# Answer
Count out option two immediately. You should avoid at all costs branching in a shader. The only exception is if the branch is consistent for the entire rendering pass. Yes, branching is not as expensive now as it used to be, and shader compilation will often optimize such that the branch is negligible, but if it can be avoided, why do it?

From there I think the best choice is option one. If you can group the rectangles by type, then you will only be switching shaders twice per frame. Now, I don't know the exact performance specifications for switching shaders in DirectX; you can bet there will be some performance hit, but likely not much for just one or two switches, considering that programs with many different types of objects and materials can render quite fast, just fine. Another reason I'd advocate this is it creates the need for a system to swap shaders based on object type, and is therefore more extendable should you add new objects to your program.

Option three could (maybe?) end up being more efficient than option one, but the only way you'll find out is if you profile both. It's more likely though that option one will be the fastest.
> 1 votes

---
Tags: c++, shaders, hlsl
---


# Question
Title: Exporting XNA class library as a DLL file
I have downloaded an open source project that I intend to use with my current game. The download came with all the class files from the original project as well as a pre-compiled DLL file representing the project. I was able to easily link this DLL with my current project and get it working just fine, no problems there.

The problem I now have is that I want to make a couple of changes to the original libraries (extend its functionality a bit to better suit my needs) and re-export the class library as a DLL again, but I have no clue how to do this. Is there some simple way in VS where I can just take the class library and export/compile it as a DLL file again or is there more to it than that?

This seems like something that should be pretty simple but my efforts to find an answer have so far come up with nothing.

Thanks in advance.

# Answer
> 3 votes
**If you have the solution file:**

In the "Solution Explorer"

Simply add right click the "Solution 'Name'", Select Add -\> Existing Project -\> And locate the .vsproj or .sln file.

Then, when the project is added. Add a reference by right clicking the project that will use the library. Select Add Reference, "Projects" and select the Project from the list.

**If you have a .dll file:**

Create a new Class Library, add a reference to the .dll file by right clicking the Class Library Project, "Add Reference" -\> Browse to the .dll file.

Whenever you wish to extend or use a functionality, inherit the methods in the .dll file and implement your own methods or create a new method and use the methods in the Namespace (of the .dll file you just referenced)

Then, add a reference to the Class Library the same way as you did earlier (if you had solution) to your main project.

**Compiling**

When you compile your main project, if you included a dll file both .dll files will be compiled to the project output directory bin\x86 for example. If you imported the whole solution, only one .dll file will be in the bin\x86 directory.

# Answer
> 1 votes
Deukalion explains it very well. Appolgoes if you already know this, but you were saying that you couldn't find any sources of information...

The problem you are describing is one of the principles of object orientated design called the Open / Closed principle. One of the 5 basic principles of SOLID.

If you're looking to read more on it, here might be a good starting point : http://en.wikipedia.org/wiki/Open/closed\_principle

The Open / Closed principle is also known sometimes as 'Open for extension, Closed for modification'.

So you essentially don't want to modify the original source code, just extend it and build your own extended library to use in your project.

# Answer
> -1 votes
Did said open source project come with a VS project file (\*.csproj) or a solution? If so, open and compile. If not you could just start your own class library project and add the class files.

---
Tags: xna
---


# Question
Title: How to transform a subset of a vertex in a vertex buffer?
```
float linePos[6]={0.0f,5.0f,0.0f,0.0f,30.0f,0.0f};
...

glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*2, linePos, GL_STATIC_DRAW);

...
glUniformMatrix4fv(UniformColor.modelToWorldMatrixUnif, 1, GL_FALSE, glm::value_ptr(modelMatrix.Top()));
//this just transforms all vertices

glLineWidth(3);
glDrawArrays(GL_LINES,0,2);

```

I want to make some animation changing the position (ex.translate) of one end the line(linePos\[0\]) but not the other. How can I do that?

# Answer
> 2 votes
You can do that using glBufferSubData. In your case, with only 6 vertices, you can just replace the complete buffer using glBufferSubData. This prevents the reallocation that glBufferData does.

You shouldn't use GL\_STATIC\_DRAW if you change it often, thought.

---
Tags: opengl, transformation, vertex-arrays
---


# Question
Title: Where should I put .xnb files in mono game project using VS2010?
My problem was described here in the "The Content Pipeline" paragraph.

The author describes how to fix it using VS2012: put xnb files to \AppX\Content folder but I use VS2010 and mono game templates for it and there is no folder like this, so where must I put these assets to run the game correctly?

# Answer
AppX exists only in Windows 8 Store app (which is impossible to build on VS2010) You should place your Content folder in .exe location, usually bin/Debug, or just add it to the project with options "Content" and "Copy if newer/always".
> 1 votes

# Answer
Build the project.

Now the AppX folder should exist in "bin/Debug/"

Create the content folder and put your files in it.

Here's the tutorial I used for VS2010 a while ago.
> 0 votes

---
Tags: xna, monogame
---


# Question
Title: Who makes the art assets for mobile games?
I know how to develop apps for Android but never tried developing games, and I want to start soon. For developing games we need sounds and high quality images (say a background, characters, logos, etc.), so how to create these? For this should we have a separate team? Or a developer can create these using any tools?

# Answer
> 6 votes
There are multiple options for where the art comes from. It's perfectly possible for the developers to create the art themselves, or have a separate team make the art. Probably the easiest way to get started on this is just finding free art assets and using those as place holders or even the final art if it's good enough.

---
Tags: android, game-design, ui-design
---


title: C#/XNA get hardware mouse position

text:
# Question
Title: C#/XNA get hardware mouse position
I'm using C# and trying to get hardware mouse position. First thing I tryed was simple XNA functionality that is simple to use

```
Vector2 position = new Vector2(Mouse.GetState().X, Mouse.GetState().Y);

```

After that i do the drawing of mouse as well, and comparing to windows hardware mouse, this new mouse with xna provided coordinates is "slacking off". By that i mean, that it is behind by few frames. For example if game is runing at 600 fps, of curse it will be responsive, but at 60 fps software mouse delay is no longer acceptable. Therefore I tried using what I thought was a hardware mouse,

```
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetCursorPos(out POINT lpPoint);

```

but the result was exactly the same. I also tried geting Windows form cursor, and that was a dead end as well - worked, but with the same delay. Messing around with xna functionality:

```
GraphicsDeviceManager.SynchronizeWithVerticalRetrace = true/false
Game.IsFixedTimeStep = true/fale

```

did change the delay time for somewhat obvious reasons, but the bottom line is that regardless it still was behind default Windows mouse. I'v seen in some games, that they provide option for hardware acelerated mouse, and in others(I think) it is already by default. Can anyone give some lead on how to achieve that.

# Answer
**What you are seeing is *not* input lag.**

To get the position of the cursor in Windows you can use `WM_MOUSEMOVE` or `GetCursorPos`. They both provide the position of the cursor after Windows has processed it, applying things like acceleration. This is the cursor position that Windows uses, including for drawing. And almost always what you want to use too.

**This is what XNA uses**. Specifically `GetCursorPos` (MSDN). This means that, when you call `Mouse.GetState`, you are getting the true position of the cursor as Windows sees it - with practically zero delay.

Now, you could use `WM_INPUT` (or DirectInput, although that's deprecated). This gives you the raw pointer data. This is before Windows can apply things like acceleration, and is usually *not* what you want.

**What you are seeing *is* output lag.**

This is because of the "**hardware cursor**". This is a small sprite that gets drawn over the screen by the GPU at the *very* end of its pipeline. And I mean the *end*. It comes after the frame buffer - it gets inserted into the data stream as the image is being sent to the monitor. The reason it reacts so quickly is because its position is set by directly setting GPU registers. There is no waiting around in the pipeline at all.

Your game, on the other hand, has to go through the GPU pipeline. This adds plenty of delays on its own. The most problematic of these for you is double-buffering - which (I'm pretty sure) you can't turn off in XNA 4. You don't draw directly to the frame buffer - you draw to the backbuffer. Which gets presented every ~16ms (at 60FPS). That means you're looking at a minimum of about 16ms between receiving the result of `Mouse.GetState` getting something based on that result on-screen. Probably longer. Certainly much slower than the hardware cursor.

**So what are the solutions?**

One is to use `SetCursor` (MSDN) to change the image that gets displayed by the hardware cursor, to am image that better suits your game (or just live with the Windows cursor).

And the other (far easier) is to just accept the lag, and set `Game.IsMouseVisible = false` to hide the relative lag. Display your own cursor in-game. It will be 16ms slower than the hidden Windows cursor - but who cares? Gamers are used to it. And 16ms is almost visually imperceptible anyway (it's why we render things at 60FPS).
> 17 votes

---
Tags: xna, c#, mouse, hardware-acceleration
---


# Question
Title: Coordinates on the top left corner or center of the tile
I'm setting up a tile system where every tile has `x` and `y` coordinates. Right now I assume that the top left corner of the tile is positioned on it's coordinate on the screen, `x = tileX * tileWidth` and `y = tileY x tileWidth`.

However, it seems strange that the tile with coordinate `(0, 0)` is completely drawn in the 'positive' side of the coordinate system as opposed to in the center of the origin.

Is it common practice to assume that a coordinate lays in the center of a tile or at the top left corner of a tile? So basically `x = tileX x tileWidth` or `x = tileX x tilewidth - ( tileWidth / 2 )`?

# Answer
I would argue that it's common to work from the top left of the tile (assuming your coordinate system works with 0,0 at the top left).

This works well for several reasons:

* typical rendering routines take a position and dimensions as arguments. If you used the centre point, you'd have to subtract half the width and height to calculate the position each time.
* typical collision detection routines also take a position and dimensions as arguments, and the same principle above applies.
* converting from pixel coordinates to tile coordinates can be done with integer division (ie. rounding down). Divide the pixel position by the tile size to get the tile index in a zero-based array. If you use the centre point you have to add in an offset to compensate.
* You need never work with negative numbers. The extreme corner of your map is typically 0,0 whether you count in pixels or in tiles. But if your tiles had their origin at the middle then you'd have to accommodate at least half a tile's worth of negative numbers for the 0,0 tile.
* The top left pixel of a graphic is unambiguous and invariant over images of different sizes. However the mid point may be less simple - if a tile has an even width, there is no middle row of pixels, and rounding or truncating this calculation could cause off-by-one errors.

Of course, all these issues are counterbalanced by some problems caused by not using the centre-point, such as counting a character as being on tile 0 when only 1 pixel is on that tile. But you can easily have a `GetCenter()` member for each tile or object which you can use for such logic calculations, and leave all the rendering to work via the top left corner.
> 4 votes

---
Tags: tiles, coordinates
---


title: Where to find passive advertisements?

text:
# Question
Title: Where to find passive advertisements?
Imagine a soccer game. While the player is playing a match, he is seeing the billboards all the time.

I want to include that kind of advertisements in my game (obviouly, making profit). Just a brand logo, not a banner the user has to click.

Does this even exist? Is there any AdMob like which allows this kind of advertisement?

# Answer
> 3 votes
I found three advertising agency's that seem to offer exactly what you're searching for:

**Reloaded Advertising**

---

Dynamic In-Game Advertising,
Console Integration,
Mobile In-Game Advertising,
Static In-Game Advertising,
AdverGaming,
Inventory Management

**Game Diamond**

---

Static In-Game Advertising,
Dynamic In-Game Advertising,
AdverGaming,
Virtual World Advertising

**Engage Advertising<br>**

---

Fixed product & brand integration,
Dynamic integration,
Partnetship marketing,
Branded game publishing,
Game communities,
Sponsorships

---

I also found two pdf brochures that might be of interest for you (You could grab contact information from there):

---
Tags: marketing
---


# Question
Title: How can I make video games if I don't like programming?
I am studying C++ code in my school (my major is computer programming). Honestly, my grades are not so good, and assignments are really hard. Sometimes I feel sad that I will spend 8-10 hours per day coding (which is stressful) in the future for my job.

But I still want to make video games. Maybe this is the only reason why I am taking all of these stressful courses. I always write down plots, stories, characters, fictional gaming worlds... Once, I thought I should study artistic technology such as game design and not computer technology such as C++, C#, etc.

However, most of popular game designers (or directors) such as Kojima, Miyamoto, etc. used to be good programmers. Companies actaully assign programmers to directors because they understand how to make a game.

I've try to find other colleges or universities where they teach game design programs. However, one article that lists rank 10 game design schools in North America seems untrustful because the survey company only scores it from intervews of students.

Once, I tried to attend Art Institute of Vancouver which is rank 7 according to that article. However, one programmer who used to be an instructor in there told me the truth: the employement rate of graduated students is low.

How can I have a future making games if I don't like programming?

# Answer
Programmers are far from the only people in the game industry. From what you've stated, it sounds like you'd be much, much happier pursuing a game design career. You could still write down those plots, stories, characters, and fictional gaming worlds with a team of other game designers (depending on how big the game company is). Then just hand all the designs to the programmers and game artists, and they'll put your ideas into action.

A game design major would be a lot more fun, and it doesn't pay that much less than being a programmer.

I personally have plans for a double major in game design and programming, simply because I'd like to create my own independent games some time in the future. As for a school, I've been looking at Champlain college in Burlington.

Here's a link to the game design major I was looking at: http://www.champlain.edu/undergraduate-studies/majors-and-programs/game-design-x14300.html

Also, of you are concerned that you'll need to have a decent insight into game programming to be a better game designer, take a look at this minor course in game programming: http://www.champlain.edu/undergraduate-studies/majors-and-programs/game-programming-minor.html

I hope some of this helps!
> 17 votes

# Answer
Game Design distinct from Game programming.

*You can* have a role as a game designer and not touch code.
> 6 votes

# Answer
I believe that as a game designer, you should have at least one area of expertise where you can be productive for the whole development cycle. You should have at least a good notion of what's going on with the code because after all, that's what holds any video game together.

I didn't plan to post this answer, but today I read some solid evidence to back it up:

Valve's presumably leaked employee manual says on page 39-40:

> **Non-Engineers: program or be programmed**
>
> Valve’s core competency is making software. Obviously, different disciplines are part of making our products, but we’re still an engineering-centric company. That’s because the core of the software-building process is engineering. As in, writing code. If your expertise is not in writing code, then every bit of energy you put into understanding the code-writing part of making software is to your (and Valve’s) benefit. You don’t need to become an engineer, and there’s nothing that says an engineer is more valuable than you. But broadening your awareness in a highly technical direction is never a bad thing. It’ll either increase the quality or quantity of bits you can put “into boxes,” which means affecting customers more, which means you’re valuable.
> 6 votes

# Answer
Are you artistic? Have you considered doing a digital media degree? I have a lot of friends that are studying both Computer Science and Digital Media and a lot of them have found digital media very enjoyable.

I'm not sure of your circumstances exactly, but the whole game creation process involves many different people of varying skills. If not pure game design (which is definitely a field that you might like), there's still modelling and animation, sound, etc.

Good luck!
> 4 votes

# Answer
Have you considered programming in another language than C++? You say programming can be stressful, but just picking a programming language that suits you better might relieve a lot of stress.

Especially if you're not really into the technical side of computers C++ might just not be the language for you. It is designed to be very fast, but can be on the verbose and intricate side. It's also very unforgiving when it comes to forgetting implementation details like memory management and types. For a non-technical person I think these properties can give you extra stress since your mind is not aligned to the implementation details.

I think trying to make a game in for example PyGame (it's in Python and I heard good things about it) would allow you to really focus on game mechanics and other highlevel game properties while not fussing so much about implementation details. It might relief some stress and release your creativity. Other languages that might be easier on you: Ruby, Lua, C#, Javascript/Coffeescript.

You are totally right that most of the big name game designers are also programmers. It is hard to get recognition as a game designer when you don't actually have any games to show for it, and it's hard to convince a programmer to make you a game when you don't have a track record. I think you'll definitely gain more respect when you have produced at least one game, even if it's a small webbased one.

I say make the programming part as easy as possible so you can focus on the things that are important to you.
> 3 votes

# Answer
I started out like you, hating programming, and loving the other aspects. I failed the programming course the first year, but had to retake and get a positive grade to stay in school. I tried my best a bit harder that year and actually enjoyed it. Now 3 years later I'm about 75% programmer and 25% artist.

There is one difference: I started with actionscript 3, which doesn't involve all the low-level headaches that c++ does. I actually hate c++ and low level programming in general. I think the conditions in which you were introduced to programming are not optimal. Try an easier language like actionscript or c#(xna), it's a big difference.
> 2 votes

# Answer
I just found this article on gamasutra. It's about using gamemaker: http://www.gamasutra.com/view/feature/182860/Suck\_at\_Coding\_But\_Make\_Games\_Anyway.php

This tool might be considered silly and easy, but it definitely can be used to create games.

For example, Spelunky was created with game maker.
> 2 votes

# Answer
## Pick a skill, any skill, and excel at it

Even ignoring that most game studios/indies have a ton of their own ideas to work with and aren't going to care about some random person with ideas of their own... ...have you looked around the web? It's full of nothing **but** game ideas, almost all of which haven't and won't come to fruition. Everyone and their little brother has game ideas, so you had better work on becoming better at **bringing an idea to fruition**, the hardest part. Which requires organization, or management or capital, etc.

## Write english instead of code

Either that or write instead, which totally skips the programming aspect, though also isn't easy to get published or if self-published, get popular. You can create games with just writing, and you can create writing that **feels** playful like a game, if you work at it. And people will enjoy that in the way that they would a game, so why not?

## Pick a different language, or two, or three

I would hate C++ if I were writing in it, too, which is why I don't. I write in different languages instead (I like clojure, though I often don't get to use it, and I don't hate javascript). Programming is not an identical experience across the various languages.

That said, having a career of programming, well, it's different than just doing it for fun, regardless of your exact circumstances. I work from home doing web coding, and develop games on the side, but even despite that I don't have a boss, work for myself, freelance, and can use my time almost as I will, it's still stressful and you have to struggle at making money, and it'd be nice to get out into the outdoors once in a while...

## Try to find programming professors/mentors/coder friends that don't hate themselves

Just a final note, have you really examined the attitudes of the professors that teach intro programming to crowds of not-right-for-programming kids? In my experience, they're not happy, enthusiastic people. Don't take that to heart, that's just them trying to reconcile all the horrible "programmers" that they'll be unleashing on the unsuspecting world by failing the barest minimum. Probably with heavy reliance on alcohol to get through it. If, instead, you get together with enthusiastic people who love coding, or coders who love game design ( try a game jam: http://globalgamejam.org/ ), you might find yourself liking the experience a lot more.
> 2 votes

# Answer
It sounds like your best bet for a job is as a writer. If that is what you want maybe you should look into studying English or Literature.

Computer game writing is probably the hardest kind of writing you can imagine, it's never completely linear, it has to fit into a game world designed with many other considerations in mind, and often your work won't be visible in anything like it's final form until it is basically too late to change.

So for practice you should probably use a good part of your time writing normal fiction, simply because that lets you create something in it's final form without the need for a team to make a game around your story. Film and theatre scripts are kind of a middle ground, you have the linearity but still make a work that has to be visualised.

You may also want to look into gameplay (designing board games is great practice), and drawing/painting. Some games may have jobs where such skill combinations are valuable.
> 1 votes

# Answer
There are tools that you can use to make simple games, if you hate programming. For example, GameSalad provides a very nice tool for cobbling together simple 2D games, without writing a mess of scary code.

However, if your ambitions reach beyond what you can make with a tool like that, you need a programmer -- whether it's you, a friend, or a woman down the hallway in the programming department at your future game company. At the end of the day, **programming is how you tell the computer what game you are trying to make and how it is supposed to interact with players**. Without programming, there's no way for the computer to have any idea what to do.

It sounds like what you really desire is to pursue a career in game design. First, you must disabuse yourself of the notion that game design is about stories and characters. What is the narrative in Tetris or Bejeweled? There isn't one! There *are* writing jobs in the game industry, but they are few and far between, and a lot of companies just outsource that work. There are a lot of other things that designers do, though, such as level design and systems design, and if you want to be a game designer, it would be a great idea to learn some of these other skill sets, as well.

Second, you should understand that Design is a very difficult track to get into from outside the industry, because it is almost impossible to prove that you have the necessary skills and talent. In general, my advice is usually to break into another track (such as programming, art, or production) first, before trying to get into design. So, it is worth learning one of those other skillsets. If you are already learning programming, it would be kind of a waste not to take advantage of that.

However, it sounds like you are struggling with your programming skills. That's a bit of a problem, since the industry is picky about their programmers. So, on to the next advice:

Another way to get a Design job is to... well... prove that you can make games. Nothing proves that you can make a game like making a game, after all. There are a lot of free tools that can help you get started. If you already know a little programming, you have a huge edge over other people who want to be designers. A programmer can make a game *with nobody else*. Oh, it will be hideous, but *that doesn't matter*, as long as it's fun. There are a lot of free tools out there, now. Try out Unity3D, and see what you can make.
> 1 votes

# Answer
If you still want to give programming a shot, I suggest giving processing a try, its a pretty easy language to pick up, I tried to learn programming by going straight into C and C++ and it overwhelmed me, I stepped back and continued to do more level design and I tried processing and it gave me a good foundation in code.

It does sound like you would be happier as a game designer though.
> 0 votes

# Answer
Languages such as Python (with Pygame) or Lua is certainly the way to go in you regaining the FUN of doing this! :-D

My intention is to help my little brother learn programming as he wants to program computer games and so we will be learning Scheme together (specifically: Racket http://docs.racket-lang.org/quick/ & using this textbook: http://www.ccs.neu.edu/home/matthias/HtDP2e/ which is very famous).

This will give him a REALLY solid understanding of computer science in a relatively painless manner (MIT used to teach their "CompSci 101" course in Scheme, it is very popular for this purpose).

Then after that we shall learn Lua together (Lua has strong links with Scheme, is kinda a "cut down" version of it. So it should be super easy to pick up Lua once we've got the hang of Scheme. And there is many more excellent resources teaching Scheme than there is for Lua because Scheme has a rich history of being taught at University for introductory courses).
> 0 votes

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


title: Shadow cubemapping?

text:
# Question
Title: Shadow cubemapping?
I am working on a game with C++ and OpenGL 3.2. I have successfully implemented directional shadow maps and now I'd like to upgrade them to shadow cube maps (for point lights). I've done some Googling and I can't seem to find much solid info on how to achieve this.

What is this technique called?

# Answer
What you are looking for is called "Omnidirectional Shadow Mapping". Google has lots of hints for that.
> 3 votes

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


# Question
Title: How to deal with Character body parts from Design to Cocos2d
I'm trying to figure out the pattern the game developers use together with game designers:

See the picture below with the independent parts:

Questions:

1) Should I create different image parts from different body parts or keep frame by frame animaton? (I know both can be used, but I'm trying to figure what is commonly used in the industry)

2) If I'm going to generate different image parts from different body parts (which is I thing is more logical) how would I export that to Cocos2d (Vector or Bitmap)?

# Answer
1. Different people will have different answers for you. The game programmer & artist should collaborate, to determine the best process of using sprites. OR you can design your sprites using Layers, for each body part. That way you will have an original file to refer back to, when you need to make modifications. Working with Layers allows you to save each individual body part in a separate file.
2. Again, different people will have different answers for you. I've read several articles/blogs on the topic of Vector vs Bitmap. Best approach I have read, is designing the original in Vector. This is done because you can re-scale the image w/ no distortion, compared with trying to re-scale an image in Bitmap. Final touches are made and saved as Bitmap.

Remember OPINIONS are just that. You will have to determine the best process for YOUR game design. When you read articles/blogs remember to look at the author's background. Look for opinions from authors that are employed or previously employed by a company that makes games.
> 1 votes

# Answer
Using a plain ole sprite sheet and animating frame-by-frame works just fine. The same goes for doing skeletal animation. It's really going to come down to your specific needs, for instance:

1. Are there any particular technical contraints that make one option more attractive than the other? Frame-by-frame animations will tend to use more memory than skeletal ones. Skeletal animations will require more complex code to implement.
2. Are there any design constraints that make one option more attractive than the other? Do you want your character to bounce around like a rag doll when he dies? Do you need to be able to change the animation at runtime? These things will be easier to do with skeletal animation.
3. What tools does your artist prefer?
4. What workflow does your programmer like?

These are just a few questions to ask yourself and your team. You can probably come up with plenty more.

Whatever you do you definitely want to be exporting bitmaps for use in your game.

If you're interested in skeletal animation you should check out Spriter. Looks like there is at least one Cocos2d implementation of the Spriter format on Github.
> 0 votes

---
Tags: game-design, sprites, cocos2d-iphone, ios
---


# Question
Title: How do I make something visible only when I'm looking at it?
So I'm making a basic 2D game in C# XNA. I want it so wherever my character is facing there is a cone of light and only that part of the level is visible while the right of the screen is dark. Please excuse my ignorance, I haven't been working with C# too long.

# Answer
> 8 votes
Well the simplest approach to this would be to simply overlay a dark mask over the right side of the screen. You could do this with a completely opaque black image that covers stuff from view, but I think what would look better is a semi-transparent black image so that you can still see the background and then hide the enemy graphics on that side of the screen.

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


# Question
Title: Are Xna XACT audio cues accurately timed enough for a loop sequencer?
Would it be possible to make an audio seqencer using XNA that works by triggering XACT cues periodically using a timer. Would the timing be precise enough to synchronize several audio clips into one loop? (Think Ableton Live)

# Answer
Not sure if you'd be able to, but on the bright side, you most likely don't have to.

If you're just trying to create a series of sounds to play in a row (and even loop that series) that can all be done in XACT.

When you have the XACT project open and all of the wavs added and corresponding Sounds for them, just drag the sounds onto the Cue that you want to use. In the bottom-left panel, you can control how the cue uses the selection of sounds.

For instance, Random will just play one of the sounds with certain probability, but it sounds like you want "Ordered" or "Ordered from Random" so it will play all of the sounds.

"Interactive" gives you other freedoms as well. See this thread for more info.
> 2 votes

---
Tags: xna, audio, xact
---


# Question
Title: Regarding sprite design and resolution for tablets and phones
I am about to start working on a game for android devices, in my spare time, to get familiar with android development. I'm more interested in using the best practices possible than getting a quick result, and that is why I need some guidance regarding graphics.

I think the game is going to be fully sprite based. Everything is going to be in .bmp form, or something similar, and my question is:

**Should I design the sprites in a small resolution (ie for phone screens) and scale them up to fit into larger screens (tablet screens), should I do it vice-versa or should I consider a completely different approach?** Would designing a different set of sprites for each of the most used resolution settings be worth it or are there simpler solutions to the problem with fewer drawbacks than the ones I mentioned above? (If I follow the first approach, for example, the larger the screen the worse the graphics will get, since every pixel of the original drawing will cover several pixels on the screen). **Is there a standard approach for dealing with this kind of problems?**

If you need me to be more detailed or more clear about something I mentioned (or forgot to) please don't hesitate to ask. Also, excuse me for any inaccurate use of the English language.

Thank you in advance for your input.

# Answer
> 3 votes
There is no standard about this for a good reason: there are infinite variations on the topic, infinite combinations of inches and pixels for every device out there.

Usually a smartphone or a generic mobile device has a dpi value much higher than a normal PC monitor, so if you think in terms of pixels you are supposed to produce an image that will appear much larger on your monitor than what actually does on a mobile device.

You can solve this keeping in mind 3 things:

* Android can pick for you the appropriate layout since this OS makes a distinction mainly based on the DPI value, you can read more here and here ( but in general you can find much more informations on the entire Developer section )
* Android offers several units when it comes to graphics and typography
* there are also some classes and methods that can help you with this programmatically like this one

I suggest to start from the units definitions.

# Answer
> 1 votes
The blog link below should answer your question. This blog has a lot of useful information. Vicki Wenderlich's Blog

---
Tags: android, sprites, resolution
---


# Question
Title: What OpenCL video cards (or FPGAs) features are needed for high speed multiplication?
I'm benchmarking some cryptographic related software and am looking for video cards that are better at parallel multiplication vs parallel addition.

* Is there any prior work that would graph video card performance against math operations (calculating large digits like 256^2048, calculating the modulus etc.)
* What GPU features should I look for?

# Answer
> 1 votes
You only really have two options when it comes to high performance graphics cards - AMD or NVIDIA.

The simplest answer is to get one of each, and profile your algorithm on both to see which is best in your specific case.

However, my guess based on having seen a few articles like http://www.theregister.co.uk/2012/12/07/monster\_password\_cracking\_rig/ is that you probably want an AMD card.

---
Tags: opengl, mathematics, opentk, encryption
---


# Question
Title: What method replaces GL_SELECT for box selection?
Last 2 weeks I started working on a box selection that selects shapes using GL\_SELECT and I just got it working finally.

When looking up resources online, there is a significant number of posts that say GL\_SELECT is deprecated in OpenGL 3.0, but there is no mention of what had replace that function.

I learnt OpenGL 1.2 in back in college 2 years back but checking wikipedia now, I realise we already have OpenGL 4.0 but I am unaware of what I need to do to keep myself up to date.

So, in the meantime, what would be the latest preferred method for box selection?

EDIT: I found http://www.khronos.org/files/opengl-quick-reference-card.pdf on page 5 this card still lists glRenderMode(GL\_SELECT) as part of the OpenGL 3.2 reference.

# Answer
> 6 votes
The way I do picking in core OpenGL is to assign a unique color to every object in the world and draw only the vertices (no texcoords, normals, etc.) with the assigned color to a FBO.

Once all the objects have been drawn, you can call glReadPixels at the mouse coordinate with a width and height of 1 to get the pixel color at that point. Then all you have to do is lookup which object was assigned to that color and return it.

If you want to drag-select a rectangle, do the same thing, but store the pressed mouse coordinate and change the parameters of glReadPixels to read back the selected rectangle between the pressed mouse coordinate and the released mouse coordinate.

# Answer
> 2 votes
In modern OpenGL you shouldn't use GL\_SELECT for objects picking since OpenGL is an API for hardware accelarated graphics drawing. But there are other methods which you can use.

As @Robert wrote, you can use color selection in order to pick objects on the screen. Another thing you can do is to cast a ray from the mouse cursor to the game world and check for collisions between the ray and the world's geometry.

To construct the ray, you will need to get the mouse cursor's position in world space. That position will be of use to you in order to calculate the ray's direction. The ray's origin is the position of your camera. Now that you have the ray, you can make an intersection test between the ray and the geometry you are trying to pick. If the test succeeds, then you have a clicked object, else you don't have one.

The code concerning the ray's construction is the following:

```
Ray Mouse::GetPickRay(mat4 projMat, mat4 modelMat,
                      vec4 cameraPos,
                      int windowWidth, int windowHeight)
{
    float mouseX = float(this->currentPosition.x);
    float mouseY = float(this->currentPosition.y);

    vec4 mousePos_clipSpace = vec4(
                                  ((mouseX * 2.0f) / windowWidth) - 1.0f,
                                  (1.0f - (2.0f * mouseY) / windowHeight),
                                  0.0f,
                                  1.0f);

    vec4 mousePos_viewSpace = inverse(projMat) * mousePos_clipSpace;

    mousePos_viewSpace = mousePos_viewSpace / mousePos_viewSpace.w;

    vec4 mousePos_worldSpace = inverse(modelMat) * mousePos_viewSpace;

    vec4 rayDirection = normalize(mousePos_worldSpace - cameraPos);
    vec4 rayOrigin = cameraPos;

    return Ray(rayOrigin, rayDirection);
}

```

This article describes very well the logic behind the unprojection of the mouse cursor's coordinates and the creation of the ray.

The only thing that's left is to check for intersections between the ray and the world's geometry. You can find various algorithms on the Internet about how to do that.

# Answer
> 0 votes
You could use something like Bullet.

It's a physics library but you can just use it for ray collision. I (should) be using it soon for my project.

---
Tags: opengl, selection
---


# Question
Title: Unity3D and Texture2D. GetPixel returns wrong values
I'm trying to use Texture2D set and get colors, but I encountered a strange behavior. Here's the code to reproduce it:

```
Texture2D tex = new Texture2D(2,2, TextureFormat.RGBA32 ,false);

Color col = new Color(1.0f,0.5f,1.0f,0.5f); //col values: 1.00, 0.500, 1.00, 0.500
tex.setPixel(0,0,col);
Color colDebug = tex.getPixel(0,0);  //col values: 1.00, 0.502, 1.00, 0.502

```

The Color retrieved with getPixel is different from the Color set before. I initially thought about float approximation, but when inspectin col the value stored are correct, so can't be that reason.

It sounds weird even a sampling error because the getValue returns a value really similar that not seems to be interpolated with anything else. Anyway I tried even to add these lines after building the texture but nothing change:

```
this.tex.filterMode = FilterMode.Point;
this.tex.wrapMode = TextureWrapMode.Clamp;
this.tex.anisoLevel = 1;

```

What's my mistake? What am I missing?

In addition to that. I'm using tex to store Rect coordinates returned from atlas generation, in order to be able of retriving the correct uv coordinate of an atlas inside a shader. Is this a right way to go?

# Answer
I think I have understand the reason. Color store each component as a float value (32 bit for each component) right?

When I set the color with setPixel it's implicitely converted to Color32, so some values are truncated and when I get them back they are different.
> 1 votes

---
Tags: unity, textures
---


# Question
Title: Best practice for organizing/storing character/monster data in an RPG?
Synopsis: Attempting to build a cross-platform RPG app in Adobe Flash Builder and am trying to figure out the best class hierarchy and the best way to store the static data used to build each of the individual "hero" and "monster" types. My programming experience, particularly in AS3, is embarrassingly small.

My ultra-alpha method is to include a "\_class" object in the constructor for each instance. The \_class, in turn, is a static Object pulled from a class created specifically for that purpose, so things look something like this:

```
// Character.as
package
{
  public class Character extends Sprite
  {
    public var _strength:int;
    // etc.
    public function Character(_class:Object)
    {
      _strength = _class._strength;
      // etc.
    }
  }
}

// MonsterClasses.as
package
{
  public final class MonsterClasses extends Object
  {
    public static const Monster1:Object={
      _strength:50,
      // etc.
    }
    // etc.
  }
}

// Some other class in which characters/monsters are created.
// Create a new instance of Character
var myMonster = new Character(MonsterClasses.Monster1);

```

Another option I've toyed with is the idea of making each character class/monster type its own subclass of Character, but I'm not sure if it would be efficient or even make sense considering that these classes would only be used to store variables and would add no new methods. On the other hand, it would make creating instances as simple as `var myMonster = new Monster1;` and potentially cut down on the overhead of having to read a class containing the data for, at a conservative preliminary estimate, over 150 monsters just to fish out the one monster I want (assuming, and I really have no idea, that such a thing might cause any kind of slowdown in execution).

But long story short, I want a system that's both efficient at compile time and easy to work with during coding. Should I stick with what I've got or try a different method?

As a subquestion, I'm also assuming here that the best way to store data that will be bundled with the final game and not read externally is simply to declare everything in AS3. Seems to me that if I used, say, XML or JSON I'd have to use the associated AS3 classes and methods to pull in the data, parse it, and convert it to AS3 object(s) anyway, so it would be inefficient. Right?

# Answer
> As a subquestion, I'm also assuming here that the best way to store data that will be bundled with the final game and not read externally is simply to declare everything in AS3. Seems to me that if I used, say, XML or JSON I'd have to use the associated AS3 classes and methods to pull in the data, parse it, and convert it to AS3 object(s) anyway, so it would be inefficient. Right?

I suppose you could do that, but doing that would be a hassle to change the numbers, especially for a development team of anything more than 1. As in, if you are the only developer and are sure there will never be any other developers then I guess hard-coding all the values would work out okay. But that's generally a bad coding practice because it's more cleanly organized to keep code and data separate. That helps even if it's just you, but is pretty imperative if there is anyone other than you who will be working on the game.

As for the overall question, I would code your monsters as a class that operates on whatever strength etc. you pass in and then read in a JSON file where the values for the different monsters is defined. Then instantiating a specific monster would look like `var monster = new Character("monster3")` or maybe `var monster = new Character(data)` where the JSON would be something like:

```
{
  "id": "monster3",
  "image": "demon.jpg",
  "strength": 50
}

```

Basically, I'm recommending your first approach but with the data defined in an external data file instead of hard-coded as a class.
> 5 votes

---
Tags: actionscript-3, rpg, data-structure
---


title: TexturePacker ignores extensions

text:
# Question
Title: TexturePacker ignores extensions
I'm using TexturePacker in one of my games, though when packing a bunch of textures their extension is kept in the data file. So when I want to find a texture I need to search for "image.png" instead of just "image". Is there an option to let texture packer ignore the extensions of my source images in the data file?

Solved:

So if anyone else wants this, here's the exported I made: https://www.box.com/s/bf12q1i1yc9jr2c5yehd Just extract it into "C:\Program Files (x86)\CodeAndWeb\TexturePacker\bin\exporters\UIToolkit No Extensions" (or something similar) and it should show op as an exporter.

# Answer
> 1 votes
You can actually create your own export format. From their page:

> You need something special or your favorite framework is not supported? Just create your own export format! The template based exporter allows you to enhance TexturePacker to match nearly any output.

Check out their template based exporter and create your own format to remove extensions.

---
Tags: textures
---


# Question
Title: Where in a typical rendering pipeline does visibility and shading occur?
I am taking a computer graphics course. The book and the lecture notes are vague on the on the order of flow between the different steps in the rendering process. For example, if we have specified a view in a scene, and then want to perform a projection transformation for that given view, then we have to go through a sequence of transformations. In the end we end up with a normalized "viewcube" ready to be mapped 2D after clipping. But why do we end up with a cube (ie 3D thing), when a projection results in projecting the 3D objects to 2D. (depth information is lost?) The other line of reasoning is that all information further needed is stored within the "cube" and that visibility detection and shading is performed with respect to this cube and then we perform rasterezation.

edit: (More explicit question) Is shading and visibility checks performed after projections/normalization and clipping.

# Answer
Short answer: visibility determination occurs both before and after the projection to screen space. Shading is generally done afterward.

Longer answer:

Visibility determination in a typical rendering engine takes place at several different levels of granularity: object, triangle, and pixel. These occur in different parts of the pipeline.

First, on the CPU, the engine will typically use a scene graph to cull entire objects that it determines are not visible from the current camera position. This involves frustum culling (getting rid of offscreen objects) and occlusion culling (getting rid of objects entirely hidden behind other opaque objects). Both of these act to reduce the number of draw calls sent to the GPU. Each mesh will be either drawn in its entirety if any part of it is visible, or not drawn at all. (By "drawn" here I mean the engine queues up a draw call for it and sends it to the GPU.)

When the GPU processes a mesh, it starts running the vertex shader on each vertex in it. This transforms the vertex into screen space. Note that screen space is still 3D. The XY coordinates of a vertex in screen space determine the pixel coordinates on screen, but the Z depth is also kept so that we can do per-pixel visibility later. If we threw away the Z at this point we wouldn't be able to tell which triangles should appear in front of which other triangles.

Once vertices start coming out of the vertex shader, the GPU assembles them into triangles and any triangles that fall entirely offscreen are thrown out. Triangles are also clipped when necessary. So this is the triangle-level visibility. After this the remaining triangles are passed to the rasterizer, which determines which pixels are covered by a triangle and runs the pixel shader on each of those.

The pixel shader typically does most of the work of calculating lighting and shading. After the pixel shader is done\*, the result is stored to the framebuffer. However, it is only stored if the Z depth of the pixel (interpolated from the Z depths of the triangle's vertices) is closer to the camera than the Z depth already stored in the depth buffer at that pixel. So this is per-pixel visibility and is the finest-grained level of visibility determination.

\*Footnote: actually, depth testing can often be done before the pixel shader runs, which saves a lot of time by not shading invisible pixels.
> 3 votes

---
Tags: rendering
---


title: Get Text dimmensions on CCTextFieldTTF

text:
# Question
Title: Get Text dimmensions on CCTextFieldTTF
Hi I want to know the width of the text inside the CCTextFieldTTF but I can't find a way to do it, I want this width so I can move a CCLabelTTF in that position so it can be like a cursor for the CCTextFieldTTF

Thanks

# Answer
> 0 votes
So I came up with an idea that really works

In CCTextFieldTTF.h declare a new method

```
float getTextDimensions();

```

And in your .cpp

```
float CCTextFieldTTF::getTextDimensions()
{
    return CCLabelTTF::getContentSize().width;
}

```

And know just call your CCTextFieldTTF object

```
m_pTextField->getTextDimensions()

```

And do whatever you like with it

---
Tags: cocos2d-x
---


title: boolean operations on meshes

text:
# Question
Title: boolean operations on meshes
given a set of vertices and triangles for each mesh. Does anyone know of an algorithm, or a place to start looking( I tried google first but haven't found a good place to get started) to perform boolean operations on said meshes and get a set of vertices and triangle for the resulting mesh? Of particular interest are subtraction and union.

Example pictures: http://www.rhino3d.com/4/help/Commands/Booleans.htm

# Answer
I think of this as Constructive-Solid-Geometry (CSG). Hopefully you can find some help here.

http://www.alsprogrammingresource.com/csg.html

http://createuniverses.blogspot.com/2009/09/qtcsg-constructive-solid-geometry.html

http://www.nigels.com/research/

Also search google for Constructive Solid Geometry as a start.

HTH
> 10 votes

# Answer
I think we can puzzle it out if we just think about it.

You would obviously want to create faces (triangles) where the two geometries intersect. Then you're left with three meshes: the intersection you just isolated, geometry 1, and geometry 2.

Then, just delete what you don't need!

* BooleanDifference: delete the isolated part and geometry 2.
* BooleanIntersection: delete geometry 1 and 2, leaving the isolated part
* BooleanUnion: merge geometries 1 and 2 and delete the isolated part (make sure to stitch together geometries 1 and 2 into a solid geometry)
* BooleanSplit: Separate out geometry 1, geometry 2, and duplicate the isolated part (attach one to geometry 1 and the other to geometry 2)

I think that covers it, eh? The tough part would obviously be creating the intersection faces. For that, iterate through each face of one and check if that face is part of the other; if it's totally inside, then copy the face as part of the intersection mesh. If it's partially inside, then you need to split the triangle along the intersection line; I think DirectX and OpenGL would both have helper functions for this, or it's just some 3D plane math (vectors). I learned that kind of thing in Calculus 3 (or was it 2?) but if you don't have a clue, perhaps ask at math.stackexchange.com. And then of course if the face is outside, do nothing. Once you iterate over all faces of both meshes you'll be left with the intersection mesh.
> 4 votes

# Answer
If you're dealing with polygonal models, you may well have to deal with non-manifold geometry, which means the question of what is "inside" and what is "outside" is not defined. It's tricky to perform a boolean operation if you don't know if you have a 0 or a 1.

You also have to deal with fringe cases such as co-planar polygons, polygons which intersect edges, vertices which lie on edges and/or faces, and things of that nature. None of which is impossible, you just need a very robust way of representing your mesh data, and a tight definition of what you expect to happen in those cases.
> 2 votes

# Answer
It's worth noting that most of your operations can be represented by negation and union, where negation of some geometry is just that geometry with its normals flipped. So if you can get union right, then the other operations should just follow:

* intersection(A,B) := !union(!A,!B)
* subtract(A and B) := !union(!A,B)

Sander has some fairly good blog posts that discuss CSG implementations: http://sandervanrossen.blogspot.com/search/label/CSG
> 1 votes

# Answer
This is a pretty tricky subject, at least if you want to do it robustly (floating point causes some serious difficulties).

I would point you to the computational geometry / computer graphics literature on the subject, particularly these recent papers:

http://homes.cs.washington.edu/~gilbo/repofiles/booleans2009.pdf

http://openflipper.org/uploads/media/campen\_2010\_eg\_02.pdf
> 1 votes

---
Tags: graphics, algorithm, graphics-programming, procedural
---


title: DirectX 9.0c and C++ GUI

text:
# Question
Title: DirectX 9.0c and C++ GUI
Well, I'm trying to code a gui for my engine, but I've got some problems. I know how to make a UI overlay but buttons are still black magic for me. Anything I tried was to compilcated ( if it goes big ). To Example I tried to look if the mouse position is the same as the Pixel that is showing the button. But If I use some bigger areas it's getting to complicated. Now I'm searching for a Tutorial how to implement your own gui. I'm really confused about it. Well I hope you have/ know some good tutorials.

---

By the way, I took a look at the DXUTSample, but it's to big to get overview.

# Answer
So what I'm understanding is that you are looking for a quick way to test for GUI button presses?

The way I check is to have each button contain its own rectangle and check for a collision between the mouse and the button rectangle.

```
#include <windows.h>

class Button
{
 public:
     //The 'rect' variable is the 'Hotspot' for the button
     //Whether that is the whole button or just a select piece of it.
     RECT rect;

     //The constructor sets the 'rect' var accordingly.
     Button(RECT rect){this->rect = rect;};

     //Checks for collision between two RECTs
     bool RectCollision(RECT rectA, RECT rectB)
     {
         if(rectA.left > rectB.right)
             return false;
         if(rectA.right < rectB.left)
             return false;
         if(rectA.top > rectB.bottom)
             return false;
         if(rectA.bottom < rectB.top)
             return false;

         return true;
     }

     //This function is ran if the mouse button is pressed
     //which is checked in your 'WindowProc' function.
     bool CheckForButtonPress()
     {
          POINT mousePos;
          if(GetCursorPos(&mousePos)) //Gets the mousePos on the screen
          {
              if(ScreenToClient(hwnd, &mousePos)) //Sets the mousePos relative to the window
              {
                  RECT mouseRect = {mousePos.x, mousePos.y, 1, 1};
                  if(RectCollision(rect, mouseRect))
                      return true;
                  return false;
              }
          }

          return false;
     }
}

```

Obviously you can do some optimizations and changes. But I hope you get the gist of it.

Sincerely -MasterBaldwin
> 1 votes

---
Tags: c++, directx, windows
---


# Question
Title: Avoiding orbiting in pursuit steering behavior
I have a missile that does pursuit behavior to track (and try and impact) its (stationary) target.

It works fine as long as you are not *strafing* when you launch the missile. If you are strafing, the missile tends to orbit its target.

I fixed this by accelerating tangentially to the target *first*, killing the tangential component of the velocity first, then beelining for the target.

So I accelerate in -vT until vT is nearly 0. Then accelerate in the direction of vN.

While that works, I'm looking for a more elegant solution where the missile is able to impact the target *without* explicitly killing the tangential component first.

# Answer
> 5 votes
It looks like the problem is that the missile is simply pointing itself at the target without regard for it's current velocity. Assign your missile a maximum angle by which the thrust can deviate from the line of motion.

At each guidance iteration you calculate it's velocity perpendicular to the target. Figure out how much it must tip it's engine in order to zero out this component of it's velocity and then clip this to the maximum that it can tip it's engine.

During the first part of it's flight it's going to move somewhat to the right of the straight line in figure #2 but as it flies the engine will zero out this component and it will end up heading straight for the target.

Note that in this scenario there will be only one frame in which the engine has a deflection of anything other than zero or max. If you were tracking a moving target you could get lesser deflections on every cycle as the target moved.

# Answer
> 4 votes
It may not be the elegant solution you are after, but I've found that if I slow the missile, if it's going to miss, as it approaches the target, it effectively tracks and turns quicker and can hit the target. You could increase the turn rate of the missile as it gets closer, rather than reducing the speed, but this might give players a 'wow I'm sure that was going to miss' nasty surprise.

This might not look so great, but it certainly stops the missiles from orbiting, and from the enemy circle-strafing the missile until the fuel runs out.

Here's a demo I've put together of my implementation (the third or forth missile demonstrates this, and again at 1:05) : http://www.youtube.com/watch?v=9uiGMC\_nH2w

You can also increase the accuracy of the missile as it approaches the target too (as it has a closer signature to lock to). This is shown in the video too about a minute in. The red circle shows the actual target of the missile. This gives it a chaotic flight path when at a long range, and then straightens out the closer it gets.

Like I say, it may not be the answer you are looking for, but I hope it helps if just a little.

# Answer
> 4 votes
# Intuition

Here's one way: Let's rotate your diagram.

Now the rocket is a cannonball!

# Physics

It has a fixed acceleration "downwards" i.e. perpendicular to the vector from its firing location to its target. I drew it above as a dashed green line. Let's call that the *reference horizon*. (Note that this reference horizon is constant! The rocket was fired from a fixed position with a fixed position as a target.)

We know (from wikipedia) for a cannonball without air resistance, that `d = v^2 * sin(2 * theta) / g`, where

* `d` is the horizontal distance travelled (distance between firing location and target)
* `v` is the speed the projectile was fired at
* `theta` is the angle as to the horizon the projectile was fired at (*angle of fire direction vector* from the *reference horizon*)

Rearranging the equation for `g` gives `g = v^2 * sin(2 * theta) / d`.

The constant in the cannonball equation, `g`, is *acceleration due to gravity*. We can take it to mean *acceleration due to rocket propulsion*. That's fine too — it's still a *constant acceleration* in a *constant direction*.

# Now what?

Run that equation for `g` when you fire the rocket. It will tell you how much to accelerate the rocket perpendicularly toward the reference horizon, in order to hit the target. Since the direction of that acceleration is constant, an orbit won't form.

Boom.

---
Tags: steering-behaviors, orbit
---


# Question
Title: XNA: Runtime differences in ClickOnce install versus development version
I have a game written in XNA, and I use ClickOnce installers to distribute the game to testers. I keep once computer as a test machine which does NOT have development environments installed, so that I can test the installed version.

We've found a reproducible bug in our game, but the bug ONLY occurs on the non-development machines that use the ClickOnce installer.

The bug is related to some of our code for moving around 3D objects and is not tied to Networking or GamerServices.

Are there known differences in the ClickOnce runtime and the version on dev? Are there any best-practices for debugging something like this?

# Answer
> 2 votes
Have you checked that the assemblies referenced by your program are actually installed via the ClickOnce installer ? It could be that the test machines have this installed by default (such as the XNA Framework) but the non-development machine does not.

A way to check this would be to have a look at your solution and check that all the assemblies that you reference have `Copy Local` set to `True` in their properties. Also check the install directory to ensure there are no differences between that which are being installed on the test machines and the non-development machines.

Also as a side note, if the game isn't crashing out completely (as I would imagine it would if it was looking for an assembly that didn't exist) then it could be that the non-development machine is loading an old version of an assembly. Check the machine for any cached versions of those that you use and clean them out.

A final step might be to log onto your non-development machine as a different user. As far as I understand, ClickOnce installs per user rather than per machine, so you might get a 'clean' install if you try that.

# Answer
> 0 votes
In my case, the issue was that floating-point numbers were rounding slightly differently on all of our dev machines versus the two test machines.

Basically -0.9999999999999 vs -1.00000000001, which caused a rotation calculation to be way off. Something to keep an eye out for!

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


title: MUD source code

text:
# Question
Title: MUD source code
I haven't been able to find a lot of the old, open source mud source codes. I find the way they did things very applicable to text-based/browser based games, and I'd love to be able to skim through parts of 'em for inspiration.

For instance, we have this huge list of muds and the relationships between them, but little by way of access to source code. http://en.wikipedia.org/wiki/MUD\_trees

Often (I'm looking at you, dikumud, http://www.dikumud.com/links.aspx ) the sites of the mud itself doesn't even have a working link to the source.

https://github.com/alexmchale/merc-mud has a copy of merc that I found, which certainly contains other works within it's history, but the pickings seems sparse.

Does anyone have better resources for gaining access to MUD source code than these?

# Answer
http://mudbytes.net/ was established for exactly the purpose you're looking for.
> 14 votes

# Answer
# http://www.andreasen.org/newmud/

**Looks like a good resource, with a list of over 30 different open source MUDs.**

Just for reference I found this by searching Open Source MUD on google.
> 3 votes

# Answer
A bit of an old question, but in case you're looking, there's also this (started out as a simple text adventure engine and is now taking a MUD direction): https://github.com/crankycyclops/trogdor
> 2 votes

# Answer
Not specifically for games, but LambdaMOO (MOO = MUD, Object Oriented) source is available here. You need both the server, which implements networking and command parsing, and a minimal (“core”) database, which implements players, rooms, movement, messaging. To build a new game on top of this, you would build on the core, but you probably won't need to modify the server.
> 0 votes

---
Tags: open-source, source-code, mud
---


# Question
Title: Scaling Skeletal values to be able to reach objects on the screen
I have created a game using Kinect + XNA and the game runs on full screen mode.. However when i try to touch or reach a certain area on the screen using hand.. I cant reach it.. I will already be outside the range of the sensor trying to touch the object on the game screen..

**Is there anyway I can scale the skeletal values so that the users can easily touch objects on the screen without having to stretch or bend too much?**

# Answer
You can get a position relative to the screen resolution, then it's just a matter of tweaking the values to find what works.

From http://kinectxna.blogspot.ie/2012/02/tutorial-5-skeletal-tracking.html :

```
foreach (Joint joint in skeleton.Joints)
{
     Vector2 position = new Vector2((((0.5f * joint.Position.X) + 0.5f) * (resolution.X)), (((-0.5f * joint.Position.Y) + 0.5f) * (resolution.Y)));
     spriteBatch.Draw(img, new Rectangle(Convert.ToInt32(position.X), Convert.ToInt32(position.Y), 10, 10), Color.White);
}

```

Instead of drawing to this position you could use it in your update logic. The values aren't perfect but they should get you on the right track.

Edit:

If in fullscreen you'll want to find the current resolution of the user's monitor. You can find it using:

> GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height

Just put this in place of resolution in the above code and you should be good to go.

If this doesn't work try:

> graphics.PreferredBackBufferWidth
>
> graphics.PreferredBackBufferHeight

Where graphics is the GraphicsDeviceManager (declared in the game's constructor when creating a new XNA game). Depending on the scaling of the game one or the other of these should work.
> 1 votes

---
Tags: xna-4.0, kinect
---


# Question
Title: How to achieve selection of a tile from a tile sheet based on an ID?
Let's say I have a tile sheet that contains 8 sprites per sheet. Each sprite is a tile of 30x30.

I wrote my own custom map parser/map loader however I'm having trouble extracting a certain tile sprite from the file. I'll describe my problem better in order for everyone to understand.

I wrote an enum of materials, each material has a value according to it's location relative to the tile sheet. For example void is 1, grass is 2, rock is 3, etc. So in my tile sheet they are represented as such:

```
+---+---+---+---+---+
| 1 | 2 | 3 | 4 | 5 |
+---+---+---+---+---+

```

Which is equivalent to:

```
+------+-------+-------+
| void | grass | stone |
+------+-------+-------+

```

Basically when rendering, I created a tile class, each tile has 2 coordinates: X and Y (They are calculated automatically) and a material which can be represented either as a number, either as a value (ID). When rendering, I have a vector of sprites which are all taken from 1 file called tilesheet.png, however each of them must only draw a certain portion of the tile sheet, for example say I have something like this:

```
tile coordinateBounds(topLeftX, topLeftY, tileWidth, tileHeight);

```

During the initialization of the map I calculate an array of tiles, and I give each of them their position, their materials based on the values in a map file and a few other variables such as collision. I need to apply the coordinateBounds to each of them according to their material value. For example if the material is grass it should only take the grass sprite from the tilesheet. I must also mention I'm using SFML, and there are no borders or spacing between the tiles.

# Answer
You want to draw the portion of the tile sheet representing the desired material. In SFML 1.6, this can be done by creating a clipping region with a sf::IntRect.

```
sf::Sprite tileSheet;
sf::IntRect clipping;
int frame = 0;              //id of the material you want to draw
int columns = 5;            //number of columns in the tile sheet
int frameWidth = 30;
int frameHeight = 30;

//set the clipping rectangle
clipping.Left = (frame % columns) * frameWidth;
clipping.Top = (frame / columns) * frameHeight;
clipping.Right = clipping.Left + frameWidth;
clipping.Bottom = clipping.Top + frameHeight;

//apply the clipping rectangle to the tile sheet so it knows what portion to draw
tileSheet.SetSubRect(clipping);

```
> 1 votes

---
Tags: c++, tiles, maps, sfml
---


# Question
Title: Ebooks for building game framework in HTML5
I begin to develop game but I don't know best ebooks for build simple game framework in HTML5 . Can anyone suggest ebooks for me and where to get free image resources for build map in game like as Contra, Super Mario, ... such as grass, characters, animals, monsters,...?

# Answer
> 1 votes
I tried this one and it really helped me up understand a lot of things and gae me the basics to start my own games:

http://www.amazon.com/HTML5-Games-Creating-CSS3-WebGL/dp/1119975085/ref=sr\_1\_1?s=books&ie=UTF8&qid=1355543837&sr=1-1&keywords=html+5+games

# Answer
> 0 votes
For your second question, there are plenty of free resources out there.

http://opengameart.org has some good stuff, though some of it may have attribution licenses etc.

Here's a list of places for free art someone compiled, it seems to have something for everyone: http://letsmakegames.org/resources/art-assets-for-game-developers/

---
Tags: html5, assets
---


# Question
Title: Start an animation exported from 3ds Max in UDK
I made a shape in 3ds Max with one bone and I gave it an animation. I exported it and imported to UDK. When I shoot to that shape, I want my animation to start playing.

How can I do this?

# Answer
> 1 votes
If I understood you correctly, your object needs to play some animations when something happens for it.

In UDK, to have some animations, you need to make an `AnimTree` and `AnimSet` node for that object (SkeletonMesh).

For Playing animations that aren't usually for loop ( like: dying, reloading weapon, opening a door, ...), you should ensure you have a `AnimNodeSlot` in your AnimTree as below:

This node should place right after your `BaseNode` and other part of your tree should place next to this node.

Next step go to UnrealScript.

First you should get access to this *AnimNodeSlot* whith its name :

```
var AnimNodeSlot slot;
...
simulated event PostInitAnimTree(SkeletalMeshComponent SkelComp)
{
    super.PostInitAnimTree(SkelComp);
    mySlot = AnimNodeSlot ( Mesh.FindAnimNode('mySlotName')) ;
}

```

And Finally you should select an animation from your *AnimSet* node with its name to play, as follow:

```
mySlot.PlayCustomAnim('YourAnimationName', ... )

```

It's Done. Hope makes sense :)

---
Tags: animation, udk, 3dsmax, unreal
---


# Question
Title: What is the best approach to informing individual GUI objects about the screen size?
I have a problem with designing classes for my game which I create.

In my app, there is:

* the class `CGame`, which contains all the information about game, itself. For example, screen width, screen height, etc. In the `main()` function, I create a pointer to the `CGame` instance.
* the class `CGUIObject`, which includes fields specifying its position and `draw()` method, which should be able to draw an object according to the screen size.
* the class `CGUIManager`, which is a singleton, and includes a list of `CGUIObject`s. For each object, in a list, it calls the `draw()` method.

Now the problem is, each `CGUIObject` needs to know the screen size, which is held by `CGame`. However, I find it inefficient to include pointer to `CGame` instance in every object.

---

For clarity's sake, I'll provide some simple code:

```
class CGame
{
   int screenWidth;
   int screenHeight;
};

class CGUIObject
{
   CPoint position;
   void draw();     // this one needs to know what is a screen's width and height
};

class CGUIManager   // it's a singleton
{
   vector<CGUIObject*> guiObjects;
   void drawObjects();
};

```

And the main.cpp:

```
CGame* g;

int main()
{
   g = new CGame();

   while(1)
   {
      CGUIManager::Instance().drawObjects();
   }

   return 0;
}

```

---

What would be the best approach to provide the screen size to each `CGUIObject`?

# Answer
There are a few decent options:

1. As stated by ccxvii. Pass the width/height of the canvas to CGUIObject::draw();
2. Pass your CGame object to the draw()
3. Make CGame a singleton
4. Redefine what CGame is and store graphics information in something called CGraphicsManager.

But yeah.. keep it simple for now, I'd go with #1 or #2.
> 2 votes

# Answer
I certainly advocate Fabien & ccxvii's advice to keep it simple and passing values to the draw() method is certainly a very logical approach for something small.

In the case of a larger more complex game, you usually have some windows system that helps in abstracting away the OS's windowing implementation. If some other system needs to know if the game window gets resized, it adds a listener that can be used to notify those interested when that happens.

```
struct IWindowListener {
  virtual void OnWindowResized(IWindow* window);
};

class WindowManager {
public:
  void AddListener(IWindow* window, IWindowListener* listener);
  void RemoveListener(IWindow* window, IWindowListener* listener);

  ListenerList& getListeners(IWindow* window);
};

class Window : public IWindow {
public:
  Window(WindowManager* owner) : mOwner(owner) { }
  void AddListener(IWindowListener* l) { mOwner->AddListener(this, l); }
  void RemoveListener(IWindowListener* l) { mOwner->RemoveListener(this, l); }

  // some method that fires when window gets resized by OS
  // This notifies all listeners who have interest.
  void WindowResizeFinished() {
    ListenerList& listeners = mOwner->getListeners(this);
    ListenerList::iterator start = listeners.begin();
    ListenerList::const_iterator end = listeners.end();
    for(; start != end; ++start)
      (*start)->OnWindowResized(this);
  }
};

class GUIManager : public IWindowListener {
public:
  void OnWindowResized(IWindow* window) {
    mWidth = window->GetWidth();
    mHeight = window->GetHeight();
  }
};

// Somewhere in your Game's initializing code
mWindowManager = new WindowManager();
mGUIManager = new GUIManager();

mGameWindow = mWindowManager->CreateWindow("My Game", 800, 600, WNDPOS_CENTERED);
mGameWindow->AddListener(mGUIManager);

```

This allows you to apply things like Separation of Concerns and Single Responsibility Principals to keep your code clean and separated into logical modules.

Again, keep it simple to start is important but realize there are some nice design patterns using the observer pattern shown above that can really make your code look elegant and clean and remain modular, extendable, and easy to maintain.
> 1 votes

---
Tags: c++, gui
---


# Question
Title: Should I be sharing data between graphics and physics engine in the game?
I'm writing the game engine that consists of few modules. Two of them are the **graphics engine** and the **physics engine**.

**I wonder if it's a good solution to share data between them?**

Two ways (sharing or not) looks like that:

## Without sharing data

```
GraphicsModel{
    //some common for graphics and physics data like position

    //some only graphic data
    //like textures and detailed model's verticles that physics doesn't need
};

PhysicsModel{
    //some common for graphics and physics data like position

    //some only physics data
    //usually my physics data contains A LOT more informations than graphics data
}

engine3D->createModel3D(...);
physicsEngine->createModel3D(...);

//connect graphics and physics data
//e.g. update graphics model's position when physics model's position will change

```

I see two main problems:

1. A lot of redundant data (like two positions for both physics and graphics data)
2. Problem with updating data (I have to manually update graphics data when physics data changes)

## With sharing data

```
Model{
     //some common for graphics and physics data like position
};

GraphicModel : public Model{
    //some only graphics data
    //like textures and detailed model's verticles that physics doesn't need
};

PhysicsModel : public Model{
     //some only physics data
    //usually my physics data contains A LOT more informations than graphics data
}

model = engine3D->createModel3D(...);
physicsEngine->assingModel3D(&model); //will cast to
//PhysicsModel for it's purposes??

//when physics changes anything (like position) in model
//(which it treats like PhysicsModel), the position for graphics data
//will change as well (because it's the same model)

```

Problems here:

1. physicsEngine cannot create new objects, just "assing" existing ones from engine3D (somehow it looks more anti-independent for me)
2. Casting data in assingModel3D function
3. physicsEngine and graphicsEngine must be careful - they cannot delete data when they don't need them (because second one may need it). But it's rare situation. Moreover, they can just delete the pointer, not the object. Or we can assume that graphicsEngine will delete objects, physicsEngine just pointers to them.

**Which way is better?**

Which will produce more problems in the future?

I like the second solution more, but I wonder why most graphics and physics engines prefer the first one (maybe because they normally make only graphics or only physics engine and somebody else connect them in the game?).

**Have they any more hidden pros & contras?**

# Answer
> 9 votes
Nowadays, more game engines adopts a component design (e.g. Unity, Unreal). In this kind of design, a `GameObject` is composed of a list of components. In your situation, there can be a `MeshComponent` and a `PhysicalComponent`, both attaching to a single game object.

For simplicity, you can put a world transform variable to the `GameObject`. During update phrase, `PhysicalComponent` outputs the world transform to that variable. During rendering, the `MeshComponent` reads that variable.

The rationale behind this design is to decouple between components. Neither `MeshComponent` nor `PhysicalComponent` knows each other. They just depends on a common interface. And it can be easier to extend the system by composition, than using single hierarchy of inheritance.

In a realistic scenario, however, you may need more sophisticated handling between physics/graphics synchronization. For example, the physics simulation may need to be run in fixed time step (e.g. 30Hz), while rendering need to be variable. And you may need to interpolate results from the output of physics engine. Some physics engine (e.g. Bullet) has direct support of this issue though.

Unity provided a good reference of their Components, which worth a look.

# Answer
> 7 votes
Engines usually pick the first option (own physics-mesh and own render-mesh) because they need very different data, both in quality and quantity.

Quality because the physics engine does not care about texture coordinates, normal groups and all this fancy render stuff for instance. Each of them expects the data in a very specific layout coming down to alignment issues, packing, interleaving of data etc.

Quantity because the physics mesh usually has way less triangles, its a simplified version of the high resolution render mesh.

By decoupling both we make sure that we can tweek one, including changing its data-layout for better performance, without corrupting the other. It's way more scalable.

# Answer
> 0 votes
Besides @Millo Yip great answer I would like just to remind you that you will need to share the same data with the Controls module and the AI module and if I'm not mistaken most audio libraries have a notion of the position of the sound emiter so you'll need to share the data with that module too.

# Answer
> 0 votes
As others have said, it's pretty common place that physics has it's internal data state is managed separately from the internal data state of the rendering engine. It's often common to see even the transform data (position/orientation/scale) stored separately from both physics and renderables because it's possible a game object exists which isn't imposed by physics nor is rendered but requires a world position for other mechanics.

How the data gets from physics to renderable is entirely up to you.

You could do this via some inter-subsystem dispatch process using events/messages. You could do this by exposing a public interface of the render subsystem to the physics subsystem so that physics can simply set a particularly renderable's position. Another option is that the renderable subsystem queries the entity for the transform during it's update and does the update of the renderable component's position then followed by drawing.

Naturally, depending on your game a few of these means are going to be more cache friendly and have better performance than others. I wouldn't get caught up too much on a specific way at this point and pick a communication pattern and try it. You can easily rework this part later on to test various means for optimization.

---
Tags: physics, architecture, graphics
---


# Question
Title: Abstract skill/talent system implementation
I've been making small 2D games for about 3 years now (XNA and more recently LWJGL/Slick2D). My latest idea would involve some form of "talent tree" system in a real time game.

I've been wracking my brain but can't think of a structure to hold a talent. Something like

> "Your melee attack is an instant kill if behind the target"

I'd like to come up with an abstract object rather than putting random conditionals into other methods. I've solved some relatively complex problems before but I don't even know where to begin with this one.

Any help would be appreciated - Java, pseudocode or general concepts are all great.

# Answer
> 3 votes
> "Your melee attack is an instant kill if behind target"

The talent system basically consists of a set of rules which need to validate to true before some effect takes place. You could treat the rules like as follows:

```
// Some abstract rule
class IRule {
  virtual bool validate() = 0;
};
class BehindTargetRule : public IRule {}
class IsAttackMeleeRule : public IRule {}

```

Then you have some code which validates each rule and if each rule is true, you trigger specific effects like:

```
// Some abstract effect
class IEffect {
  virtual void apply() = 0;
};
class SetDamageToHealthOfTarget : public IEffect {}

```

You could package these up in something like the following:

```
struct Talent {
  std::vector<IRule*> rules;
  std::vector<IEffect>* effects;
}

```

This allows you to mix/match bits and pieces of talents with one another to give varying talent choices which are similar or have the same rules but different effects based on the type of player, etc.

Now somehow you'd need to interface this with your combat system. Since combat often needs to take into account things like buffs/debuffs, armor depreciation, armor mitigation and so forth, you'd need to interweave those calculations with the effects that the rules trigger if they all validate.

HTH.

---
Tags: java, architecture
---


title: Tutorial on OpenGL texture formats

text:
# Question
Title: Tutorial on OpenGL texture formats
Looking at the documentation glGetTexImage(), one can see that there are plenty of available texture formats.

GL\_TEXTURE\_1D, GL\_TEXTURE\_2D, GL\_TEXTURE\_3D, GL\_TEXTURE\_1D\_ARRAY, GL\_TEXTURE\_2D\_ARRAY, GL\_TEXTURE\_RECTANGLE, GL\_TEXTURE\_CUBE\_MAP\_POSITIVE\_X, GL\_TEXTURE\_CUBE\_MAP\_NEGATIVE\_X, GL\_TEXTURE\_CUBE\_MAP\_POSITIVE\_Y, GL\_TEXTURE\_CUBE\_MAP\_NEGATIVE\_Y, GL\_TEXTURE\_CUBE\_MAP\_POSITIVE\_Z, and GL\_TEXTURE\_CUBE\_MAP\_NEGATIVE\_Z

I've only used GL\_TEXTURE\_2D for the time being.

Is there any place / documentation where one can learn about these other formats ?

PS : and yes, of course, i've googled for it, results are pretty poor

# Answer
> 4 votes
The most comprehensive information can usually be found by reading OpenGL extension specifications:

GL\_TEXTURE\_1D, GL\_TEXTURE\_2D, GL\_TEXTURE\_3D: http://www.opengl.org/registry/specs/EXT/texture\_object.txt (slightly antiquated)

GL\_TEXTURE\_RECTANGLE: http://www.opengl.org/registry/specs/ARB/texture\_rectangle.txt

GL\_TEXTURE\_CUBE\_MAP\_XXX http://www.opengl.org/registry/specs/ARB/texture\_cube\_map.txt

GL\_TEXTURE\_1D\_ARRAY, GL\_TEXTURE\_2D\_ARRAY: http://www.opengl.org/registry/specs/EXT/texture\_array.txt

---
Tags: opengl, textures
---