title: blending alpha textures in gluOrtho2D

text:
# Question
Title: blending alpha textures in gluOrtho2D
i'm doing a simple game/application with some minimal 2d graphics: png textures and ploygons with standard glVertex calls

my setting:

```
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, w, 0, h);
glMatrixMode(GL_MODELVIEW);

glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc( GL_ONE_MINUS_SRC_ALPHA, GL_SRC_ALPHA );

```

code for textures:

```
texture = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, texture)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,     GL_UNSIGNED_BYTE, textureData )
newList = glGenLists(1)
glNewList(newList,GL_COMPILE);
glBindTexture(GL_TEXTURE_2D, texture)
glBegin(GL_QUADS)
glTexCoord2f(0, 0); glVertex2f(0, 0)
glTexCoord2f(0, 1); glVertex2f(0, height)
glTexCoord2f(1, 1); glVertex2f( width,  height)
glTexCoord2f(1, 0); glVertex2f(width, 0)
glEnd()
glEndList()

...

glCallList(newList)

```

i've found this code here: http://disruption.ca/gutil/introduction.html

if i render any texture with glCallList i no more visualize plygons! what could it be? i'm stucking with some combinations of glBlendFunc but i'm getting nothing goos..

# Answer
> 1 votes
I have tested the example2a and it worked without changes. These are the files that I have used:

gutil.py:

```
import pygame

from OpenGL.GL import *
from OpenGL.GLU import *

def initializeDisplay( w, h ):
    pygame.display.set_mode((w,h),pygame.OPENGL|pygame.DOUBLEBUF)

    glClearColor( 0.0, 0.0, 0.0, 1.0 )
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT )

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluOrtho2D( 0, w, 0, h );
    glMatrixMode( GL_MODELVIEW );

    #set up texturing
    glEnable( GL_TEXTURE_2D )
    glEnable( GL_BLEND )
    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA )

def loadImage( image ):
    textureSurface = pygame.image.load( image )

    textureData = pygame.image.tostring( textureSurface, "RGBA", 1 )

    width = textureSurface.get_width()
    height = textureSurface.get_height()

    texture = glGenTextures(1)
    glBindTexture( GL_TEXTURE_2D, texture )
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR )
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR )
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData )

    return texture, width, height

def delTexture( texture ):
    glDeleteTextures( texture )

def createTexDL(texture, width, height):
    newList = glGenLists(1)
    glNewList(newList,GL_COMPILE);
    glBindTexture(GL_TEXTURE_2D, texture)
    glBegin(GL_QUADS)
    glTexCoord2f(0, 0); glVertex2f(0, 0)    # Bottom Left Of The Texture and Quad
    glTexCoord2f(0, 1); glVertex2f(0, height)    # Top Left Of The Texture and Quad
    glTexCoord2f(1, 1); glVertex2f( width,  height)    # Top Right Of The Texture and Quad
    glTexCoord2f(1, 0); glVertex2f(width, 0)    # Bottom Right Of The Texture and Quad
    glEnd()
    glEndList()

    return newList

def delDL(list):
    glDeleteLists(list, 1)

```

example2a.py:

```
import gutil
import pygame
from pygame.locals import *
from OpenGL.GL import *

def main():
    pygame.init()
    gutil.initializeDisplay(800, 600)

    glColor4f(1.0,1.0,1.0,1.0)

    done = False

    cowTex, w, h = gutil.loadImage('put here a correct file path to a png file')
    cow = gutil.createTexDL(cowTex, w, h)
    alienTex, w, h = gutil.loadImage('put here a correct file path to a png file')
    alien = gutil.createTexDL(alienTex, w, h)

    while not done:

        glColor4f(1.0,1.0,1.0,1.0)

        glEnable( GL_TEXTURE_2D ) # enable texture
        glLoadIdentity()
        glTranslatef(0, 0, 0)
        glCallList(cow)
        glTranslatef(400, 400, 0)
        glCallList(alien)
        glDisable( GL_TEXTURE_2D ) # disable texture

        glLoadIdentity();  # reset the MODEL_VIEW matrix

        glColor3f( 1.0, 0.0, 0.0 ) # set color to red
        glBegin( GL_TRIANGLES )
        glVertex2i( 0, 0 )
        glVertex2i( 100, 0 )
        glVertex2i( 100, 100 )
        glEnd()

        pygame.display.flip()

        eventlist = pygame.event.get()
        for event in eventlist:
            if event.type == QUIT \
                or event.type == KEYDOWN and event.key == K_ESCAPE:
                    done = True

if __name__ == '__main__':
    main()

```

Review that your code is exactly the same. Put extreme caution in the identation. If copy and past the code below, convert the spaces into tab. If you try this and have a problem you can write a comment.

# Answer
> 1 votes
OpenGL is a state machine, whenever you set it to a state you need to revert that state after you've used it. You have set current texture to be "texture", once you've called the list you need to restore the 0 texture (no texture state).

Textures aren't stored with display lists, so there's no need to bind them when making lists.

Your code should look like so:

```
//Create lists and fill them up
glNewList(newList,GL_COMPILE)
glBegin(GL_QUADS)
glTexCoord2f(0, 0); glVertex2f(0, 0)
.....
glTexCoord2f(1, 0); glVertex2f(width, 0)
glEnd()
glEndList()

...

//Bind texture and call the list
glBindTexture(GL_TEXTURE_2D, texture)
glCallList(newList)

//Bind another texture and call another list
glBindTexture(GL_TEXTURE_2D, texture2)
glCallList(newList2)

//UnBind texture
glBindTexture(GL_TEXTURE_2D, 0)

//Render any other untextured polygons/triangles in any fashion (Call lists, begin/end)

```

The reason why you had your polygons invisible most probably is that your texture is black/transparent at 0;0 coordinates. And when you draw your polygons they had been using 0;0 texture coords (default).

---
Tags: opengl, 2d, textures, blending
---


# Question
Title: Does XNA's content pipeline alter my FBX files?
Basically I'm trying to export a model in fbx format through the XNA content processor and I'm finding that the model itself is getting modified and being shifted slightly to the right and being scaled down a bit too. I am certain the FBX file being exported by 3D Studio Max is properly alligned at the center and of a larger scale.

If I export an FBX file with more than one mesh in it the exporter seems to work fine, so not sure what's up with that either...

\*Just found that no matter what rotation/orientation I give a model XNAs content exporter seems to reset it to an identity matrix. i.e. I create a long box and give it an angle of 20degrees, XNA resets it to 0 degrees when I draw it...

THis is as it appears in 3D StudioMax: https://i.stack.imgur.com/e0oW4.png

This is how it appears in XNA: https://i.stack.imgur.com/1vOcx.png

Both are being viewed from the same angle and direction but varying distances.

Now what is really odd is if I create another mesh in max, say a box, and export that (along with the original model), it works fine: https://i.stack.imgur.com/SIDg9.png

So long as there is more than one mesh in the fbx model it draws fine, if there is less its orientation which I applied to it in 3D studio max is removed when I draw it.

Here's my code for drwaing the mesh:

```
model.CopyAbsoluteBoneTransformsTo(boneTransforms);
foreach (ModelMesh mesh in model.Meshes) {
    foreach (BasicEffect effect in mesh.Effects) {
        effect.World = boneTransforms[mesh.ParentBone.Index];
        Vector3 cameraPosition = Camera.Get.Position; // new Vector3(0, 0, 0);
        //cameraPosition.X = -Camera.Get.PosX;
        //cameraPosition.Y = Camera.Get.PosY;
        effect.View = Camera.Get.View;
        // Matrix.CreateLookAt(cameraPosition, cameraPosition + Camera.Get.LookDir,
Camera.Get.Up);

        effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4
            , BaseGame.Get.GraphicsDevice.Viewport.AspectRatio
            , 0.01f, 1000000);
        //Matrix.CreateOrthographic(800 / 1, 480 / 1, 0, 1000000);

        //effect.TextureEnabled = true;
        effect.LightingEnabled = true;
        effect.PreferPerPixelLighting = true;
        //effect.SpecularColor = new Vector3(1, 0, 0);
    }

    mesh.Draw();
}

```

# Answer
Moo

The first bone in the model contains the orientation the object had at time of export in 3dsmax. Doing a matrix transform using this bone (to the left of world matrix, matrix multiplication order matters) should orient your model correctly. Eg. If your model's rotation is set to Quaternion.Identity (no rotation) and you transform via first bone, your model should appear with same orientation as you see in 3dsmax.

^^ I found that out the painful way after wondering the same thing, why my models kept showing up backwards...

(3dsmax 2010, exporting as fbx version 200900)

See this snippet from my draw method:

...

Matrix\[\] modelTransform = new Matrix\[gameobject.TexturedModel.Model.Bones.Count\]; gameobject.TexturedModel.Model.CopyAbsoluteBoneTransformsTo(modelTransform);

```
            Matrix worldMatrix = Matrix.CreateFromQuaternion(gameobject.Rotation) * Matrix.CreateScale(mGlobalScale * gameobject.Scale) * Matrix.CreateTranslation(gameobject.Position);

            foreach (ModelMesh mesh in gameobject.TexturedModel.Model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    if (gameobject.TexturedModel.UseTexture) //override the default texture
                    {
                        effect.Texture = gameobject.TexturedModel.Texture;
                    }

                    effect.EnableDefaultLighting();

                    effect.PreferPerPixelLighting = true;

                    //effect.World = worldMatrix;
                    effect.World = modelTransform[mesh.ParentBone.Index] * worldMatrix;

                    effect.Projection = projectionMatrix;
                    effect.View = viewMatrix;
                }
                mesh.Draw();
            }

            //if (gameobject is CompoundUnit)
            //{
            //    ((CompoundUnit)gameobject).ChildObjects.ForEach(child => DrawGameObject(child));
            //}

```
> 2 votes

# Answer
I haven't had this problem with max & FBX. Are you sure your camera positions are equivalent?

Are you still using the transforms even though you only have one mesh? (I'm talking about the myModel.CopyAbsoluteTransformsTo(). And using those transforms in the effect.World property.) Often people will skip this if there is only one mesh but if you do skip it, it can produce a problem like what you are experiencing.

Scale is tricky to get right. It is a combo of setting units properly in max & the exporter. I often simply open the imported FBX in my favorite editor (usually in VS after importing to the project) and scrolling down to the bottom where is sets 'GlobalScaleFactor' and manually setting it there.
> 0 votes

---
Tags: xna, pipeline
---


# Question
Title: Online leaderboard systems for (small/indie) PC games?
Are there any free/affordable systems/libraries out there for adding online features to a small PC game? (most likely, for a small primarily-Windows-based indie game)

I'm not concerned about matchmaking or online multiplayer - but I'm interested in leaderboards, and maybe slightly more advanced features, such as the upload/download of user-created-content (e.g. replays or player-created levels). Maybe even automatic updates or downloadable content?

Whilst it probably shouldn't be too hard to implement at least the very basics from scratch, it seems like a big wheel to reinvent, and a tried-and-tested system would be preferable, to reduce development time, and reduce the chance of gaping security holes. Is there anything in reach of low/no-budget indie developers?

# Answer
> 2 votes
Two options right now (besides roll-your-own)

OpenFeint is in alpha/beta for WP7 (so Silverlight/XNA would be available too). However the signup hasn't progressed beyond an email saying it's coming soon.

OpenXLive is an open version of the XBL leaderboard system. It looks like it's XNA but there are tutorials for Silverlight as well so you can use both.

Both systems have leaderboards, achievements, etc. but at the time of this answer only OpenXLive is actually usable.

OpenXLive: http://www.openxlive.com/

OpenFeint: http://www.openfeint.com/

Hope that helps.

# Answer
> 2 votes
As said, you can use Cocos Live for leaderboards. I used it with android projects (Java and C++). I have rewritten the client part in Java (100 lines). Our C++ client uses libcurl and jansson.

Cocos Live uses HTTP commands (REST + Json). So it can be implemented easily in many langages.

Cocos live pros:

* Leaderboard server available if you don't need yours
* Google App Engine available if you need your private leaderboard servers

Cocos live cons:

* Not complete as OpenFeint/ScoreLoop..

# Answer
> 1 votes
Well, it would be relatively simple for you to roll your own basic system using Google App Engine. You could implement some basic security if needed. Most likely, this is probably what you will need to do unless you find an SDK, like Steamworks, that include such a thing.

Objective-C Solution: Cocos Live is free for leaderboards. I've used it previously for an iOS project of mine. It's a stand-alone library that takes advantage of Google App Engine on it's end. They don't charge you anything until your game is really, really pushing a LOT of scores (then they'll probably ask).

---
Tags: online, leaderboards, pc
---


# Question
Title: Can XNA Content Pipeline split one content file into several .xnb?
Let's say I have an xml file which looks like this

```
<Weapons>
 <Weapon>
  <Name>Pistol</Name>
  ...
 </Weapon>
 <Weapon>
  <Name>MachineGun</Name>
  ...
 </Weapon>
</Weapons>

```

Would it be possible to use a custom importer/writer/reader to create two files, Pistol.xnb and MachineGun.xnb which I can load individually with Content.Load()?

While writing this I realized I could just import a Weapon\[\] list and split them up with a helper, but I'm still wondering if this is possible?

# Answer
Basically: **No**.

The content pipeline transforms a single input file into a single output file. It can also do a single input file plus dependencies, into a single output file. And you can also trigger building of other files into assets.

But it cannot generate multiple outputs from a single file.

This thread on the App Hub forums explains it in more detail. (And may have some ideas for work-arounds.)
> 4 votes

# Answer
Yes, you can.

With the dependency system, you can call

```
ContentProcessorContext.BuildAsset
ContentProcessorContext.BuildAndLoadAsset

```

to make the Content Pipeline build whichever asset you want, and get the external reference to that file. Keep in mind that this isn't very flexible, and all the assets built this way will have the name of the original asset plus "\_0", "\_1", etc. to mark them as dependent from the original.

Also, ContentProcessorContext is an abstract class and you can inherit from it and extend with the functionality you want. So, when you are compiling your specific asset, create a new instance of your custom processor context and let it do its own magic.

Keep in mind that this requires a very advanced knowledge of the XNA pipeline and will be too much effort if you are a beginner.
> 7 votes

---
Tags: xna, pipeline, xml
---


title: Moving from DirectX 10 to DirectX 11

text:
# Question
Title: Moving from DirectX 10 to DirectX 11
I've done a reasonable number of small hobby projects using DirectX 9 but it's time to move to DirectX 11 now.

I have Frank Luna'a book on 3D programming using DirectX 10 but nothing on DirectX 11. I believe they are pretty similar, but was wondering if anyone could enumerate the main differences at a code level that I'll need to be aware of (or point to an existing source).

# Answer
The SDK documentation has a section on migrating to 11 that covers coming from both 9 and 10. There's also the D3D11 features page.

One of the single biggest changes in terms of API shape between 10 and 11 is that 11 moves a bunch of methods from the device itself to a new interface called a device context (`ID3D11DeviceContext` specifically), in order to support the new multi-threading features.

Once you are aware of the change, though, it's quite easy to adapt to: where you would have in 10 called "`someDevice->Draw()`" you will instead get the immediate context for the device and call "`immediateContext->Draw()`."

The other big change is that the Effects API is pulled out of core and made an independent source distribution you must compile and link yourself. You may also notice some D3DX interfaces and functions that have been deprecated or removed.

Beyond that, there are a handful of new parameters to some functions and a handful of extra fields in structures, et cetera. For example, the buffer description object in 11 has an extra `StructureByteStride` field that isn't in 10, and device creation involves passing feature level information. Plus there are the obvious and aforementioned changes in interface names (10s replaced with 11s).
> 15 votes

# Answer
There will be no need to change. Directx11 only adds new features. You will just changing numbers from ID3D10 to ID3D11 etc.

---

DirectX11 adds (if not talking about hyped HW tessalation) Direct Compute: API for the GPGPU, with excelent connection to the graphics pipe line (i cant say this about CUDA, or openCL). And possibility of multiple RW textures and buffers on a pixel shader, which opens lots of new possibilities.
> 1 votes

# Answer
I think the main difference is that, in DX11 the DXFont is gone, other than that it's pretty much as notabene said. You should be fine with that DX10 book. I used that one when moving to DX11 and I had no problems. You will need to go and look at the msdn from time to time though, there are some minor differences in the API a some places IIRC.
> 1 votes

---
Tags: directx
---


# Question
Title: What NPC gets attacked first when attacking an NPC party in an RPG?
Let's say I am in a battle with four trolls, and I have the highest initiative, so I attack first. Should I randomly choose a troll to attack? Proximity to each troll does not matter (it is not a factor in the algorithm). I remember playing an older RPG (I think one of the Final Fantasy games on N64), and the attacks appeared random. You might have one troll that never gets hit, or you might have one that always gets hit. Is there an acceptable standard?

# Answer
> 6 votes
If you don't have a good reason for otherwise, then the player always chooses.

# Answer
> 2 votes
The biggest troll or the most dangerous one.

# Answer
> 1 votes
You could solve an equation to see which strategy is the best.

There are 4 trolls and they all are different. Each one does N damage per second and takes T time to kill. In said example you have 24 possible killing sequences (1-2-3-4, 1-2-4-3, 1-3-4-2, etc..) you can estimate/compute all of them in under 1ms and choose/suggest the best strategy for the player.

Of course it would be nice if player could choose any one he likes to be killed first instead :)

# Answer
> 1 votes
From a realistic-y type PoV:

The heroes aren't really going to know 'oh look, this troll is the most damaged' or 'this one is the largest threat' too much. Mostly since they'll be avoiding getting hit. They're going to attack whatever is closest to them. As such, I would say in the situation like this (H for Hero, E for Enemy)

> ```
>   E1
>
> ```
>
> H1 E2
>
> H2 E3
> E4 H3
>
> ```
>   E5
>
> ```

H1 will go for E2, H2 for E3, H3 for E4.

The other option is totally random, or let the player choose. It's probably easiest to let the player choose to avoid 'whoops, accidentally didn't kill the boss who had 3hp left oh look I am dead'.

# Answer
> 0 votes
There are a bunch of different ways to solve this problem, as others have said. This ranges from a completely random choice to completely player chosen.

One game that has the style of semi-randomness that you were talking about was Ogre Battle 64. All attacks were done without player choice, but you could direct how you wanted your squad to act. The options were autonomous (pretty much completely random), target weakest (try to kill the enemy with the weakest health), target strongest (slowly weaken the opposing squad), or target leader (without a leader, the squad tries to run back to their base).

The kind of system you want depends on the kind of game you are making. The typical Final Fantasy game is not based around large scale strategy, but are more based on the individual tactics of a single fight; allowing for almost complete player choice tends to be the best bet for this style. In a squad based game, like Ogre Battle, you may want to make the player focus more on the strategy, such as where the squads are placed on the map, or which enemies to kill or weaken first.

# Answer
> 0 votes
Depends on how smart you want the decision to be, which is a gameplay design decision - do i want a fluid gameplay where your AI party members automatically pick the correct things to hit on the head so that the player can just do his thing and keep hacking and slashing without being interrupted, or do i want "dumb" party members so that the player has to use his head and make all strategical decisions (maybe even after pausing the game)?

In Dragon Age (might have been done before so don't kill me) for example they've let the player pre-script the behavior of his party members and tell them how to "automatically" make that decision (and others as well).

About the AI picking which one to start striking first - are they all identical and distance doesn't matter? In that case i don't see why not pick a random one. Otherwise some things to take into consideration are which one would be the fastest to kill (least armored, smallest health buffer, already damaged)? Which one deals the most damage? Which one has an ability to heal it's allies? Which one has misc abilities that might be a threat - such as temporary disabling your friendly characters and debuffing them. Based on those and other factors you should make some sort of a score system, you check which troll gets the highest score, and this one gets attacked first.

---
Tags: character, rpg
---


# Question
Title: Is there any way to earn money with an open source game?
I know FreeToPlay games are financed by advertisements and/or selling additional content, but what about an Open Source single player game to which several people have contributed? And how can a fair sharing be determined?

# Answer
> 25 votes
I would suggest that you sell:

* **Distributions of the source:** Build versions of the source code, tools, etc that people can work with. If they are modifying the source themselves then this won't help them, but if they just want to include a dll for example, this can simply things especially if your build process is complex. Another options is to sell incremental revisions of the source and open source previous versions.
* **Art, Basic Levels, etc:** As mentioned above, providing art resources and building block maps, objects, and other assets simplify development for others.
* **Server Rental:** If your game is an open source multiplayer game, you can rent out time on servers you run. This makes supporting the game easier for people building off of your game, and ensures stability (this relies on you of course) for multiplayer games.
* **Advertising:** A no brainer, advertising on your site and support forums could earn you something
* **Support:** While I generally view selling support as evil, perhaps selling room in online training sessions, access to advanced tutorials, or "1 on 1"-ish support wouldn't be so bad (likely more like 1-or-2-on-team but hopefully you get the idea).
* **Microtransactions:** You could sell content in game, or only provide certain content in the "premium" version of the game that YOU built. People building off of the game would have to either go without said content or pay you to include it.
* **Commercial Licences:** While your game could be open sourced for non-commerical purposes, you could require that you be paid a certain amount or a cut of the profits for people planning to sell derivatives of your work.
* **Promotional Items:** If your game gets popular enough, you could sell T-Shirts, etc relating to the original game.
* **Sponsorship Period:** Following along the lines of point 1, you could sell the game for a certain amount of time and THEN open source it.
* **Donations:** Simple--ask for donations to your project (this would probably look bad if you were doing too many of the other things but it may be worth a shot).

I'm sure there are more ways I didn't even think of as well. As for sharing, that's really up to your team and you but as this is an open source project and not something built in a corporate environment it would presumably be split evenly amongst you.

# Answer
> 5 votes
I would start searching the blogsphere to find people who have. Steve Streeting who lead the Ogre project was quite open about his experiences about making money from his open source engine .

Some projects have released older source to stimulate interest and modding after an initial closed-source start. The people at Wolfire  released some source. Introversion have been recently selling code for Multiwinia .

Joining an interest group at IGDA  or BCS  could also be a pro-active step to finding out more, and larger organisations like that may have resources to answer your legal questions about revenue sharing etc.

# Answer
> 4 votes
You could also have people donate/pay for you to work on new features once the game has a following. For instance, if a group of users really want the ability to ride horses in your game, members would donate money to have you put that at the top of the priority list.

# Answer
> 1 votes
It's certainly *possible* to make money with it. At the very least you can ask for donations or distribute a version with advertisements. It will be difficult, and there's no guarantee you can make the same amount of money, but it's possible.

If all the contributors agree, you can always close the source, improve it, and then sell that. That's probably a much better approach.

I'd try to split "fair sharing" based on how much time the various contributors spent on it. It's quite possible nobody involved will be happy with the results and there will be no agreement that can be made. On the other hand, if it's open-source, they also can't stop you from making money off it - selling open-source software isn't illegal as long as you leave it open. If you can come up with a method to make it profitable, then you'd deserve the money earned from it.

Without knowing more about the situation and the game, there's not much more we can say.

# Answer
> 1 votes
The way people like Red Hat make money from open source is by providing support contracts. It's obviously not practical to charge customers like this, but if someone wants to base a game off your code, why not set up a formal support contract?

For more traditional revenue, why not open-source the game code, but charge for content packs and art? If people want to improve your code, or provide their own content, great, but your's is going to be the best, most fun and most professional, natch.

# Answer
> 1 votes
To understand what you can sell you first need to understand what your game consist of and it breaks down to the game engine, client/server engine, art assets, rule/value/balance assets.

So if you want to open source the game and still sell something you have to chose from the above one or more to keep.

Additionally you can also sell the "service" whether it is access in multiplayer games or in game items and so on.

You can also go the donation way based on the promise that you will keep evolving the game.

---
Tags: open-source, monetization, free-to-play
---


title: Rotating coordinate system

text:
# Question
Title: Rotating coordinate system
Lets say that you want to rotate simple cube around fixed point in center.

Is it possible to use such coordinate system, that you need to use only sine and cosine in order to rotate?

I have done some 3d stuff in VHDL, but i screwed whith coordinate system and is not working correct. I need to make rotation that works in at least two axes.

# Answer
> 1 votes
What you are looking for is the spherical coordinate system. Note that you have to be careful what order you apply the rotations in.

A simple overview of some useful 3d coordinate systems is covered here.

A very distilled set of slides on generic transforms is covered here.

Honestly, given your use of VHDL, I would suggest implementing a 4-element dot product (take two vectors of length 4, multiply them together element-by-element, and sum the products), and use that to create a matrix-vector multiply. If you have the general capability, all the rest of affine math for graphics is within your reach.

# Answer
> 1 votes
Hope this helps, but order of operations are important when rotating. You will want to move the object's rotation point to the origin coordinates, rotate it around as many axises as you want, then translate it back into place. That way it will be rotated around that point (its center for example) instead of its position around the origin of the coordinates you are within.

Hope this helps.

---
Tags: 3d, coordinates, geometry, rotation
---


title: Collision with User Input and Object

text:
# Question
Title: Collision with User Input and Object
I am curious on how to handle collision detection involving a moving target and user input. Basing myself in the mobile space, I get events from a set framework, but I do wonder about the amount of lag involved.

Say the object moves faster and faster, then position of the input and the object is very important. What I want to know is what is the best design for handling user input and then also the best way to make sure to accurately work out when the input point collides with the object, keeping threads in mind?

# Answer
Your question is so vague that it cannot really be answered. However, you sound new so I'm going to try and help. Here is what I suggest you do if you truly want to make computer games:

> I am curious on how to handle collision detection involving a moving target and user input... but I do wonder about the amount of lag involved.

Your first question tells me that you really need to read up on your Matrix mathematics, in all non trivial cases it will come down to some small Maths to work out if the users press on the screen was on an object. Usually by firing a projection through your world starting at the camera and seeing if it collides with anything. For Matrix Maths knowledge and vector calculus in general start with this good guide: Vector Math Tutorial for 3D Computer Graphics. (Those sixteen chapters give you the basics and it should take you a few months to learn that properly.)

About the lag issue: Maths on Computers is usually ridiculously fast. If you can find a good way to do it using some Maths then, in general, it will be fast code and result in little in the way of lag. If you suffer more lag despite that then it is probably an algorithmic problem and you should look into Complexity Theory and see if you algorithm are fast enough. All you probably need most of the time is Big-O notation and here is a good introductory tutorial (though there are better notes out there).

> Say the object moves faster and faster, then position of the input and the object is very important. What I want to know is what is the best design for handling user input and then also the best way to make sure to accurately work out when the input point collides with the object, keeping threads in mind?

Once you know the Math, knowing how to handle collisions with 'jumping' objects due to high speed is relatively easy. Ask a new question about that specifically if it does not come easily to you; but only once you have read that Vector Calculus math above.

There is no 'best designs' for handling user input in games, just methods that work well for your particular game. Just try and make the simplest thing that will work and improve them only if you need to.

Now accuracy in video games! That is a real problem and one that requires true concentration and skill, if your game needs a high level of accuracy, and you are using floating point values like 'float' and 'double' to represent things then you will need to learn how to deal with those properly too otherwise you will see serious and subtle problems occur in your games. I would recommended looking at: Comparing Floating Point Numbers and other good articles on the topic too to see if, and how, it will effect you.

As for concurrency, well that completely depends on what parts of your program you think you can make concurrent and how you do it. Just minimise shared state and everything will be easier. There are concurrency best practices out there and they are included in any good concurrency tutorial, the rest is left as an exercise to the reader.

In the future, try and ask smaller questions with more details because it raises the possibility that somebody will be able to give you a definite answer. Keeping that in mind I hope this answer help and you should note that the road to game development if filled with learning many different and new topics so it will take some time but, if you enjoy programming, then it is a extremely fun journey.
> 0 votes

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


title: Represent planet surface in 2d

text:
# Question
Title: Represent planet surface in 2d
I'd like to make game, where one part is managing planet (building cities, factories, roads, etc.) but I'd like to avoid 3D - only what I want is nice 2d. But if I represent planet's surface as a grid, it will be strange to move near poles (if I go up, I won't appear in the bottom of the map, but in the top - only in different place) and it will be hard to have nice terrain (poles will be stretched). Do you have any ideas how to do that?

# Answer
> 9 votes
Games should not be realistic, you can always cut some corners if it makes the game better. Take a look at Ascendancy for example:

*(Original image source)*

You can loop the 2D terrain from left to right and from bottom to top. Like a Civilization map does.

Another option would be to make "unwalkable" polar caps, like we have here on Earth ;-) They will hide the areas of stretched grid.

# Answer
> 3 votes
Section 2 of this paper has some interesting notes on hierarchical triangle models, but you might find more immediately useful material looking at geodesic grids. You need to supply the connectivity information, but that will get you to a good approximation of a sphere.

This paper also has some interesting ideas.

As Krom pointed out, you certainly can setup your own system for connections, allowing for colonization of weird extra-dimensional spaces at the most weird, or simpler structures such as a Halo-ish ring world.

# Answer
> 1 votes
The "proper" way to represent a planet's surface without any special treatment of the poles or any other extreme points is a triangulated irregular network. From there, you can use any of the usual geographical map projections to represent whatever part of the surface you want as a 2D map.

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


# Question
Title: Pros and Cons of AMF in multiplayer flash game?
After trying to use red5 for my turn-based multiplayer game, I've decided to give AMF a try using amfphp, because of the expensive media server hosting solutions. (With AMF all I need is a web server). The game is a simple turn based game. It uses Box2D for physics. Its similar to pool or billiards. More than two users should be able to play in one game 'table'. Is it OK to use AMF in this situation? Also which one should I use? ZendAMF or AMFPHP?

Features: No. of players \>= 2 in each 'room' or 'table', turn-based, multiple rooms.

I've heard games like farmville use AMF. Does zynga's poker game also use AMF? How does one player get info on what the other player is doing? Do they do a timed checking for any changes, similar to polling? How can changes or 'moves' made by one player be updated to everyone? Since the connection is terminated after every request unlike in a socket connection.

# Answer
If you have a normal web hosting, you won't be able to run socket connections. So your game has to constantly fetch the updates from the server by issuing a HTTP request. For a turn-based game this might be ok, but probably won't work if you want to simulate your pool billiard on the server and update the clients (to prevent cheating).

Now as for which AMF implementation to use: AMFPHP is quite easy to setup and get going, but AFAIK it's no longer actively developed. If you have some experience with the Zend Framework (or would like to learn it), definitely stick with the Zend version.
> 1 votes

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


# Question
Title: Handling User Input with Simple Hit Test
Currently in my project, the way I handle user input events is through the OS Framework, then create a generic object - basically combines all types of input: keyboard, mouse, touch, trackball, etc. all together - this object gets queued and then on update gets processed. The queuing of objects is done on the UI thread - created by the OS - and the processing of the queue on another thread - one that I have generated. I handle the threads by using turn-based concurrency.

My problem is I worry about lag of the input events when there are fast moving objects, and I am curious to see if there are better ways of handling the input events then currently?

My current idea, of handling the simple hit test of fast moving objects with user input, is that I try and use the timestamp generated by the event to work out where everything was at that time, but it seem like a lot of work - probably because the way I have implemented everything on the update side - so is there a better way?

I did think about adding a bulk of data on the generic object creation, but there might be a lag between the creation and the actual event - on Java, I have to go through JNI and the generic object is always created on the native side. So I feel that the timestamp is my best solution. If anyone has any better ideas, it would be great to hear them.

# Answer
Well basically I think this is more of a game design then a programming problem. If objects are moving so fast that in between the time of clicking and the time of processing the click event the object has moved so far that the user 'misses' the intended target, then the objects are just moving too fast.

How much time is there between the actual clicking and the handling of the clicking? I assume it's not more than 1/60s (since most update loops update at 60fps). If that is the case then there is no way of fixing this problem, simply because the reaction/response time of a human is not in the range of 1/60s.

If there is more time between clicking and processing then the input will feel laggy for everything the user does, so in that case try fixing the entire problem. :)

(If you're talking about online gaming, then yes this is an unavoidable problem, but the way you phrased it, it sounds like it is all on one machine and then this should never be an issue).
> 2 votes

---
Tags: c++, architecture
---


title: Problem with my model loader?

text:
# Question
Title: Problem with my model loader?
I'm trying to load MD2 models (stolen from Cube) and my loader seems to be loading the models fine, but I can't say the same for the drawing of the model. Here's my code:

```
typedef float vec3_t[3];

struct md2_t
{
    int ident;
    int version;

    int skinwidth;
    int skinheigh;
    int framesize;

    int num_skins;
    int num_xyz;
    int num_st;
    int num_tris;
    int num_glcommands;
    int num_frames;

    int ofs_skins;
    int ofs_st;
    int ofs_tris;
    int ofs_frames;
    int ofs_glcommands;
    int ofs_end;
};

struct md2_vertex_t
{
    unsigned char v[3];
    unsigned char index_normal;
};

typedef short md2_textcoord_t[2];

struct md2_frame_t
{
    float scale[3];
    vec3_t translate;
    char name[16];
    md2_vertex_t vertices[1]; // First vertex of this frame.
};

struct md2_triangle_t
{
    short index_xyz[3];
    short index_st[3];
};

struct md2_anim_t
{
    int first_frame, last_frame, fps;
};

struct md2_animstate_t
{
    md2_anim_t* animation;
    float current_time, old_time, interpol;
    int type, current_frame, next_frame;
};

struct md2_glcmd_t
{
    float s;
    float t;
    int index;
};

#define MD2_IDENT (('2'<<24) + ('P'<<16) + ('D'<<8) + 'I')
#define MD2_VERSION 8

class MD2 : public VertexModel
{
    public:
        MD2(const std::string& Path);
        ~MD2();

        void Draw(timestep_t Time);

    private:
        md2_t m_MD2Header;
        md2_animstate_t m_MD2AnimState;
        md2_anim_t* m_MD2Animations;
        vec3_t* m_Vertices;
        vec3_t* m_InterpolatedVertices;
        int* m_Commands;
        int* m_Normals;

        unsigned int m_TextureID;
        float m_Scale;

        void Interpolate(vec3_t* Vertices);
};

#include <helpers/md2.h>
#include <iostream>
#include <fstream>
#include <exception>

MD2::MD2(const std::string& Path) : m_TextureID(0), m_Scale(1.0f)
{
    std::ifstream File(Path.c_str(), std::iostream::in | std::ifstream::binary);
    if(!File.is_open())
    {
        Debugging::Debugf("Unable to open the file: %s", Path.c_str());
        exit(0);
    }

    // Get the filesize.
    File.seekg (0, std::ios::end);
    int Size = File.tellg();
    File.seekg (0, std::ios::beg);

    if(Size < sizeof(md2_t))
    {
        Debugging::Debugf("Incorrect header for the file: %s", Path.c_str());
        exit(0);
    }

    // Get the header.
    memset((void*)&m_MD2Header, 0, sizeof(md2_t));
    File.read((char*)&m_MD2Header, sizeof(md2_t));

    // Check if the file is actually a MD2 model.
    if(m_MD2Header.ident != MD2_IDENT || m_MD2Header.version != MD2_VERSION)
    {
        Debugging::Debugf("The file %s is not a MD2 model.", Path.c_str());
        exit(0);
    }

    // Allocate memory for the data.
    m_Vertices = new vec3_t[m_MD2Header.num_xyz * m_MD2Header.num_frames];
    m_InterpolatedVertices = new vec3_t[m_MD2Header.num_xyz];
    m_Normals = new int[m_MD2Header.num_xyz * m_MD2Header.num_frames];
    m_Commands = new int[m_MD2Header.num_glcommands];
    char* Buffer = new char[m_MD2Header.framesize * m_MD2Header.num_frames];

    // Read the frame data.
    File.seekg(m_MD2Header.ofs_frames, std::ios::beg);
    File.read(Buffer, m_MD2Header.framesize * m_MD2Header.num_frames);

    // Read the command data.
    File.seekg(m_MD2Header.ofs_glcommands, std::ios::beg);
    File.read((char*)m_Commands, m_MD2Header.num_glcommands * sizeof(int));

    // Read all the data.
    for(int i = 0; i < m_MD2Header.num_frames; ++i)
    {
        md2_frame_t* Frame = (md2_frame_t*)&Buffer[m_MD2Header.framesize * i];
        vec3_t* Vertices = &m_Vertices[m_MD2Header.num_xyz * i];
        int* Normals = &m_Normals[m_MD2Header.num_xyz * i];

        for(int vertex = 0; vertex < m_MD2Header.num_xyz; ++vertex)
        {
            Vertices[i][0] = (Frame->vertices[i].v[0] * Frame->scale[0]) + Frame->translate[0];
            Vertices[i][1] = (Frame->vertices[i].v[1] * Frame->scale[1]) + Frame->translate[1];
            Vertices[i][2] = (Frame->vertices[i].v[2] * Frame->scale[2]) + Frame->translate[2];
            Normals[i] = Frame->vertices[i].index_normal;
        }
    }

    // Free unused memory and close the file.
    delete[] Buffer;
    File.close();

    memset((void*)&m_MD2AnimState, 0, sizeof(m_MD2AnimState));
}

MD2::~MD2()
{
    delete[] m_MD2Animations;
    delete[] m_Vertices;
    delete[] m_InterpolatedVertices;
    delete[] m_Commands;
    delete[] m_Normals;
}

void MD2::Draw(timestep_t Time)
{
    glPushMatrix();
        // Transform the model coordinates into OpenGL coordinates.
        glRotatef(-90.0f, 1.0f, 0.0f, 0.0f);
        glRotatef(-90.0f, 0.0f, 0.0f, 1.0f);

        // Reverse the orientation of front-facing polygons.
        glPushAttrib(GL_POLYGON_BIT);
        glFrontFace(GL_CW);
        glEnable(GL_CULL_FACE);
        glCullFace(GL_BACK);

        // Bind the texture.
        //glEnable(GL_TEXTURE_2D);
        //glBindTexture(GL_TEXTURE_2D, m_TextureID);

        // Interpolate between frames.
        Interpolate(m_InterpolatedVertices);

        // Draw the model.
        int* Commands = m_Commands;
        while(int i = *(Commands++))
        {
            if(i < 0)
            {
                glBegin(GL_TRIANGLE_FAN);
                i = -i;
            }
            else
            {
                glBegin(GL_TRIANGLE_STRIP);
            }

            for(; i > 0; --i, Commands += 3)
            {
                md2_glcmd_t* Command = (md2_glcmd_t*)Commands;

                glColor3f(1.0f, 1.0f, 1.0f);
                glTexCoord2f(Command->s, Command->t);
                glVertex3fv(m_InterpolatedVertices[Command->index]);
            }

            glEnd();
        }

        // Use the original orientation.
        glDisable(GL_CULL_FACE);
        glPopAttrib();

    glPopMatrix();
}

void MD2::Interpolate(vec3_t* Vertices)
{
    for(int i = 0; i < m_MD2Header.num_xyz; ++i)
    {
        Vertices[i][0] = m_Vertices[i + (m_MD2Header.num_xyz * m_MD2AnimState.current_frame)][0] * m_Scale;
        Vertices[i][1] = m_Vertices[i + (m_MD2Header.num_xyz * m_MD2AnimState.current_frame)][1] * m_Scale;
        Vertices[i][2] = m_Vertices[i + (m_MD2Header.num_xyz * m_MD2AnimState.current_frame)][2] * m_Scale;
    }
}

```

# Answer
> 1 votes
The drawing code looks fine - are you sure the loading is?

```
// Read all the data.
for(int i = 0; i < m_MD2Header.num_frames; ++i)
{
    md2_frame_t* Frame = (md2_frame_t*)&Buffer[m_MD2Header.framesize * i];
    vec3_t* Vertices = &m_Vertices[m_MD2Header.num_xyz * i];
    int* Normals = &m_Normals[m_MD2Header.num_xyz * i];

    for(int vertex = 0; vertex < m_MD2Header.num_xyz; ++vertex)
    {
        Vertices[i][0] = (Frame->vertices[i].v[0] * Frame->scale[0]) + Frame->translate[0];
        Vertices[i][1] = (Frame->vertices[i].v[1] * Frame->scale[1]) + Frame->translate[1];
        Vertices[i][2] = (Frame->vertices[i].v[2] * Frame->scale[2]) + Frame->translate[2];
        Normals[i] = Frame->vertices[i].index_normal;
    }
}

```

To me it looks as if the indexing is wrong - shouldn't you index `Vertices[vertex][0]` rather than `Vertices[i][0]`?

*Besides*: you don't need to take the OpenGL command list from the MD2 file - MD2 files also contain a regular list of triangles with indexes into the texture coordinate and vertex arrays.

I mention it because I took this path when I wrote a MD2 loader. I found this data much more convinient than a pre-optimized OpenGL stream, but it surely depends on the application.

---
Tags: c++, opengl, 3d, models
---


# Question
Title: How do I calculate the forces exerted by a taut wire wrapping 2D objects?
Assume I have a physics primitive I am going to call a "wire", wrapped around a 2D environment (as described in this question).

Here's an illustration of what that might look like:

In the example illustration: The box is being pulled upwards (held up) by the wire, and the box is pulling the wire downwards. The object on the spring is being pushed downward by the wire, but is also pushing the wire upwards.

While I haven't figured out how to implement it yet, assume the wire will slide freely across the points that it is wrapped around.

**In a 2D physics simulation (ie: frame based) how do you calculate the forces (or impulses) to apply to the objects that are attached to or wrapped by a wire like this?**

---

As I alluded to in my first question, I imagine that if the only non-static object "on" the wire was the mass at the end, then the force would be identical to a fixed-length joint between the mass and the point before that on the wire.

# Answer
> 9 votes
The box pulling on the wire applies a tension to the wire. Tension is a force, measured in Newtons. If we make some simplifying assumptions (no friction between wire and environment) then the tension is the same at all points along the wire.

If we consider your example to be static, then the tension on the wire is just the weight of the box:

```
T = m * g

```

where m is the mass of the box and g is acceleration due to gravity (i.e. 9.8 m/s^2). Note this is only valid in the static case, see below for an explanation of how to calculate it in the dynamic case.

The force at each bend in the wire is then just the projection of the tension onto the relevant direction. For example the force at the tip of the spring object is a force along the contact normal, of magnitude:

```
F = T * cos(angle between wire and contact normal)

```

In this case the contact normal direction would be the bisection of the angle between the wire segments. The force at your second marked point on the environment is irrelevant, since it has no impact on the tension or anything else.

Now, in the dynamic case the tension is simply the constraint force which you apply to the box in order to keep it attached to the wire. So if the physics engine is impulse based, the tension is just:

```
T = impulse / timestep

```

This leads into the general algorithm for wrapping the wire around the environment too. The important property is the total length of the wire. Only the last segment needs to be simulated, all the earlier segments can be considered to be fixed. So the length of the last segment is known, just subtract the lengths of the earlier segments from the total length. Then the last segment can be a simple spring constraint. Then just split a segment whenever it intersects with the environment, and remove the split when the bend straightens out.

# Answer
> 4 votes
I definitely appreciate your frustration in these wire-based threads, it's a hard problem to solve. We never got collision working perfectly, but the constraint simulation is definitely doable and straightforward.

A wire constraint is actually almost identical to a regular distance constraint. Instead of two constraint points you have n+1 for a wire with n segments, one for each vertex -- at the end points the Jacobian is identical to a distance constraint (i.e it's something like d/|d| where d is the vector between points), and for the internal nodes the Jacobian is something like (a/|a| - b/|b|) where a and b are the vectors from the node to the adjacent nodes. (Sorry, it's been a couple years since I touched this...)

You can't fake it a-la "only the last segment is dynamic" because, as in your example, objects can interact with other segments, but you only need to simulate masses at the ends of the rope -- internally the rope can be massless. The constraint impulses calculated at each node need to be applied to the object that's colliding at that node.

Here are a few related papers:

The first three are relatively recent and should help a lot. Page 75 of the bottom paper describes a "multibar" constraint which is essentially a wire.

Good luck :)

raigan

# Answer
> 0 votes
The basic idea is that the length of the rope remains the same. If it's being pushed up, you will need to create a "split point" there. Then the rope determines on which side it's attached, because it can't "grow" in that direction. Because it's attached to something on the right, the piece of rope on the left will become shorter and the piece between the split point and the attached point will become slightly longer. Then, like Niall said, calculate the tension of the wire. How I would do this is to calculate the tension of each "piece" of rope. You can then use this to determine the forces involved.

Hope this helps.

---
Tags: physics, rope-physics
---


# Question
Title: Mobile game monetization idea - pay to remove ads?
Has anyone tried a free app/game with Apple's iAds with an in-app-purchase to remove the ads? Just wondering if this works. A friend mentioned that some apps do this... is this a common and/or "user-friendly" monetization method? Assume the ads are "tastefully" on the home screen and not in the actual game itself.

# Answer
> 3 votes
I can say that I will prefer an ad-free version and I will pay after trialling the game.

Not just games, but other apps too, will often have small ads that take up some room on the top or bottom of the screen. For games, these are usually on titles/game over screens. As long as they do not restrict the game itself, they can be good.

Instead of an in-game purchase, it may be better to have the standard (well, commonly used) Lite and ad-free versions of the game. If you do this, you can also take some content away for the free users.

Either way you go, people do not want to pay for a game and still have ads.

# Answer
> 2 votes
why would anyone pay to remove an ad they see for only a few seconds during startup of the application? Or are you planning to have the browse through 10 minutes of advertising before they're able to start playing unless they pay up? Because in that case you won't get many users at all, they'll just uninstall and try something else.

# Answer
> 2 votes
The best method to solve this type of problem: **try it and see!** Just give it a shot, it might work and it might not but actually doing it is the only way to know. Then write a blog post when you are done so that others know for the future.

# Answer
> 2 votes
It's hard to say in general. For myself, I hate looking at ads and would happily pay once to remove them forever, assuming the application is otherwise something I'd be interested in. The apparent success (although I have no hard numbers) of games and other products on the app store that offer both free, ad-supported versions and paid, ad-free versions imply to me that the concept is viable in theory.

In practice, you probably need to make sure the balance of when and how long the ads are displayed (which impacts your expected impression and click-through count) is reasonable. You want users to see them as often as possible without making them too offensive. If they are seen rarely, users may not see value in paying to remove them, *and* you'll get fewer impressions and click-through instances.

You also don't want to sacrifice the quality of the application itself in order to leverage ads; what I mean is, you mention in a comment to another answer that:

> The user would see the ads everytime the game ends and the homescreen is displayed. Since it's a casual game that's replayed often (in theory) the user would see the ads for a non-trivial amount of time.

This sounds to me like quitting/back-button'ing out of your app will take me back to the home screen when I re-launch it, and/or that I will be forced to spend at least long enough on the game-end screen for the ad to download and display for a second or so (in order to guarantee I have really seen it and encourage me to click).

When you remove the ads from this scenario, you are saying that the game doesn't save my state if I have to quit it (which I would expect a casual game on a mobile platform to do) and that you're going to hold me at the end-game screne for a potentially unpleasant period of time. If the game *does* save state between invocations, you're drastically reducing the time I'll spend at the home screen.

In short, I think conceptually this is a workable plan, but I feel like your specific implementation plan may not be as optimal for you or your customers as it could be.

---
Tags: mobile, ios, monetization
---


# Question
Title: Are there companies that can store the stream of each user event?
I want a company that can store in a database of it's own the stream of clicks each user does (my game is programmed in action script), of course I will define what data and when to store it. Bear in mind that I am talking about a game that will have millons of users a day.

# Answer
I think you mean you want a library or application. Not a company; that is, a business.

And you are being seriously over-optimistic. Even World Of Warcraft will not reach 1 million unique users a day.

As for the technical aspect, you're going to need:

* Some server to host the database. Expect to pay a lot for some 30 million people a month using it.
* Some database to host on the server. I would look up SQL databases.
* Flash access to said database, sending the user and their 'stream of clicks'. Each time they click.
> 1 votes

# Answer
There are companies out there that can host a database, sure, but you'll have to be the one to design the database and then collect and store the data. You will have to implement that kind of collection into your game.
> 0 votes

---
Tags: flash, databases, events
---


# Question
Title: Search gamedev companies and vacancies by game genre
My favourite game genre is quest/adventure and I am a C++ game programmer and game designer from Europe.

I visited a lot of job search & employment websites, but did not find any with a function to search a company by genre preferences. Such prefered genres are defined by company's released titles, current active projects, etc.

Do you know such companies or search sites? Which search strategies would you recommend?

# Answer
> 7 votes
This data is hardly standardized. On top of that, most companies aren't completely open with what they're working on. Just because company X shipped a certain kind of game in the past, doesn't mean they're working on that kind of game now or in the future. I mean for some companies it's pretty obvious, but for others not so much.

So I doubt you'll find such a site.

Personally I'd much rather find a place that has a corporate culture I'm interested in than one that's working on some predetermined type of game.

# Answer
> 3 votes
Not only are games difficult to fit into genres as such, studios do not always produce just one kind of game. Even further, I doubt you'll find it significantly more interesting to produce one kind of game over another with time in the industry.

Your best shot with this is to look up a company with a vacancy, that you would like to work for (take Frictional Games for an example), and check up their previous titles (Amnesia, Penumbra) and their genres (horror/survival).

As a general rule, if you do not have the time to check up a bit about the company, I doubt the company will care much for you since you don't have the time to put some effort in.

# Answer
> 2 votes
http://gamedevmap.com/ has break down by very very granular "genres". Bit of a stretch, but thats about the best you are going to find. Aside from MMO vs. non-MMO (and even that distinction is dropping slowly) companies rarely only handle one kind of game.

For programmers and artists the actual genre of the game, if that work even means anything these days, has zero impact on the job, and for designers there are still much bigger factors you should look at (these days the casual\<-\>hardcore\<-\>serious spectrum is probably the first thing I would look at as a designer).

Also if you think you would only be happy working on one type of game then I'm sorry to tell you that this industry really isn't for you.

# Answer
> -3 votes
You do realise that when you're in game development you won't be playing many games? That most likely you'll quickly come to loath playing games because you have to test little bits of them over and over again to analyse errors?

You seem under the impression that working at a game development shop means you're just going to be paid to do what you like to do now, play a certain genre of game when and how you like to do it.

Nothing could be further from the truth. You're going to be spending a lot of time not playing games but in exhaustive meetings about minute details about them. The rest of the time will be spent working on implementing or testing those minute details, and if that includes any playing it'll be playing the same little bit of the game over and over again to test that little detail you happen to have been assigned to working on. It's a job no different from any other, and any job can quickly destroy what enjoyment you have in the thing you're doing. Which is why I always advise people to NOT try to turn their hobbies into their jobs.

---
Tags: game-industry, jobs
---


# Question
Title: How can I get voice recognition features into the Unity Game Engine?
How can I get voice recognition features into the Unity Game Engine? Is there a plug-in or a framework (hopefully freeware) that I could use? If so, do you have any ideas on how to install it? Also, how much of a problem would there be with background noises in the game interfering with the voice inputs into the game? Are there any examples of games on the market that use this? (besides for Spain 3D for the Torque Game Engine).

# Answer
Unity3D doesn't have any direct support for voice recognition. You would need to write an extension (System.Speech.Recognition) or find some kind of plug-in to get you rolling. If you do end up going this direction you will lose out on the unity web player compatibility with your project.

I do not see any plug-ins that are already developed for this purpose.
> 5 votes

# Answer
Community Core Audio is looking pretty promising. It converts voice to text and is said to handle automatic speech recognition. The data is sent via the network through UDP so it would be easy to integrate into Unity. That is if you're not planning on using the webplayer.

http://nuicode.com/projects/cca-alpha
> 1 votes

---
Tags: unity
---


title: Java game in a day or two

text:
# Question
Title: Java game in a day or two
We are **three people** who are going to make a simple game in Java as a school project (University, first year). The game has to be object oriented. We don't have much time, **10-20 hours** tops. None of us has any experience in game development, but we all have fair skills in Java.

We can choose exactly what kind of game, and that is where the problem lies. How high should we aim? There is a competition involved, so we do want to make the best game in the time we have. Is a 3d game unrealistic? Should we use any game-engines/libraries? What kind of functionality should we avoid?

# Answer
**Avoid 3D**, because you would need to know how to make 3D models or find good ones, you would need to know how to load such models (often an epic task in itself, sadly), and how to draw them on the screen (e.g. OpenGL or DirectX takes a lot of work for little gain, and even an engine like jMonkeyEngine requires knowledge of how to utilize the engine, along with basic 3D knowledge). Blitting 2D images on screen and moving them around is far simpler than dealing with vertices, materials, view matrices, transforms, etc. etc. I think you get the point.

**Stick with the built-in Java libraries and classes: Graphics2D, ImageIO, AWT mouse and keyboard listeners, Canvas, Java Sound API, and so on.** The benefits of sticking with these instead of finding some other library include: you already know them (to some extent), you know they're well tested and stable and generally make sense, online documentation and resources are abundant, and they are portable so you don't have to worry about installing extra libraries with native libraries and all that.

**Build up a little library of code snippets ahead of time.** These would include things like loading an image, drawing the image to a position on screen, scaling the image and other effects, playing a sound, looping background music, bounding box collision detection, drawing text. Also have a skeleton application which opens a Frame (or Applet), adds a Canvas to it, and the canvas's paint and repaint methods should be overridden, and a thread should be looping the canvas repaint method (or a timer calling it). You can learn these things if you search around for `Java 2D game programming`. Assuming you have access to your university's library, you should have a number of good Java game books at your disposal; check them out and skim through them for the above-mentioned snippets, and others I missed.

**Practice source control and division of work with your team ahead of time.** Are you going to use Subversion, Git, Mercurial, or something else? Are everyone's computers set to the same up-to-date version of Java? Create your repository, commit/push some files, make sure everyone has the repository checked out and ready to go on your system. Maybe commit a 'hello world' app and make sure everyone is able to pull and modify and commit it; and make sure you know how to handle merging (whether you avoid it entirely with good communication or pair programming, or you know how to use a merge tool). Or, if you aren't familiar with source control, make sure you figure out a solution that works; whether it's pair programming while the third person does art or sounds, or something else, just make sure to be organized from the start or you'll waste tons of time.

**Bookmark links to websites which provide free media.** There have been quite a number of these type sites listed in other questions here; sites like freesound are perfect for quickly finding useful media to use in your game when you don't have the time to make it from scratch. Bookmark this site of course, so you can ask a question if you get stuck on something. Bookmark forums such as the gamedev.net forums so that you can search them for answers. If you opt to use a third-party library, bookmark their website. Organize these bookmarks into folders and grab as many as possible, and make sure to share them so that all three of you have the same useful library of bookmarks. It doesn't take a lot of time to go around and collect these bookmarks and organize them by type/subject, but it saves you a lot of time when you don't have to remember all those websites in the middle of your project.

For more suggestions, see the answers to my question "How to prepare for a game development competition?".

---

To address the rest of your question... The general advice is: **don't aim high**. However, it can vary widely depending on how prepared you are (i.e. my above suggestions) and your skills in Java. This is largely a personal judgement based on your history, but since none of you have history of making games (and therefore can't judge the time necessary), **aim really really low**. Come up with a really basic idea which can be easily implemented in 2D without any advanced concepts (e.g. avoid pixelwise collisions, crazy physics calculations, particle effects, etc.). But then create a **prioritized list** of the features of the game, in as much detail as possible (e.g. break each feature into as many separate tasks as possible). This way, you simply work your way down the list as far as possible, and if you don't get to some low-priority tasks, it shouldn't be a big deal. This has to be done carefully (you still need a functional game at the end of the time, so there is a minimum set of tasks which need to be done and some tasks depend on other tasks), but in general I think this is the best approach when you don't know how long things will take.
> 23 votes

# Answer
Don't aim too high. Pick something you're interested in and build something simple around that. Example: Maybe you're really interested in learning about a physic-engine. Why not build a physics-puzzle like totem-destroyer or similar? Try to revolve around a core-element and don't include other complicated stuff like A.I., sophisticated rendering/graphics/shaders etc.

Focus on *one* aspect and try to find a game-mechanic that suits that. If you're interested in 3D, your game could be as simple as tic-tac-toe, but focus on getting good 3D graphics on screen.

Don't try to learn too much new stuff at once. Make use of existing frameworks/tools as much as possible.

To round this up, here are some ideas for a "getting started" game: What are good games to "earn your wings" with?

**Update:** Since you're really short on time, I'd reduce the "new stuff to learn" to an absolute minimum. A physics-engine might already be overkill if you never used one before. Also pick a game-mechanic you already know, preferably with a well defined and small ruleset and limited amount of game-states.
> 2 votes

# Answer
If you have no prior experience in writing 3D games, I'd drop the 3D idea immediately. Instead, focus on a simple game-play concept and try to implement it using simple 2D graphics. Make sure you implement the game mechanics *first* \- if you're finished earlier, you can still add sophisticated visual effects.

But a game without gameplay isn't a game while a game without stunning graphics can still be fun.

20-30 work hours is very little time for a good game, so you *really* need to plan and prioritize your tasks carefully or you'll never get to a proper result.
> 2 votes

---
Tags: software-engineering, java
---


# Question
Title: Maximum range of projectile fired at given force and elevation
I've gone over this again and again, and my result is obviously wrong when viewed in-action. Here's the initial formula I converted (first one):

http://en.wikipedia.org/wiki/Range\_of\_a\_projectile

and here's my C# code:

```
float CalculateMaximumRange() {
    float g = Physics.gravity.y;
    float y = origin.position.y;
    float v = projectileSpeed;
    float a = 45;

    float vSin = v * Mathf.Sin(a);
    float vCos = v * Mathf.Cos(a);

    float sqrt = Mathf.Sqrt(vSin * vSin + 2 * g * y);

    return Mathf.Abs((vCos / g) * (vSin + sqrt));
}

```

Does anyone see what I did wrong?

# Answer
> 7 votes
Use degrees instead of radians.

45 degrees is Pi/4 radians ~= 0.785398.

The `y` in your formula should be the object's distance above the ground when it is released. Is the ground 0? If the ground is not at y=0, then y should be:

`y = origin.Position.y + groundHeight`

Finally, are you sure that this formula is giving you what you want? This formula gives the horizontal distance of the object's travel only -- not the distance of the object along the path (which is longer or equal to the horizontal travel).

Based on your response, it sounds like you're actually looking for the maximum possible distance that can be achieved.

To find the angle that gives the maximum possible distance, use this (using your variable names):

```
 a = arccos(sqrt((2*g*y + v*v)/(2*g*y + 2*v*v)))

```

Now you can plug `a` into the equation you already have to find what the distance is at that angle.

Now you have both the angle that produces the maximum distance, and the maximum possible distance itself!

For example: g = 30, y = 3.85, v = 35, gives:

Wolfram Alpha computation.

a = 0.7422637 radians = 42.53 degrees.

Then plugging a into your original formula gives range = 44.517.

---
Tags: physics, projectile-physics
---


title: Naive minmax optimizations

text:
# Question
Title: Naive minmax optimizations
I'm working on a perfect information game in my spare time. I've implemented a naive minmax algorithm for the computer player. I've further optimized it using alpha-beta pruning.

What I'm looking for is next logical steps to improve the speed of the search (currently the computer player searches 5 nodes deep with acceptable time taken).

# Answer
> 1 votes
The most obvious next step is to cache the tree, hang on to the calculations you already made for the branch chosen, and use the time saved by not recalculating it to extend it further.

Depending on how confident you can be that your cost function is accurate, it might be worth trying to improve it. You may be able to semi-automate this using genetic algorithms to improve it by having different versions play against each other.

# Answer
> 1 votes
You mention that there may be more than one AI opponent. Just note that alpha-beta pruning doesn't work for more than 1 opponent (although you can look into Paranoid Search). Next steps are to look at move ordering, branch and bound pruning and transposition tables (which is probably the same as caching mentioned earlier)

---
Tags: ai, optimization
---


# Question
Title: States, actions logic am I doing it right?
Currently I have the follow states:

```
Need To Run
Run
Need To Walk
Walk
Need To Fight
Fight

```

Am I misunderstanding it and mixig possible actions with states ?

I mean, to me Need To Run would either return true of false telling wether I should procced to the Run action or not and same goes for the other needs.

While I am fighitng should I have second FSM to threat what skills it should be using for example if it needs to heal or not ?

For instance inside the fight I would have the another FSM for

```
Need To Heal
Heal
Back To Fight
Use Skill

```

# Answer
> 7 votes
It does seem a bit odd to have Need To Run and Run states.

What might be better is having a Running, Walking and Fighting state. Your finite state machine then checks the appropriate logic (Do I need to run? Do I need to walk? etc) to determine what state to transition to.

Check out Programming Game AI by Example. In that book, there is an implementation of FSMs using the state design pattern. A nice, clean and flexible way of implementing FSMs.

You can find the source for it here: http://samples.jbpub.com/9781556220784/Buckland\_SourceCode.zip

The state specific stuff is actually available freely online, but the book is a solid investment as an introduction to AI. The state explanations can be found here: http://www.ai-junkie.com/architecture/state\_driven/tut\_state1.html

Hope that helps.

EDIT:
Just to add some points regarding your second FSM, I would suggest looking into hierarchical FSMs as that's essentially what you're doing, but the same concept as above applies really. Later on, if you wanted to get really fancy you could use some sort of planner, or even swap it out completely to use behaviour trees. But they're probably a story for another day :)

# Answer
> 1 votes
Sounds like you don't need an FSM, but instead a behaviour system.

Each state becomes a behaviour, and should have a function that returns a priority, with that value being higher the more it wants to execute. So for instance your Heal behaviour would return a high priority when the entitiy is injured, and Fight would return a low priority when there is no enemies around. This priority calculation function is the "need to" state in your current system.

The behaviour that returns the highest value then gets to execute.

It's up to you if the priorities are recalculated at a set time step, and so states could flip-flop rapidly, or if once a state has control it is up to the state to yeild, which may lead to states monopolising control too much but is a bit more "FSM-y".

The drawback of this approach over FSMs is that there are no defined transitions. Depending on your implementation a state may have no say over when it loses control. This could make interfacing with your animation system difficult and may not be a good fit for some problems.

---
Tags: c#, ai, state, fsm
---


# Question
Title: Are there any implemented game controls like a screen (thumb) joystick? - iOS
I'm looking for some open source game controls. Especially I'm looking for a thumb screen joystick to move a character on the screen, something like a touch circle.

Are there any open source implementation of what I'm looking for?

# Answer
There's a button and virtual joystick implementation for cocos2d called "SneakyInput". Here's a tutorial that might help you use it.
> 2 votes

---
Tags: open-source, ios, motion-control
---


# Question
Title: File format for static and animated 3D models
I'm currently writing a 3D game in C++ with OpenGL and I'm coming to the part where to load 3D models in. Therefore I'm looking for popular file formats and techniques to

* display static meshs and
* render animated meshs.

I've already found quite a large number of possible formats and techniques, like keyframe animations, skeletal animation, MD2 up to MD5, 3DS, X, Collada etc. pp.

For simplicity I'd like to use a format (and technique) that allows both, namely static and animated meshs. So my question is if *one* format is suitable for that task and which one you'd suggest. And to clarify a bit: I don't need super-smooth animations or brandnew features.

Sidenote: Because I'm a blender fan (but *not* an expert ;-)) it'd be helpful if it can be used with that -- but of course that shouldn't be the show stopper, here.

# Answer
> 16 votes
Let me propose you to use **Collada**.

It's widely supported by DCC tools and well standardized. It supports skeletal animations and .. well, it does almost everything, including shaders and physics - those won't be relevant for you.

Vertex-based animations such as in the MDL or MD2 formats are more or less a relict of the past. Today, most animations are skeletal animations (i.e. think if smoothly-rigged characters) and the content creation tools are optimized for them.

Blender has a working Collada exporter, but as always, exporting stuff from Blender can be annoying. You may need to try alternative exporters or file formats or hack the scripts manually should you experience problems.

To load Collada, use libraries such as FCollada or ColladaDOM (Don't try to parse it on your own, Collada is a *really* fat XML monster ...). There's also Open Asset Import Library, which loads ~25 file formats, including Collada (and all the other formats you mention). It would be an excellent choice since it aims especially towards game developers and provides its output in a format suitable for real-time rendering. But to be honest: I'm one of its co-authors, so I'm probably a *bit* biased.

**Last but not least**: The file format you use to import your assets should not define the abilities of your engine and the techniques it uses - it should rather be the other way round. Whether your animations are super-smooth is not a question of the import format, it's about which technique you use to animate meshes and how good they are modeled in the first place. The import format should just help you bring your data from Blender into your game.

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


title: 2D XNA game Camera issue

text:
# Question
Title: 2D XNA game Camera issue
I'm currently making a 2D Worm-clone in XNA, and have regrets about the way I've made my camera. I declare my camera in my Main class and the camera follows the player. In my draw I then begin my spritebatch using my camera transformations.

The problem is, EVERYTHING needs to be drawn in Main because they need to be drawn under the camera transformations (unless I send the camera to each classes constructor).

My question is, is there a way to make it so the Camera is basically global over my whole program, everything is "by default" affected by it? Or at least so it's not only in Main and I can have things that draw themselves.

I've searched for tutorials, but they all explain how to make the camera and to implement it in one draw function, not over a whole program with many different entities.

# Answer
> 3 votes
I'm afraid I have to disagree with Andrew on this one. I do recommend the DrawableGameComponent architecture and I would dispute that this, or the services pattern, are particularly 'heavyweight' - I do have other issues, outside of the scope of this question, but performance generally isn't one of them.

Creating a single camera object to provide a view and projection matrix to your drawables is straightforward and allows you to have your objects draw themselves in their own Draw method. This is, by far, the most common way of structuring an XNA project in my experience. At the end of the day your drawables are only maintaining a *reference* to a single object, so there is not much overhead.

How you provide this reference is a matter of taste and whether you are bothered about reusing your code in other projects:

* You can offer the camera through the services pattern and get hold of it in your drawable's Initialize method.
* Pass it in during construction (provided it has already been instansiated).
* Use a public Property of your derived game class (which you retrieve by casting the Drawable's game object reference to the derived game type first)
* Use a Static, as Andrew suggests.

Personally I would suggest one of the first 2 options (via an ICamera interface definition) to neatly decouple your actual camera & drawable implementations for later re-use. Personally I don't believe well structured code is 'fancy' - good code is just good code.

# Answer
> 3 votes
OK, so when you say "Main" I am imagining you mean the class that you derive from `Game`?

There is nothing wrong with calling `SpriteBatch.Begin()` multiple times around your program and passing in your camera matrix to each one.

Presumably each of your gameplay classes has a `Draw` method? I recommend passing either your camera matrix or a class containing your camera matrix into each `Draw` function you are calling. So your `Draw` function in your game class might look like this:

```
protected override void Draw(GameTime gameTime)
{
    player.Draw(spriteBatch, camera);
    foreach(var enemy in enemies)
        enemy.Draw(spriteBatch, camera);
}

```

If your gameplay classes are `DrawableGameComponent`s, well this is a really good reason not to use game components!

Of course, if you insist on using DGC, then passing a camera **class** to each constructor, as you mention, will *work*. But as you've probably discovered, it means you have to figure out how to *store* it in each class - along with quite a bit of code duplication to do so.

You could also use the Services architecture to allow your components to access the camera. But like DGC, this is a very "heavy" architecture. Why write and manage a service, when you can just make your camera global by making it a `public static` member of your game class?

(It's gameplay code. It doesn't have to be fancy. DTSTTCPW.)

# Answer
> 0 votes
You need to create your own Camera "engine". It isn't good to put your camera on Main and force to draw all the entities here. And in the same way, it isn't a good idea to draw everything in the same class. For this reason, you can to create your Camera as an entity or class. This Camera has to be accesible to the rest of the game (static) Draw the object in their own classes (not in main, each object draw itself (or in your render engine class it has)) and when you draw it, call to camera to apply the transformation. Example: public Draw(GameTime gameTime) ... Matrix transform = Game.CameraEngine.Get.... spriteBatch.Begin(...,transform). ....

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


# Question
Title: Where can I find documentation or an example of a C/C++ Plugin for FSX
I want to make a plugin for FSX in C/C++ but all the examples and documentation forward to the SimConnect Examples for FSX.

I want to access USB-hardware from the plugin and for this reason I'm looking for a way to write a plugin in C/C++ which does not rely on the SimConnect interface.

# Answer
I don't know if this helps you with FSX, however documentation for FS2004 modules has always been rare too, so this might be of help.

Here's an example of an FS2004 module: http://pastebin.com/AQG2H0Vc (written by myself, public domain). From my experience the APIs haven't changed that much so with a bit of luck you'll be able to adopt the example for FSX.

Important is the *Linkage* global variable (type *GAUGESLINKAGE*) because it includes the MSFS version (*0x900* in the example) and callback functions that MSFS shall call. I don't remember exactly what *ImportTable* was for, however if you're not writing code for gauges, you may just ignore it for now.

Have you checked the SDK that is shipped with the FSX Pro/Deluxe edition?
> 1 votes

---
Tags: c++, simulations
---


# Question
Title: Different revenue models between developers and publishers?
I am working at a small game studio developing games for iOS and Android. We do the full journey here, from idea to finished product and we have funding to do so. However, with the smartphone market being a bit of a lottery for small developers we are looking into getting into a publisher deal.

What I am wondering now is what kind of different deals one could look at. From what I have gathered from reading a number of articles a common model it is that the publisher pay for the development cost and once the game is released the developer gets about 20% of the revenue. What I am wondering is if there are any other common models used between developers and publishers?

# Answer
In general nature of the Developer-Publisher relationship, it is true that the developer will make the game at a loss to themselves and then receive compensation from the publisher. 20% of the revenue however seems first fairly high to me, and second it is -very- easy to show how very little 'revenue' is being generated by something to make this kind of agreement even more frustrating. You may want to consider alternates that are more tangible or lump sum payments for completion (given), target sales ranges, completion dates met, etc. Also, depending on how long your development cycles are, you might want to negotiate milestone deliverables and payment schedule, so its not an all or nothing sort of deal. Split the development cycle into 3 substantial collections of functionality and upon completing terms of the each deliverable you would receive partial payments towards the development costs.

Another large thing to be aware of, almost every publisher -will- require you to give them ownership of any IP they are publishing, regardless of who came up with the idea. Make sure the terms in that area are well understood by all parties.

Hope this helps.
> 2 votes

---
Tags: publishing, revenue, business-model
---


# Question
Title: How would I abstract a newtork layer for a Java messaging system, and is it worth it?
I'm currently working on an online Java game.I am not an experienced game programmer, having only worked with web applications, so far. Currently, I am building the messaging system between the client and the server, and I came across a big "what if".

Currently, the messaging system uses a custom solution and Java NIO with sockets, but it got me wondering: what if it fails? What if I have to change it all to some other system?

I decided that I should abstract the network layer of my engine, and if someday I need to change it, I'll swap the adapter. Then came two more problems; how would I abstract a network layer, and of course, is it worth the trouble? Will it be a waste of time?

# Answer
Sockets are going to be around for a long, long time, so I wouldn't worry about that. If it is already working for you, that's even better!

For an interesting messaging layer, check out ZeroMQ.

In general, if you construct your game to have a general sort of event-based flow (i.e.,"Client 2 fire", "Client 1 die", "Sound explosion (2,3,1)", etc.) and use that for all interactions, you then reduce your problem to routing streams of events and handling them.

Your networking issue then becomes one mainly of serializing these events to a communications channel (for example, over sockets), and then deserializing these events to an event stream on the client/server. If you make that abstraction, then any change to the networking mechanism (sockets to modems to semaphores to whatever) means that you only will have to rewrite that serialization/deserialization/channel management code.

Hope that helps!
> 3 votes

---
Tags: java, networking
---


title: Sprite sheet or multiple resources

text:
# Question
Title: Sprite sheet or multiple resources
When animating for the Android platform is it a better practice to create a sprite sheet with multiple states for each sprite on a single picture or should I instead export individual images for each character/state/etc.? Which option gives me a smaller file size for resources and which is easier for the programmer to animate?

# Answer
It depends how many you have and how many of those would be in use at any given time.

I would break it down as follows:

For each "sprite" I would have one sheet, each WxH section is a single frame. If there are only a few states, I'd keep those all in the same image file, and just make a map of

1. Walking is sprites 0-9
2. Jumping is 10-15
3. Crouching is 15-20

If you have many states per sprite, I would consider breaking up each state animation into its own file.

If you only have a few sprites and a few states, it might be best to simply have it all on a single image file, and use the maping I have above, but include it per sprite. This will keep the amount of memory usage to a minimum, since you're targeting android, memory is a premium resource and should be conserved where possible.
> 4 votes

# Answer
One of the biggest speed advantages from using a sprite sheet is that you can render multiple instances of the sprite batched with a single draw call. If you do it with individual images then each character (or whatever) on screen is going to be a different draw call unless they happen to be on the same animation frame.

In general you probably want to atlas as much as possible onto a single sheet.
> 4 votes

---
Tags: android, animation, sprites
---


# Question
Title: Any good book on lighting in video games?
Lighting plays a fundamental role into videogames. A videogame without a good ilumination is flat and without life. I'm looking for a book that explains how must be iluminated a scene and what factors are involved in the creation of convincing worlds.

# Answer
> 1 votes
I understand, that you are asking for **artistic way**. Every game engine has few types of lights, at least "point light", "spot light" and "directional light" (and propably ambient light). Those (without area light) can be simulated in realtime in dynamic scene and are typical lights in 3D modelers/renderers (such as Maya, Max or Blender).

**Lighting for a game is no different for lighting for a CGI movie** (maybe with fewer lights). It is typical that lighting in a scene is done by people who studied movie lightening (mean real movies with human beings).

There is one book which is something like a bible for 3D artist lighters:

* **Digital Lighting & Rendering** \- It is worth reading if you are interested in this topic. Doesn't matter if your scene is dynamic or lighting is baked into textures.

# Answer
> 2 votes
Thought I'd throw Real-time Rendering out there as it covers a lot of topics, including quite a lot on different lighting techniques.

# Answer
> 2 votes
There really isn't much in the area sadly. I'm currently writing a thesis on the topic of lighting in video games and why it is so important. If your really looking for it now the best books on the subject are in the areas of film and architecture... that or you could wait around for about 6 months for me to finish.

http://www.moddb.com/tutorials/lighting-in-game-environments-the-hows-and-whys

this is an alright link on a basic jist of games lighting.

# Answer
> 1 votes
I don't know of any books that cover that topic on it's own. However there is a chapter in Introduction to 3D Game Programming with DirectX 10 that covers lighting. The code examples are HLSL as it's a DX book, but the discussion about lighting algorithms is language agnostic. It covers diffuse, specular, ambient, parallel, point and spot lighting.

Essential Mathematics for Games and Interactive Applications, Second Edition also has a nice chapter on lighting.

You could also read these slides published by DICE, they cover various techniques used in battle field 3, including lighting and shadows. It doesn't go in depth, but give a nice overview of some of the things getting done in the industry.

---
Tags: books, lighting
---


title: opengl rotations for a human

text:
# Question
Title: opengl rotations for a human
I currently can rotate around a pivot point by first translating to the pivot point then performing the rotation and finally translating back to the origin. I do that easily enough for the shoulder in my example. However I cannot figure out how to also add in a rotation around the elbow for the forearm.

I've tried the following for the forearm rotation around the elbow:

1. translate to shoulder, rotate, translate to origin, translate to forearm, rotate, translate to origin
2. translate to shoulder, rotate, translate to forearm, rotate, translate to shoulder, translate to origin

Neither work for me. Any suggestions? I'm really stuck on this one.

# Answer
> 2 votes
The transformation that you are describing is relatively simple and as you can see is very difficult to know what steps must be follow to achieve it.

When you solve this, you'll find with more problems with the next transformation. Then I encourage you to use "Hierarchical Transformations", at end of this article is described.

With "Hierarchical Transformations" you save a simple transformation ( a matrix for example ) in each node of the hierarchy. A node can be the arm, other the elbow, forearm, legs, etc. The final transformation is acomplished with the combination of all the simples transformations. Once the system is built, whatever transformation is easy to achieve.

# Answer
> 0 votes
Have you tried doing the forearm transformation first? I think you may just have the transforms in the reverse order.

---
Tags: opengl, opengl-es, matrix, rotation, linear-algebra
---


# Question
Title: Rotating object around circumference of circle
I'm trying to get a lens texture to rotate around the circumference of the circle and although I picked the centre of the circle as the rotating point of the lens it doesn't work.

```
 private float angle;

//Initialize Method
circlePosition.X = vp.X + vp.Width / 2;
circlePosition.Y = vp.Y + vp.Height / 2;

lensPosition.X = circlePosition.X;
lensPosition.Y = circlePosition.Y + 155;

//Load Content Method
circleOrigin.X = Circle.Width / 2;
circleOrigin.Y = Circle.Height / 2;

lensOrigin.X = Lens.Width / 2;
lensOrigin.Y = Lens.Height / 2;

 //Update Method
 angle += 0.005f;

//Draw Method
spriteBatch.Draw(Circle, circlePosition, null, Color.White, 0.0f,
    circleOrigin, 1.0f, SpriteEffects.None, 0f);

spriteBatch.Draw(Lens, lensPosition, null, Color.White, angle,
  circleOrigin, 1.0f, SpriteEffects.None, 0f);

```

# Answer
> 6 votes
You could try

```
private Vector2 Rotate(float angle, float distance, Vector2 centre)
{
    return new Vector2((float)(distance * Math.Cos(angle)), (float)(distance * Math.Sin(angle))) + centre;
}

```

Keep in mind I'm not at a computer I could test this on but that should be in the right direction

Edit: Checked it, works fine

Edit 2: Something else cool you could do:

```
public Vector2 Rotate(float angle, Vector2 currentPos, Vector2 centre)
{
    double distance = Math.Sqrt(Math.Pow(currentPos.X-centre.X, 2) + Math.Pow(currentPos.Y-centre.Y, 2));
    return new Vector2((float)(distance * Math.Cos(angle)), (float)(distance * Math.Sin(angle))) + centre;
}

```

That way you put in the angle you'd like to be rotated to, the position you're currently at and the the central point you'd like to be rotated around

# Answer
> 0 votes
I don't know XNA, but usually the rotation of a sprite is around it's origin. So the lens *position* should be the center of the circle and the *origin* should be `y: lensRadius, x: lensRadius - circleRadius`. That would initially position your lens at the 3 o'clock position (0 radians)

# Answer
> 0 votes
Harold's reply should sort you out, but to clarify, I think the source of confusion here is that "rotating around the circumference" is actually '*positioning* around the circumference'. Passing the angle directly into the spritebatch draw will simply orientate the lens texture around its own centre. Instead you need to use the angle to find the circumference *position* and use that in the draw call. Harold's code snippet should do this step for you if you call it each Update (cheers Harold!).

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


# Question
Title: OpenGL - resize texture when using cubemap
I want to resize my texture. I am using cubemap to compute reflection. I want to use this cubemap to draw skybox. Skybox is drawn but I want to resize texture down, because it is dilated. As I wrote in my previous question (question), to draw skybox I use shaders:

```
//vertex shader
uniform mat4 modelViewMatrix;
      uniform mat4 projectionMatrix;

        attribute vec4 position;
        varying mediump vec4 texCoord;
        void main() {
            texCoord = position;
            gl_Position = projectionMatrix * modelViewMatrix * position;

        }

//fragment shader
uniform samplerCube Sampler;

    varying mediump vec4 texCoord;

     void main() {
         mediump vec3 cube = vec3(textureCube(Sampler, texCoord.xyz));
         gl_FragColor = vec4(cube, 1.0);
     }

```

I send this data:

```
float vertices[24] = {
    -1.0, -1.0,  1.0,
    1.0, -1.0,  1.0,
    -1.0,  1.0,  1.0,
    1.0,  1.0,  1.0,
    -1.0, -1.0, -1.0,
    1.0, -1.0, -1.0,
    -1.0,  1.0, -1.0,
    1.0,  1.0, -1.0,
    };

```

In this order to draw cube:

```
GLubyte indices[14] = {0, 1, 2, 3, 7, 1, 5, 4, 7, 6, 2, 4, 0, 1};

```

I think, that main problem is in the vertex shader, where I use vertex data as texture coord. But I have no idea how to map vertexes to cube map texture coordinates. Can you help me? Thanks

Edit: It is strange, but when I multiply modelviewMatrix with projectionMatrix it does not work. Now my code is:

```
    uniform mat4 modelViewMatrix;
  uniform mat4 projectionMatrix;
  uniform mat3 normalMatrix;

    attribute vec4 position;
    varying mediump vec3 texCoord;
    void main() {

        gl_Position = projectionMatrix * modelViewMatrix * position;
        texCoord = normalMatrix * (gl_Position.xyz);
    }

```

I have attached the screenshot, it looks quite good. Maybe it is distorted, because of the aspect ratio:

# Answer
Texture cubes works differently than regular texturing. Texture cubes are indexed not by indicies on the polygon, but by a direction vector. Imagine that you are in the middle of the cube and texture coordinate are actualy 3D vector pointing to the texture cubes surface.

Resizing texture will not solve anything. You have to somehow change texture coordinates. But this problem doesn't seem to be caused by texture scale problem. It looks more like a too big field of view in perspective matrix, which can cause this problems.

```
//this should be OK.
gluPerspective(45.0f, width/height, zNear, zFar);

```

And the vertex shader should be like this:

```
void main() {
    gl_Position = modelViewMatrix * projectionMatrix * gl_Position;
    texCoord = gl_NormalMatrix * gl_Position.xyz;
}

```

About gl\_NormalMatrix

The matrix multiplication order should be really like this, if this (correct) order doesn't work, there is propably some error on other place...

(*credits: That nice image was stolen from here*)
> 2 votes

---
Tags: iphone, opengl-es, textures, shaders, cubemap
---