# Question
Title: How can I achieve a good fire effect with alpha blending and particles?
Using the following setting for the OpenGL particle effect:

```
SRC: GL_SRC_ALPHA
DST: GL_ONE

```

Creates an additive blend, which looks spectacular on a black background but terrible on brighter colours, as it begines to fade to white.

I then used alpha blending:

```
SRC: GL_SRC_ALPHA
DST: GL_ONE_MINUS_SRC_ALPHA

```

This allows other backgrounds to be used without affecting the color of the particles, but the particles themselves look dull compared to the additive blend. How can I achieve a good fire effect with alpha blending and particles?

Additive:

Alpha:

**UPDATE:**

Following David's advice below, I created a separate texture and then used additive blend on the particle effect before drawing onto the texture. The problem with that is that drawing on an alpha=0 texture resulted in just the coloured parts of the particle appearing in front of my world map, since normally you have a black background instead. The trick was to use two textures. I created a black texture and then drew the particles on it. Then I removed the alpha layer of the particles from this texture, effectively removing all the surrounding solid black and fading out the partially visible particles, while leaving the underlying black as you'd expect when making additive blend particles on a black background. In short, a gruelling process, but I got there eventually:

Here's the thread where I posted my process: http://www.cocos2d-iphone.org/forum/topic/28707?replies=8#post-141528

Video: http://www.youtube.com/watch?v=JptGbEO3b5E

# Answer
I admit I'm not aware of any ideal solution to this problem, so I'll describe a workaround that you may or may not be comfortable with:

1. Render all of the particles using **additive blending** to a *separate* texture (or render target) with its background cleared to *transparent*.
2. Render that texture (or render target) on *top* of your scene using **alpha blending**.

I tried it in Photoshop and here's what I got - It's not perfect, but at least it preserves the original colors better:

Here's the original texture without doing additive blending on the particles:
> 17 votes

# Answer
Have a look at premultiplied alpha.

Link
> 8 votes

# Answer
Have you tried using both? Layer on some particles with alpha blending, which should get your colors the way you want, then come back with some additive blending to get the nice highlight that you're looking for.
> 4 votes

# Answer
As David Gouveia pointed out, there's no satisfying replacement for additive blending on bright backgrounds. The best effect I found (that doesn't require something like rendering to a backbuffer) is to use the following GL blendmode:

```
SRC: GL_ONE
DST: GL_ONE_MINUS_SRC_ALPHA

```

It's not as nice as additive blending, but way better than `GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA`. If you tweak the start and end alpha and color values a bit, you might get results that are really close to additive blending.

In the image above there's `GL_SRC_ALPHA, GL_ONE` on the left, in the middle there's `GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA` and on the right you can see the blend mode I would propose for this setup.
> 4 votes

# Answer
Well first off, the particle images you're using appear to have a black background, resulting in the dark fringes in that second image. Don't do that; that is, don't draw the shape of the particle on the color channels. Instead, the image should be solidly colored and only define the shape in the alpha channel.

Doing that will improve the look of alpha transparency considerably. Then you can further improve the look of the overall effect by having the particles change color over their lifetime. Like, the base image is very bright, giving you that central bright yellow area. Then tint the particles reddish orange and increase the tint over time. That way the particles will darken as they move out from the center.
> 3 votes

---
Tags: opengl, particles, blending
---


# Question
Title: What model file formats are supported in XNA?
What model extensions are valid in XNA? I know it supports `.fbx`, for example.

# Answer
XNA ContentManager can parse ".x" and ".fbx" files. More information can be found here: http://msdn.microsoft.com/en-us/library/bb197848.aspx
> 7 votes

# Answer
By default DirectX can parse ".x", ".sdkmesh", and ".obj" but of course you can write your own parser for any model format or find one online.
> 2 votes

---
Tags: xna, models, xna-content-pipeline
---


title: Decent Shader editor for Visual Studio

text:
# Question
Title: Decent Shader editor for Visual Studio
Is there a decent Effect file editor plugin for Visual Studio? I'm getting slightly frustrated with constantly copying and pasting from FX Composer.

# Answer
NShader provides syntax highlighting for HLSL, GLSL and CG.

They also plan to extend it with the following:

* Add syntax parsing and checking (handling braces, compilation errors... etc.). This requires the definition of parser rules under MPLex and integration in the language service.
* Add compilation checking (using fxc...etc.).
* Add basic render preview window

Though, judging by the check-in history, it doesn't look like those items will come any time soon.
> 4 votes

# Answer
The easiest way to get syntax highlighting/editing assistance is to:

1. Open Up RegEdit.exe
2. Goto "HKEY\_CURRENT\_USER/Software/Microsoft/VisualStudio/10.0\_Config/Languages/File Extensions/"
3. Open up the key ".c", select "(default)" and then right click\>Modify then copy the value.
4. Then make keys for each file extension (include the period) like ".hlsl", ".fx", ".vsh", or ".psh" then select "(default)" and then right click\>Modify then paste the value from ".c" and then you will have C/C++ syntax highlighting.

This is what I use, and will keep using until Visual Studio 2011 Comes Out.
> 3 votes

# Answer
Not in the current version of VS. But VS 2011 will have, see http://msdn.microsoft.com/en-us/library/dd547188%28v=vs.110%29.aspx#BKMK\_GraphicsTools

But I guess that doesn't really help you now :-(
> 1 votes

# Answer
Haven't tried it myself but the GPU based development team at work started using it and rave about it.

http://www.nvidia.com/object/parallel-nsight.html
> 0 votes

---
Tags: xna, shaders, editors
---


# Question
Title: How difficult is it to add vibration feedback to a open-source driving game?
I'm looking to use SuperTuxKart as a basis for a PhD research project. A key requirement for the game is to provide vibration feedback through the controller (obviously dependant on the controller itself). I don't believe that the game currently includes this feature and I'm trying to get a feel for how big a challenge it would be to add.

My background is as a J2EE and PHP developer/architect, so I don't know C++ as such, but am prepared to give it a crack if there are resources and guides to assist, and it's not a herculean task.

Alternatively, if you know of any open source games that do include vibration feedback, please feel free to let me know! Preferably the game would be of the style that the player had to navigate a character (or character's vehicle) over a repeatable course/map.

# Answer
> 6 votes
It appears SuperTuxKart is built using Irrlicht, so the question is in that context. This wiki page shows how to replace Irrlicht's internal input library with OIS which apparently supports force feedback.

Hope this helps!

# Answer
> 0 votes
Well as you said this is mostly dependant on the device you'll be using. My answer will only be theoretical. The most important to make things simple is to be sure that the controller has a public (or not) Sdk or Api that let you bind it with your game engine.

For your second question, my first guess would be XNA which supports natively the Xbox controller. But again this depends on your choice of controller.

# Answer
> -1 votes
Try Rigs of Rods. Great game, and it has force feedback. http://www.rigsofrods.com

---
Tags: c++, open-source, force-feedback
---


# Question
Title: Texturing (or seeing through) the back of a plane
I've got a basic textured quad forming a plane. When I move the camera or rotate the plane to see the back of it, there is no texture there.

The effect I want is as if the plane were a clear piece of glass, so that I'd be seeing the texture from through the other side. I was hoping this was going to happen automagically. Is there an easy way to accomplish such a thing, or am I going to have to manually flip the texture and assign it to the back?

Thanks!

# Answer
By default XNA culls back-facing tris. Use a RasterizerState with the cull mode set to none.

```
RasterizerState stat = newRasterizerState();
stat.CullMode = CullMode.None;

```
> 4 votes

# Answer
To expand on ClassicThunder's presumably correct answer (I don't use XNA), what you are seeing is called backface culling. 3D graphics pipelines usually do this in order to reduce the number of polygons that they have to render; polygons facing away from the camera are usually on the far side of the object and thus not visible.

You can turn off backface culling, or you could duplicate your polygons (with the duplicates located in exactly the same place but with normals facing the opposite direction).
> 1 votes

---
Tags: xna
---


# Question
Title: Is there a simple way to group two or more sprites, so all of them will be dependent on each other?
I think that this question is very similar to this one, but I'm not sure if the answers are universal.

So, my goal is:

* Place two sprites in fixed position, for example player and his eyes
* Make sure that whenever the player rotates, eyes sprite rotates too and gets to the same relative position from the body (so eyes aren't on player's back). So they'll be working as a group. - This step should be automated, that's my goal!

So, for example, I now want to place a gun in user's hands. So now I say, that player is in position `Vector2(0, 0)` and gun is in position `Vector2(26, 16)`. Now I want to group them up, so whenever the player rotates, gun rotates too.

Currently in this example it's pretty okay but in case that I'd need to move my gun on axis y (only), I'm lost

# Answer
**Concept**

I would solve this problem with a *sprite hierarchy* using a varitation of the composite design pattern. This means having each sprite store a list of the children sprites that are attached to it so that any modifications to the parent are automatically reflected in them (including translation, rotation and scaling).

In my engine I have implemented it like this:

* Each `Sprite` stores a `List<Sprite> Children` and provides a method to add new children.
* Each `Sprite` knows how to calculate a `Matrix LocalTransform` which is defined *relative* to the parent.
* Calling `Draw` on a `Sprite` also calls it on all of its children.
* Children *multiply their local transform by their parent's global transform*. The result is what you use when rendering.

With this you'll be able to do what you asked for without any other modifications to your code. Here's an example:

```
Sprite tank = new Sprite(tankTexture);
tank.Children.Add(new Sprite(turretTexture) {Position = new Vector2(26, 16) });

spriteBatch.Begin();
tank.Draw(spriteBatch);
spriteBatch.End();

```

**Implementation**

For starters I'll just drop in a sample project with this technique implemented, in case you prefer to just look at the code and figure it out:

*Note: I've opted for clarity instead of performance here. In a serious implementation, there are a lot of optimizations that could be done, most of which involve caching transforms and only recalculating them as needed (for instance, cache both local and global transforms at each sprite, and recalculate them only when the sprite or one of its ancestors changes). Also, the versions of XNA's matrix and vector operations that take values by reference are a bit faster than the ones I used here.*

But I'll describe the process in more detail below, so read on for more information.

---

*Step 1 - Make a few adjustments to the Sprite class*

Assuming you already have a `Sprite` class in place (and you should) then you'll need to make a few modifications to it. In particular you'll need to add the list of children sprites, the local transform matrix, and a way to propagate transforms down the sprite hierarchy. I found it easiest way to do that just to pass them as a parameter when drawing. Example:

```
public class Sprite
{
    public Vector2 Position { get; set; }
    public float Rotation { get; set; }
    public Vector2 Scale { get; set; }
    public Texture2D Texture { get; set; }

    public List<Sprite> Children { get; }
    public Matrix LocalTransform { get; }
    public void Draw(SpriteBatch spriteBatch, Matrix parentTransform);
}

```

---

*Step 2 - Calculating the LocalTransform matrix*

The `LocalTransform` matrix is just a regular world matrix built from the sprite's position, rotation and scale values. For the origin I assumed the center of the sprite:

```
public Matrix LocalTransform
{
    get
    {
        // Transform = -Origin * Scale * Rotation * Translation
        return Matrix.CreateTranslation(-Texture.Width/2f, -Texture.Height/2f, 0f) *
               Matrix.CreateScale(Scale.X, Scale.Y, 1f) *
               Matrix.CreateRotationZ(Rotation) *
               Matrix.CreateTranslation(Position.X, Position.Y, 0f);
   }
}

```

---

*Step 3 - Knowing how to pass a Matrix to SpriteBatch*

One problem with the `SpriteBatch` class is that its `Draw` method doesn't know how to take a world matrix directly. Here's a an helper method to bridge this problem:

```
public static void DecomposeMatrix(ref Matrix matrix, out Vector2 position, out float rotation, out Vector2 scale)
{
    Vector3 position3, scale3;
    Quaternion rotationQ;
    matrix.Decompose(out scale3, out rotationQ, out position3);
    Vector2 direction = Vector2.Transform(Vector2.UnitX, rotationQ);
    rotation = (float) Math.Atan2(direction.Y, direction.X);
    position = new Vector2(position3.X, position3.Y);
    scale = new Vector2(scale3.X, scale3.Y);
}

```

---

*Step 4 - Rendering the Sprite*

*Note: The `Draw` method takes the parent's global transform as a parameter. There are other ways to propagate this information, but I found this one to be easy to use.*

1. Calculate global transform by multiplying the local transform by the parent's global transform.
2. Adapt the global transform to `SpriteBatch` and render the current sprite.
3. Render all children passing them the current global transform as parameter.

Translating that into code you'll get something like:

```
public void Draw(SpriteBatch spriteBatch, Matrix parentTransform)
{
    // Calculate global transform
    Matrix globalTransform = LocalTransform * parentTransform;

    // Get values from GlobalTransform for SpriteBatch and render sprite
    Vector2 position, scale;
    float rotation;
    DecomposeMatrix(ref globalTransform, out position, out rotation, out scale);
    spriteBatch.Draw(Texture, position, null, Color.White, rotation, Vector2.Zero, scale, SpriteEffects.None, 0.0f);

    // Draw Children
    Children.ForEach(c => c.Draw(spriteBatch, globalTransform));
}

```

When drawing the root sprite there's no parent transform, so you pass it `Matrix.Identity`. You can create an overload to help with this case:

```
public void Draw(SpriteBatch spriteBatch) { Draw(spriteBatch, Matrix.Identity); }

```
> 11 votes

# Answer
You should be able to group them into a SpriteBatch and them move it into place and rotate it using a matrix.

```
var matrix =
    Matrix.CreateRotationZ(radians) *
    Matrix.CreateTranslation(new Vector3(x, y, 0));

SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, matrix);
SpriteBatch.Draw(player, Vector2.Zero, null, Color.White);
SpriteBatch.Draw(gun, Vector2(handDistance, 0), null, Color.White);
SpriteBatch.End();

```

Codes not tested and my matrix multiplication is very rust but the technique holds true.
> 2 votes

# Answer
I would implement this a little differently.

Give your sprite class a list for its children. Then when you update the position and transformations of the sprite, also apply the same translations to the children with a for-each loop. The child sprites should have their coordinates defined in model space rather than world space.

I like to use two rotations - one around the origin of the child (to spin the sprite in place) and one around the origin of the parent (to make the child essentially orbit the parent).

To draw, just begin your spritebatch, call your player.draw() which would draw then loop through all its children and draw them as well.

With this sort of hierarchy, when you move the parent all its children move with it - also allowing you to move the children independently.
> 0 votes

---
Tags: xna, c#, 2d, sprites
---


# Question
Title: How to get window size from within another class?
I have found this post explaining about how to get the size of the Window, but for whatever reason I'm having issues getting it to work inside of a Singleton class that I'm made to manage a set of Objects. Anyone have any examples of getting these values from inside of a singleton?

EDIT: Just in case the question gets asked. I'm using the values for when the Manager instantiate the objects it's managing... So that they don't all start at the same spot and to ensure they start on the screen.

# Answer
**Method 1 - Provide global access to Game**

The simplest way I can think of is to provide global access to your `Game` instance:

```
public class MyGame : Microsoft.Xna.Framework.Game
{
    public static MyGame Instance;
    public MyGame () { Instance = this; }
}

```

After which you can simply do `MyGame.Instance.GraphicsDevice.Viewport.Bounds` or any of the other alternatives Andrew suggested in the other question. This would work from *anywhere* in your application, granted the game has already been created which should always be the case anyway.

---

**Method 2 - Pass a reference to Game to your class**

Alternatively, pass a reference to `Game` to your class. If you're using a singleton class (do you really need to?) and your constructor needs to remain empty, use a separate `Initialize` method instead:

```
public class MySingleton
{
    public void Initialize(Game game) { _game = game; }
    private Game _game;
}

```

After which you can access it as `_game.GraphicsDevice.Viewport.Bounds` from within your class. Don't forget to call `Initialize` when starting the game though (i.e. calling `MySingleton.Instance.Initialize(this)` from within your `Game`).

---

**Method 3 - Make your class a GameComponent**

If your manager inherits from GameComponent or DrawableGameComponent, then it's already guaranteed to hold a valid reference to a `Game` object. You'll need to pass this reference to the constructor when instantiating your manager.

```
public class MyClass : GameComponent
{
    public MyClass(Game game) : base(game) { }
}

```

In this case you can access it as `Game.GraphicsDevice.Viewport.Bounds` from within your class.
> 1 votes

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


# Question
Title: HTML5 multi-player game data/event validation best practices
I'll start by saying that I am fully aware that this question might seem subjective at first, but I'll try and provide a specific test case scenario for it to be a clear question about validating the data received from 2 multiplayer game clients.

**Scenario**

Imagine we have a multi-player Tower Defense (TD) game. And let's assume that the game is built using HTML5 Canvas, Javascript and a multi-threaded web server, for example, Tornado running in the back-end. And in this scenario both of the players have an option to place a turret anywhere they want.

After a turret is placed, a bunch of enemies are released from both sides and move in a straight line towards the other side.

As soon as an enemy reaches turret range, we can assume that it is destroyed in 1-5 shots. If it takes more than that, the enemy safely passes to the other side. Now, my problem lies in the fact that usually I would do all the validation server-side, but it becomes increasingly difficult to do, because I would need to simulate every step of the game.

Instead, I would like to depend on the event data (enemy destroyed/enemy gets safe passage) received from both clients.

**Question**

The main question then is this:

*What is the best and hopefully easiest way to implement these sorts of checks and would there be anything prohibiting me from continuing with the development using HTML5, Canvas and Javascript?*

# Answer
> 3 votes
The most efficient way of preventing cheating is to let both competitors run the same simulation and only have the server run it when and if the players' machines disagree on the result.

This requires a deterministic engine and a precise history of player actions. Thus you should have the players send their orders to the server, have the server give the order a time stamp, and then send it back to both players for execution. The server should also inform players if no actions have taken place in a given time frame so that they can advance their simulation.

For a tower defence game you may want to use a simple engine that runs relatively few simulation steps, and then interpolate those to get fluid animation, thus if the server has to validate the result only the simple part needs to be run.

Node.js is an obvious choice for platform as that makes it easy to migrate client code to the server.

# Answer
> 0 votes
Why not use your game engine (without the visuals) as a server with **node.js** or something similar? Then you could run the simulation server-side and periodically sync with clients, and most of your codebase would be the same for both the game and the server.

Alternatively, if you wish to tunnel only events through the server, I would recommend you to set one client as `the master`, so that after all the events are exchanged, whatever happened on `the master` is final and syncs to other client(s).

---
Tags: multiplayer, html5, html-canvas
---


# Question
Title: Is there a turn-based game service (like GKTurnBasedMatch on iOS) for desktops?
Game Center's GKTurnBasedMatch seems to provide a pretty robust service for handling turn-based games, and OpenFeint appears to have something similar. The problem is, I'd like something like this for the desktop. I was thinking of rolling my own REST-based service on Rails, but after looking at the GameKit documentation, I realized it would take longer than I'd like to make it solid. I don't suppose something like this already exists that I missed in my searches?

# Answer
> 3 votes
Not really, I think you would want to program all the networking stuff yourself, I would make turn based stuff like so:

```
    Server::ProcessNetwork(ClientID p_ID, EOPCODE p_In){
    switch(p_In)
    {
        case OP_NOACTION: // No action would be like a heartbeat to tell the server its still there.
        //user is still waiting
        break;

        case OP_ENDTURN:
        EndTurn(p_ID);
        break;

        case OP_SOMEACTION:
        //perform some action
        break;

        case OP_DISCONNECT:
        // User is disconnecting
        Disconect(p_ID);
        break;
    }

```

Again, just an idea I thought you could use, hope it helps.

---
Tags: server, turn-based
---


title: Making a level editor for my game

text:
# Question
Title: Making a level editor for my game
I am doing a 2D sprite based game in XNA for WP7, The game logic is simple, you start at some point, you want to avoid obstacles and reach a certain goal.

obviously I need to make many levels for the game to be challenging and funny.

I am considering making a level editor for my game where I can be able to design the level using some kind of GUI then it translates that to a `.lvl` or something that the game can read and interpret that to a playable level.

I am asking for an already made level editor for XNA/WP7.

# Answer
> 6 votes
I recommend tIDE its open source written in XNA and comes with a rendering engine, and is an excellent starting point.

# Answer
> 4 votes
I have no first hand knowledge in this field, but here are the "Google answers" to your question.

You could use GLEED2D if you want free form levels, or you could use Tiled Map Editor if you want tile maps.

See also: Tools for creating 2d tile based maps

Depending on your choice of map editor you might be able to find a suitable importer for XNA, otherwise you'd have to write one yourself.

# Answer
> 0 votes
You probably have to make your own editor, so that it will "know" about specifics to your game. I did this too, and I just used straight serialization/deserialization instead of having to code save/load. Saved time, but not terribly portable.

---
Tags: xna, c#, windows-phone-7
---


# Question
Title: Animations in FBX exported from Maya are anchored in the wrong place
We are trying to export a model and animation from Maya into Unity3d.

In Maya, the model is anchored (pivot point) at the feet (and the body moves up and down). However after we have performed the FBX export, and imported the file into Unity the model is now appears to be anchored by the waist/head and the feet move.

These example videos probably help explain the problem more clearly:

We have also noticed that if we take the FBX file and import it back into Maya we have exactly the same problem.

It seems to be that the constraints no longer work after the FBX is reimported back to Maya, which just kills the connection between the joints and the control objects.

When we exported the FBX we have tried checking the 'bake animations' check box.

The fact that the same problem exist when importing the FBX back into both Maya and Unity suggests that the source of the problem is most likely with the Maya FBX export.

Has anyone encountered this problem before and have any ideas how to fix it?

# Answer
> 1 votes
The solution to this was to bake the animations to the rig, and then delete the control objects including the IKs.

---
Tags: animation, unity, maya, fbx
---


# Question
Title: Methods of Creating a "Lightning" effect in 2D
well i'm just wondering on the best way to go about create some form of "Lightning" effect to be used in a game, so for example:

-In my game, i would like to have this effect in the menus and in-game in some form of random weather system perhaps.

Just wondering on the methods available? I did read this blog post: http://drilian.com/2009/02/25/lightning-bolts/

And took a-look at the Lightning sample thats around. I like the method placed in the blog post, just really a bit unsure on how to create the vertices from the lightning segments. I would be great if someone could explain that seconded sub-heading (Adding glow) a bit more to me :).

But like i said, i'm really want to know if there's any other ways i could accomplish this?

# Answer
> 3 votes
Creating quads: http://msdn.microsoft.com/en-us/library/bb464051(v=xnagamestudio.10).aspx. You need only one quad per segment, as in image 9 "lightning vertices" of the linked article you mentioned.

Next, the glow is first created by having a bitmap, a simple circle will do nicely, which blends from hard bright center to soft darker outside, and alpha similarly solid in center and disappearing to edges. Black background works too, depending on shader. A shader with some blend effect smooths things out.

It really is the most impressive lightning effect, doing it with hand-drawn sprites only works if you have a scene for that specific situation.

---
Tags: xna, effect
---


# Question
Title: How do I load Gleed 2D levels in WP7 XNA game?
I've been trying so long to use this modified version of GLEED2D that includes WP7 support,

I'm stuck into loading the level into my game, now my Game1.cs class has the following:

```
    protected override void Initialize()
    {

        Stream stream = TitleContainer.OpenStream("Content/leveltest.xml");
        XElement xml = XElement.Load(stream);
        level = LevelLoader.Load(xml);
        base.Initialize();
    }

```

I included the `XML` file of my level into `Content` Directory, when I try to build the solution, It gives this error:

```
XML is not in the XNA intermediate format. Missing XnaContent root element.

```

I didn't find any reference on how to fix it on the developer's blog or the github WiKi

Any Idea?

# Answer
The problem is that you're trying to **build** the XML file using the *XNA's Content Pipeline*. However, in the source code you posted, the XML file is being loaded at runtime using the LINQ to XML API (*XDocument*) so it doesn't need to go through the content pipeline.

To solve the problem, go to the **Solution Explorer**, browse into your Content project to your XML file, and then on its **Properties**, change the **Build Action** property from Compile to **Content**, and also enable the **Copy to Output Directory** property. See picture below:

This way your XML file will still be copied to the *Content* folder, without being built by the XNA's Content Pipeline.
> 4 votes

---
Tags: xna, c#, windows-phone-7, gleed2d
---


# Question
Title: CGPointMake in Respect to other UIImageViews
I have a `UIImageView` called `hitBox`, and another image called `mainSprite`. So what I want to do is when an `IBAction` is pressed, it will move `hitBox` to above `mainSprite`. I don't know if this is syntax but this is what I know moves things on the screen.

```
hitBox.center = CGPointMake(x coordinate, y coordinate);

```

I just want to replace `x` coordinate and `y` coordinate with something that will place it somewhere in relation `mainSprite`.

# Answer
> 2 votes
Why not `hitBox.center=mainSprite.center` ?

\[edit\]

```
hitBox.center= CGPointMake(mainSprite.center.x,mainSprite.center.y+5);

```

---
Tags: game-design, iphone, objective-c
---


title: How to differentiate a tap from a drag

text:
# Question
Title: How to differentiate a tap from a drag
I'm creating an app and I'm trying to make it so I can drag a sprite (with a second sprite on top) around the screen, but if I just tap the sprite some other method should get called.

I got the dragging working fine when I touch the edge of my sprite, but when I try to drag from the middle of the sprite (where the second sprite is on top) the dragging doesn't work at all, but the tap gets called.

I know why is't doing this, tho, there's conflicting touches from both the sprits because the one on top is swallowing the touch before it hits the second one below it.

How would I be able to implement this where I want the sprite to drag if the finger moves, but I want the tap to register when only a tap is given (IE the finger didn't move on the screen)?

A visual of the sprites I'm working with (if it helps):

The yellow rune is a separate sprite from the stone underneath it (because there's animations involved).

```
--------Touch for the top sprite----------
-(BOOL) ccTouchBegan:(UITouch*)touch withEvent:(UIEvent *)event{
    lastTouchLocation = [RuneScene locationFromTouch:touch];
    BOOL isTouchHandled = CGRectContainsPoint([charSprite boundingBox], lastTouchLocation);

    return isTouchHandled;
}
-(void) ccTouchEnded:(UITouch*)touch withEvent:(UIEvent *)event{
    NSLog(@"Tap received!");

}

------Touch for the bottom sprite--------

-(BOOL) ccTouchBegan:(UITouch*)touch withEvent:(UIEvent *)event{
    lastTouchLocation = [RuneScene locationFromTouch:touch];
    BOOL isTouchHandled = NO;

    // Check if this touch is on the Spider's sprite.
    if (CGRectContainsPoint([current.runeSprite boundingBox], lastTouchLocation)){
        mover = current;
        isTouchHandled = YES;
    }
    else if(CGRectContainsPoint([rune1.runeSprite boundingBox], lastTouchLocation)){
        mover = rune1;
        isTouchHandled = YES;
    }
    else if(CGRectContainsPoint([rune2.runeSprite boundingBox], lastTouchLocation)){
        mover = rune2;
        isTouchHandled = YES;
    }else if(CGRectContainsPoint([rune3.runeSprite boundingBox], lastTouchLocation)){
        mover = rune3;
        isTouchHandled = YES;
    }else if(CGRectContainsPoint([rune4.runeSprite boundingBox], lastTouchLocation)){
        mover = rune4;
        isTouchHandled = YES;
    }else if(CGRectContainsPoint([rune5.runeSprite boundingBox], lastTouchLocation)){
        mover = rune5;
        isTouchHandled = YES;
    }else if(CGRectContainsPoint([rune6.runeSprite boundingBox], lastTouchLocation)){
        mover = rune6;
        isTouchHandled = YES;
    }else if(CGRectContainsPoint([rune7.runeSprite boundingBox], lastTouchLocation)){
        mover = rune7;
        isTouchHandled = YES;
    }else if(CGRectContainsPoint([rune0.runeSprite boundingBox], lastTouchLocation)){
        mover = rune0;
        isTouchHandled = YES;
    }

    // Stop the move action so it doesn't interfere with the user's scrolling.
    //[self stopActionByTag:ActionTagCastingLayerMovesBack];

    // Always swallow touches, GameLayer is the last layer to receive touches.
    return isTouchHandled;

}

-(void) ccTouchMoved:(UITouch*)touch withEvent:(UIEvent *)event{
    CGPoint currentTouchLocation = [RuneScene locationFromTouch:touch];

    // Take the difference of the current to the last touch location.
    CGPoint moveTo = ccpSub(lastTouchLocation, currentTouchLocation);

    // Then reverse it since the goal is not to give the impression of moving the camera over the background,
    // but to touch and move the background.
    moveTo = ccpMult(moveTo, -1);

    lastTouchLocation = currentTouchLocation;

    [self moveActionWithLocation: moveTo];
}

-(void) ccTouchEnded:(UITouch*)touch withEvent:(UIEvent *)event{
    if (!current.isPlaced && mover == current && currentR < Rune6) {
        // Move the game layer back to its designated position.
        CCMoveTo* move = [CCMoveTo actionWithDuration:1 position:curPt];
        CCEaseIn* ease = [CCEaseIn actionWithAction:move rate:0.5f];
        //ease.tag = ActionTagCastingLayerMovesBack;
        [current.runeSprite runAction:ease];

        [current setIsPlaced:YES];
        current.charSprite = [characters objectAtIndex:currentR];
        current.charSprite.position = curPt;
        //charSprite.visible = YES;
        [current performSelector:@selector(fade:) withObject:current.charSprite afterDelay:1];
        [current reorderChild:current.charSprite z:10];

        [self updateCurrentRune:currentR];
        [self updateCurrentCastNum:currentP];
        [self reorderChild:current z:10];
    }
}

```

I tried looking into the UITapGestureRecognizer, but everything I do to try to implement that never works. My layers/sprites won't let me add them as gestures. I also read something about CCGrstureRecognizer or something on the cocos2d forums, but I can't find any documentation on that class, nor can I find out how to actually use it...

Does anyone here know of a way to help me with my issue?

# Answer
I can't tell you about cocos2d specifically, but in general, tap vs. drag is the same input recognition problem as mouse click vs. drag.

The standard way to handle this is to note when a mousedown (or touch) happens, and store where it happened, for later reference. Watch for mousemoved (or touchmoved) events to see if it moves around. If it moves to a position more than a certain distance from the original click/touch (typically 3 pixels for mouse operations -- I imagine that this threshold would be somewhat higher for touch controls), then classify the click/touch as a drag, and start treating it that way (moving objects, etc). If the mousedown/touch is released without ever being converted into a drag, then act on the stored click/touch position as having been a simple click/touch event.

You should be able to implement this simple recognition system entirely within the TouchBegan, TouchMoved, and TouchEnded objective C messages you already have, just by storing a little extra state about each touch.
> 5 votes

# Answer
The iOS is already implementing the detection of tap/drag.

ccTouchMoved is called only when the finger has moved (with a tolerance). So just implement ccTouchMoved in the topSprite. If it's called, you can consider it's drag.

```
-(BOOL) ccTouchBegan:(UITouch*)touch withEvent:(UIEvent *)event{
    lastTouchLocation = [RuneScene locationFromTouch:touch];
    BOOL isTouchHandled = CGRectContainsPoint([charSprite boundingBox], lastTouchLocation);
    dragged=NO;

    return isTouchHandled;
}
-(void) ccTouchMoved:(UITouch*)touch withEvent:(UIEvent *)event{
    NSLog(@"Drag !");

    dragged=YES;
}
-(void) ccTouchEnded:(UITouch*)touch withEvent:(UIEvent *)event{
    NSLog(@"Tap received!");
    if (!dragged) {
        //Follow tap event to the mainSprite
        //...TODO
    }
    dragged=NO;
}

```
> 0 votes

---
Tags: cocos2d-iphone, ios, touch
---


# Question
Title: Creating sideways friction in a 2D top down racer
I've been playing around with trying to create some kind of top down racer but I'm having trouble getting the car to turn properly. At the moment this is the code I have to update the position of the car:

```
var power;
    if (keyboard.upKeyDown) {
        power = 1;
    } else {
        power = 0;
    }

if (keyboard.leftKeyDown) {
    this.rotate -= 0.05;
} else if (this.keyboard.rightKeyDown) {
    this.rotate+= 0.05;
}

this.velocityX += Math.cos(this.rotate) * power;
this.velocityY += Math.sin(this.rotate) * power;

var cDrag = 0.98;
this.velocityX *= cDrag;
this.velocityY *= cDrag;

this.positionX += this.velocityX;
this.positionY += this.velocityY;

```

At the moment the code is very simple, you hold down UP and force is applied in the direction you're pointing which makes it feel like the ship in asteroids.

It seems to me the next thing I need to do is compare the direction the car is pointing with the direction it's actually travelling and apply some sideways force to make it slow down in the sideways direction but also transfer some of that force to the forward direction so it keeps going in the direction it's now pointing.

I'm a bit confused as to how I go about doing this so any advice would be most welcome.

# Answer
*Disclaimer: There are probably other, and better ways to do this. Either way I'll share and describe the way I approached this problem a while back, which ended up working okay for me.*

I've implemented a 2D top-down car game a couple of years ago for a university project, and if I remember correctly I used this article as a starting point, although I ended up simplifying it a lot, and dropped all of that "wheel" modeling stuff in favor of a single body for the car. What I did use however was something similar to the `KillOrthogonalVelocity` method which you can find there, to take care of applying lateral friction.

So, here's **a little video** of what it turned out like. There's a certain amount of sideways friction being applied which also depends on whether I'm using the handbrake button or not, and the car I used for the video also drifts significantly more than the others. This was controllable though. It also had a truck with zero sideways motion and very stiff controls.

I was never completely satisfied with the results, but it was enough for my needs. Bear in mind that I didn't base any of my physics on real vehicle movement or anything. I just tweaked and tried things out until It felt right.

**Sideways Friction**

So, to give a few details on the implementation, basically, when I adapted that method to my project, I added a variable which allowed me to control exactly *how much* of the lateral velocity I would kill, as a value between 0 and 1. This allowed me to fine tune the handling of the car and how much it could drift. Here's the method translated to XNA and simplified:

```
public static void KillOrthogonalVelocity(Car car, float drift = 0f)
{
    Vector2 forwardVelocity = car.Forward * Vector2.Dot(car.Velocity, car.Forward);
    Vector2 rightVelocity = car.Right * Vector2.Dot(car.Velocity, car.Right);
    car.Velocity = forwardVelocity + rightVelocity * drift;
}

```

As you can see I'm using vectors and linear algebra though, not trigonometry, so you'll have to adapt it to your needs. Both `car.Forward` and `car.Right` are normalized vectors pointing in that particular direction.

**Throttle, Brakes, Steering**

Other than that the only other relevant part was how I applied the forces to the car to make it move and steer:

* *Accelerating* and braking was simple. Just a matter of applying a force in the direction the car was currently facing, or its inverse.
* *Steering* on the other hand had a couple of tricks. Steering was done by applying a torque to the car (I used Box2D so this was a simple method call) but the power of that torque depended on a few factors, in particular:

1. When breaking I increased the torque by 25% to make it possible to make sharper turns. `if(braking || handbraking) torque *= 1.25`
    2. When going in reverse, I also reversed the torque in order to get the correct controls. `if(reverse) torque *= -1`
    3. Finally, if the car was going under a certain speed threshold, I made it steer less than usual. `if(speed < 2.0f) torque *= (speed / 4.0f)`

Then just call the `KillOrthogonalVelocity()` method to adjust the final velocity and make it behave less like a spaceship and more like a car.
> 11 votes

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


# Question
Title: Confused about order of operation when using a Matrix in XNA, C#
Here are two different pieces of code

This is what I started with

```
Vector2 hold = Vector2.Transform(pos1, mat1);
Matrix inv = Matrix.Invert(mat2);
Vector2 pos2 = Vector2.Transform(hold, inv);

```

And this is what i'm told is the simplified version

```
Matrix matrix1to2 = mat1 * Matrix.Invert(mat2);
Vector2 pos2 = Vector2.Transform(pos1, matrix1to2);

```

What I don't understand is, why isn't the first line in the simpilifed version

```
Matrix matrix1to2 = Matrix.Invert(mat2)*mat1;

```

Since in matrix order it looks like the matrix on the right would take effect first and in the original we have mat1 being multiplied in first

Another example,

The following image shows the order of operations desired

http://www.riemers.net/images/Tutorials/XNA/Csharp/Series2D/mat1.png

The tutorial says that to create this transformation you use;

```
Matrix carriageMat = Matrix.CreateTranslation(0, -carriage.Height, 0) * Matrix.CreateScale(playerScaling)
* Matrix.CreateTranslation(xPos, yPos, 0) * Matrix.Identity;

```

How could this work if the the order was left to right?

# Answer
Direct3D and XNA typically use a row-vector convention, meaning that when a vector is multiplied by a matrix, it's interpreted as a single row and multiplied on the left of the matrix. So `Vector2 hold = Vector2.Transform(pos1, mat1);` means `hold = pos1 * mat1`. This differs from the column-vector convention in used in OpenGL and in standard mathematical notation, where the vectors go on the right of the matrix, like `hold = mat1 * pos1`.

This means that matrix operations are applied left to right rather than right to left, so a matrix like `mat1 * inv(mat2)`, when applied to a vector, has the effect of applying `mat1` first and then applying `inv(mat2)`.

As for the diagram, it seems to label the transformations in the opposite order to that shown in the code. This is because the tutorial is written in terms of operations on *coordinate systems*, rather than operations on an *object in* a single coordinate system. These are two complementary ways of describing the same sequence of transformations:

1. Reading from right to left, the coordinate system of the carriage is translated, scaled, and translated again as seen in the diagram. Each successive operation occurs relative to the carriage's *local* coordinates. For instance, the scale takes place relative to the carriage's local origin, and the second translation takes place in the scaled local coordinates.
2. Reading from left to right, the carriage itself is translated, scaled, and translated again (in the opposite order) with each operation occuring in *world* coordinates. Here is a modified version of the diagram that shows this:

As you can see, the carriage ends up in the same place, but in the second version the coordinate axes do not move and each operation is taking place in world space.

We are still using a row vector convention here, but these are two different but equally valid ways of interpreting the same transformation: going left to right in world space, or going left to right in local space.
> 6 votes

---
Tags: xna, c#, mathematics, matrix, vector
---


# Question
Title: Does it require any license to use soccer players and teams names in a paid or free game?
I would like to know if any license is required to use Fifa registered team names and player names in paid or free games (e.g. Spanish League teams, Messi, Cristiano Ronaldo names etc).

I'm currently developing an interactive soccer game for mobile platforms (iOs and Android specifically) and I was wondering if it there is any legal issue on using this information. I suppose that if I publish it as a paid-app, it is maybe ilegal without a Fifpro License or something like that. But would it be ilegal if I publish the game for free, and charge for special items in the game?

# Answer
***I am not a lawyer. This is not legal advice. If you are considering this, and any business really it would be wise to seek one.***

Yes.

That you are 'giving it away' doesn't make it any less infringing.

Furthermore, this License is currently held by EA. Giving them, as well as FIFA reason to pursue you. http://en.wikipedia.org/wiki/FIFA\_(video\_game\_series)#FIFA\_World\_Cup\_licensed\_games
> 13 votes

# Answer
Why not give players the option to name players/teams themselves? That way, you avoid copyright issues and players can play with their team of choice. Everybody wins!
> 2 votes

---
Tags: legal
---


# Question
Title: Is using SharpDX or SlimDX easier than using DirectX directly from C++?
I decided to learn to program in DirectX yesterday, and, not being a huge C++ fanatic, went looking for a .Net wrapper. After reading about SlimDX and SharpDX, I decided I liked what the SharpDX people were doing and began trying to use it. Although they have a huge number of samples that are really nice, I had trouble finding any tutorials specifically for it. I ended up seeing a huge number of C++ tutorials. Besides the really long and less than aesthetically pleasing function names, it really didn't seem any more complicated than using the managed wrappers.

So my options (and what I think about them) are:

* SlimDX/SharpDX are in a language I am familiar with, but nearly as complicated as the C++
* DirectX is C++, something I am not too familiar with. I would really need to learn proper memory management.
* Focus on really learning C++ well before diving into game programming with straight Direct3D. This would allow me to learn proper memory management and get comfortable with C++.

My original thinking was that if using Direct3D was just as easy as a managed equivalent, there would be no point starting with the managed equivalent. On the other hand, if the managed equivalent is much easier, it would allow me to focus on the ins and outs of developing a game rather than constantly worrying about the language and getting even small things done.

So, will using one of these managed wrappers be easier than using the native Direct3D API itself?

# Answer
> 2 votes
If you're not a huge C++ fan, then the question I have is, are you already competent at C#? Any way you slice it, DirectX and its related APIs are fairly complex and you will get stuck in some places if this is your first time using a 3D graphics API. Because they are merely wrappers, they involve low-level stuff that you have to deal with on your own. If you decide you want something a bit higher-level than SlimDX or SharpDX, XNA may be another option for you, but at the trade-off that it's limited to Direct3D 9-level graphics.

The best thing, in my opinion, about using a managed D3D wrapper is that you don't have to really worry about memory leaks! The only major performance profiling you'll have to do is GPU efficiency (obviously) and garbage collection rate.

# Answer
> 4 votes
As APIs, SlimDX and SharpDX are almost exactly as difficult to use as the native D3D API or any other APIs they encapsulate. With a few minor exceptions, any ease-of-use benefit you get from either API comes primarily from the fact that you're using a higher level language (C#). This is because, as Martins points out in the comments on your question, they're both lightweight wrappers.

---
Tags: xna, directx, slimdx, sharpdx
---


# Question
Title: Avoiding bouncing between states in an FSM
Suppose you have a simple state machine for a game character with two states:

* **StandingIdle**
* **Walking**

In the update logic for the **StandingIdle** state you have (pseudo code):

```
if input received
    setState(Walking)

```

In the **Walking** state you have:

```
intendedLocation = calculate new location based on current heading and speed

if intendedLocation is blocked
    setState(StandingIdle)
else
    move to intendedLocation

```

Now this creates the problem that the state machine can bounce back and forth between the states, which can result in an awful visual effect. This is because the **StandingIdle** state may switch to **Walking**, whereupon the **Walking** state may determine that something is blocking the way and subsequently switch back to **StandingIdle**. As long as there is input being received (ie. the player is trying to move), then the state machine will bounce back and forth between these two states.

In order to deal with this, the **StandingIdle** state could first check whether there is sufficient room in which to start walking. But that requires either duplicating logic that already exists in the **Walking** state, or exposing that logic in some fashion and calling it from the **StandingIdle** state. I am leaning towards the latter route at this stage.

Another option I considered was exposing some kind of `canTransition()` method from my state objects and having the state machine call it prior to allowing a state change. That way, the **Walking** state could return false if there is insufficient room to walk. This, however, creates other problems.

Is there a best practice way to deal with this problem?

# Answer
> 2 votes
There is nothing wrong with this

```
if (input received  && can walk)
   setState(walking)

```

you can share the "can walk" logic between states.

# Answer
> 0 votes
Move `intendedLocation` to the scope of the state machine and set the 'blocked' flag to be true by default.

When input is received in either state, calculate `intendedLocation` and check if it's blocked. Therefore, `intendedLocation` will be in a different location from the player when input is received. 'Blocked' should also be true if `intendedLocation == playerLocation` (not receiving any input).

In both states:

```
if input received
    set and check intendedLocation

```

Then, in your StandingIdle state:

```
if intendedLocation is not blocked
   setState(walking)

```

In your Walking state:

```
if intendedLocation is blocked
    setState(StandingIdle)
else
    move to intendedLocation

```

It may be a good idea to put the code for setting and checking the intendedLocation in the base class of that the Walking and StandingIdle states derive from, since they'll be both checking for input.

# Answer
> 0 votes
Your `canTransition()` solution is good, but rather than a simple function you would want to have a class that defines the possible transitions from one state to another, since `Walking` can have multiple entry points, that may have different conditions. This will complicate your FSM design though. Here is the relevant Wikipeda page on the deterministic finite automaton

Alternatively, you could allow for more than one state change at a time. That would mean the entering `Walking` state which then switches immediately back to `StandingIdle` and since your input event is already consumed it won't bounce back. You have to take care though to not create circular paths, because that can stall your game. Of course you could introduce a `DoNothing` state, but I'd consider that bad form.

---
Tags: state, fsm
---


title: Using multiple shaders

text:
# Question
Title: Using multiple shaders
I'm currently studying opengl shaders but I can't figure out something: how to apply different shaders to the objects, for example, a teapot rendered using toon shader and another one in the same scene using a very reflective surface and other distorted from a noise function, like in this video

http://www.youtube.com/watch?v=1ogg4ZfdBqU

Another one is applying a bloom shader in a scene and a motion blur shader afterwards. How to achieve those effects when you can only have one vertex shader and one fragment shader? Is there any trick such as using more than one shader program?

# Answer
> 70 votes
The simple answer is you change them between each draw call. Set a shader, draw a teapot, set another shader, draw another teapot.

For more complex stuff where you need to apply multiple shaders to just one object such as blur, glow and so on. You basically have everything rendered to texture(s). Then you render a quad over your entire screen with that texture applied while using another shader.

For example if you want to render a glow effect, you first need to render your regular non-glowing scene, then render just the colored silhouette of the stuff that you want to glow on a texture then you switch to a blur shader and render your quad with that texture attached over your non-glowing scene.

There is another technique called Deferred shading where you render the scene without lighting and apply it later in screen space. The core goal is to reduce the expense of per pixel lighting.

Normally you render a color buffer which is put on the screen. With deferred shading you instead render a color buffer as well as a normal and depth buffer in one shader pass (you can store the normal vectors and the depth in a texture like with normal and height mapping).

This means that, for every pixel, you know the position of the nearest piece of non transparent geometry (depth or distance from eye) the color and the normal. Because of this you can apply lighting to each pixel on the screen instead of to each visible pixel of every object you render. Remember that some object will be drawn over the top of other objects if the scene isn't perfectly rendered in front to back order.

For shadows you actually render just the depth buffer from the point of view of your light then use that depth information to work out where the light strikes. That's called shadow mapping (there is also another approach called shadow volumes that works out a silhouette of the geometry and extrudes it, but your still going to be using shaders.).

With more modern OpenGL (3.0+) you use a Framebuffer Object with Renderbuffers Objects attached. Since renderbuffers can be treated like a texture. You might do things like have 1 shader render to multiple different renderbuffers (so you don't have to render your texture then your normals *then* the glow components) but the underlying practice is still the same.

Also it's desirable to minimize the number of shader switches as much as possible to save on overhead. So some engines will group everything with the same material together so it can all be drawn at once.

# Answer
> 18 votes
You just bind one shader, render all the objects using that shader, then bind the next shader, render the objects using that one, etc.

You can have as many shader objects (shaders loaded into memory and compiled) as you want; only one can be bound (active) at a time.

# Answer
> 11 votes
Using more than one shader in a scene is quite simple; change the shader, set the values for it, then render the object.

Beware, however, switching shaders can be costly, so shader switching should be kept to a bare minimum. There are a few ways to reduce this impact while getting all of the effects you want.

The first method, and usually the most desirable, is to add the functionality for all your shader techniques to just one shader and use conditions you set to render each object in a different way with the same shader. I don't know about OpenGL and GLSL shaders but with HLSL shaders and DirectX these can be grouped together as a "technique" and you can set the technique instead of changing the shader. This allows you to actually have several different pixel and vertex shaders in the same file.

The second way to reduce performance impact is to set the shader, render every object that uses that shader, then repeat. In other words, batching your rendering.

If you wish to apply two different effects to the same object (i.e. apply say a toon shader then some lighting) you can do it in two different ways. The first is to write a shader that applies multiple effects in the same function. The second way is to render the model once with each shader and blend the results by setting different blend options. However, this is a lot more work, and not achievable in all circumstances. Therefore the best option is to combine all your effects into one shader.

# Answer
> 8 votes
Another way of doing that I have discovered is through something called glsl subroutines, where each type of shader is defined in one function, and in the OpenGL application, we can define the current subroutine, draw the vertex of a buffer, change the subroutine and rendering another buffer

---
Tags: shaders, glsl
---


# Question
Title: What to consider legally when cloning an old game?
> **Possible Duplicate:**
> How closely can a game resemble another game without legal problems

I'm going to make a game in the form of a 100% free Android phone app that will be basically a clone of an old arcade style NES game, but with a few modifications to make it better. Now the game I am inspired by was released in 1985, so I'm not exactly shitting bricks about being sued, but I just thought I'd ask on here first about what kind of legal considerations developers go through when copying others' games.

# Answer
The rule of thumb for cloning games is that they can't copyright game mechanics but they can copyright or trademark the specific names and art. Thus making a game that plays the same but has a different title and different artwork is fine.
> 11 votes

---
Tags: legal, copyright
---


title: XNA mouse position in windows forms

text:
# Question
Title: XNA mouse position in windows forms
I am using this code in Update method in XNA RenderControl in Windows Forms:

```
...
Mouse.WindowHandle = renderControl1.Handle;
MouseState stat=Mouse.GetState();
...

```

Everything works fine but when I want to record it with Fraps I get this result: http://www.youtube.com/watch?v=oDmzAIx\_wU0 mouse position is moved but in screen everything is OK. When first line is removed I have moved cursor on screen but not in video. Is posible to have same result in both cases?

# Answer
I'm not sure if it will work in your specific problem but I also use Windows Forms with XNA and after trying many ways to get *consistent* mouse behavior across several different situations, I settled with this:

```
public Vector2 GetMousePosition()
{
    System.Drawing.Point point = this.PointToClient(Control.MousePosition);
    return new Vector2(point.X, point.Y);
}

```

This method returns the current mouse position relative to the control bounds. Put that inside your control class and see how it works for you. This solved a few problems I was having when I tried using the XNA Mouse API for reading the mouse position, in particular when placing my XNA rendering control inside of another control.

Your problem seems to be a different one, but I've just tried using Fraps on my application which uses the method described above, and it's working correctly, so I think it should probably solve your problem too.
> 4 votes

---
Tags: c#, xna-4.0, input, windows-forms
---


title: Are my lines instanced?

text:
# Question
Title: Are my lines instanced?
I have a class which "collects" line mesh transformations throughout the update and then draws them in one place by drawing one line over and over again. I'll post the code below. I'm just wondering if this is instanced or if the idea is to join them all into one mega-mesh and send that through?

Or if I'm missing some key-part altogether....

```
void BatchLineRenderer::RenderLines(D3DXMATRIX matView, D3DXMATRIX matProjection)
{
    device->IASetInputLayout(pVertexLayout);

    device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP);

    // select which vertex buffer and index buffer to display
    UINT stride = sizeof(LINE);
    UINT offset = 0;
    device->IASetVertexBuffers(0, 1, &pBuffer, &stride, &offset);
    device->IASetIndexBuffer(iBuffer, DXGI_FORMAT_R32_UINT, 0);

    std::vector<LINE>::size_type allLines = permanentLines.size();

    for(int i = 0; i < allLines; i++)
    {
        pColour->SetFloatVector(permanentLines[i].colour); // in the line loop too?

        // combine the matrices and render
        D3DXMATRIX matFinal =
        permanentLines[i].scale     *
        permanentLines[i].rotation  *
        permanentLines[i].position  *
        matView * matProjection;

        pTransform->SetMatrix(&matFinal._11);
        pRotation->SetMatrix(&permanentLines[i].rotation._11);    // set the rotation matrix in the effect

        pPass->Apply(0);

        device->DrawIndexed(2, 0, 0);
    }

    allLines = temporaryLines.size();

    for(int i = 0; i < allLines; i++)
    {
        pColour->SetFloatVector(temporaryLines[i].colour); // in the line loop too?

        // combine the matrices and render
        D3DXMATRIX matFinal =
        temporaryLines[i].scale *
        temporaryLines[i].rotation *
        temporaryLines[i].position *
        matView * matProjection;

        pTransform->SetMatrix(&matFinal._11);
        pRotation->SetMatrix(&temporaryLines[i].rotation._11);    // set the rotation matrix in the effect

        pPass->Apply(0);

        device->DrawIndexed(2, 0, 0);
    }

    temporaryLines.clear();
}

```

# Answer
> 5 votes
The purpose of "instanced" rendering is to make *one* draw call to draw all of the instances. You are making `allLines` number of draw calls. So no, that's not instancing.

Since each instance is completely separate from the other, sharing absolutely no data at all (the matrix is basically just a bulky way to encode the two endpoints of each line), you would gain nothing from instancing. Instead, you should build a vertex buffer that contains all of the lines (and their colors). If lines change, you change the buffer.

This way, you draw all of them at once.

# Answer
> 1 votes
I would consider instanced rendering to either be a single Draw call of some sort, where the geometry itself is either duplicated in the buffer N times, or the drawing API renders the mesh N times for you with some per-instance vertex buffer data, or multiple Draw calls with no other API calls in between them (i.e. only changing the starting index or vertex and number of primitives, which you would need to do if you wish to draw less than a whole mesh, but in parts).

Any other API to change textures, rendertargets, shader constants, render state, and shaders calls can incur quite a lot of overhead.

---
Tags: c++, directx, graphics-programming, directx10
---


# Question
Title: How to deal with large depth buffer values due to extreme distances
Alright, this is semi-related to my last question here

So I've got an really big coordinate system and need to handle rendering large astral bodies from extreme distances. My current approach involves different rendering passes based on the distance of the object. The extremely far objects are simply rendered first without writing to the depth buffer using a painters algorithm, while the closer objects are ran through my standard pipeline.

This works however, it isn't ideal for me. The problem isn't when the planet is far enough to fit on the screen. The billboard technique Nicol mentioned below works fine in this case. However, it's when the player is in a fairly low orbit from the surface. I can't use a billboard and would like the terrain to be able to run through my standard pipeline to make it nice and properly lit. With my limited depth buffer though, this isn't possible without z-fighting or letting it clip past the far plane.

**My question is are there any other approaches I can take?** I'm looking into using a linear depth buffer but this doesn't sound too easy since DX11 only supports a floating point depth buffer and I would have to implement all the z culling functionality and what not myself with a standard render target.

# Answer
> 9 votes
> need to handle rendering large astral bodies from extreme distances

Consider the scale of the Solar System. 8 planets, and we're currently on one. Our closest neighboring planet, Venus, is almost the same size as Earth. Yet, it is so far away from the Earth that it appears as nothing more than just another star in the sky. Jupiter is the largest planet in the Solar System; its radius is approximately 11 times the radius of Earth. Yet again, it is so far away that it appears as nothing more than a point of light with the unaided eye.

The Sun itself has 100x+ the radius of the Earth. It is absolutely *immense*. How big is it from the Earth? Not very; it appears as a small disk in the sky.

The Solar System is **gargantuan!** If you're close enough to a planet to be able to see that it isn't just a faint star, odds are good that there will be no other planets nearby enough to be able to see as anything more than a star in the sky. Moons of that planet *may* have visible details, but that's about it.

"Large astral bodies from extreme distances" are points of lights. They don't need to be anything more than that.

If you're making a space game, you can represent a planet as simply a textured sphere. There shouldn't be any z-fighting, because it's just a sphere; it can't z-fight with itself. Indeed, you can probably represent the planet most of the time as a simple flatcard impostor that grows and shrinks as you approach it. You'd use some shader logic to orient a cube map or two onto it of course.

If the planet is close enough for parallax to matter, then you could either use a ray-traced impostor or just render a sphere of the appropriate size. Either way, you use a projection at infinity to make it work, so that it doesn't overlap with the depth buffer.

Now, you may ask what happens if something moves behind the planet? Well, that something would have to be another celestial body for you to notice. Remember: *space is big*. No, *bigger* than that. If a ship is far enough away to duck behind a planet, then it was almost certainly far enough away that you can't see it anymore. So you need not worry about it.

Any celestial bodies large enough to overlap with the nearby planet can be handled very easily. They're spheres/impostors/etc: render them farthest to nearest. No need for depth buffering of any kind.

---

> I can't use a billboard and would like the terrain to be able to run through my standard pipeline to make it nice and properly lit.

Terrain doesn't have very many details that you could pick out from low-orbit. All you need is a reasonably-sized bump map on your billboard.

Take a look at the Planet Earth documentary, which has some shots of Earth from relatively low-orbit. Bump mapping should really be all you need.

I think you're trying too hard to make everything "realistic" when you should be focused on making your *game*. Just get something that looks reasonably good; don't try to do everything exactly how it works in reality.

# Answer
> 1 votes
Alright, figured I'd also post my technique that I ended up using.

As mentioned before, I wanted to render the planets through my deferred pipeline. (rendering to one of my buffers alone with a single pass first would cause side-effects due to ambient light during compositing of all the render targets)

I realized that I could easily do this by using two depth buffer and projection matrices. First I render the distant low resolution bodies and other significant sized objects (Dreadnought ships in my case) with a far set of clip planes and their own depth buffer, and then the closer objects and terrain (if I'm close enough to the surface) with another projection matrix and depth buffer. If you adjust your clip planes you can easily render near and far without any z-fighting.

---
Tags: directx11, depth-buffer, deferred-rendering
---


# Question
Title: Enconding/Decoding bit value in Texture Alpha Channel
I am Rendering to a SurfaceFormat.Color. (R8G8B8A8) The alpha of this format has 8 bits and I want to be able to use those 8 bits as a bit field.

For example, in one pass of my render, I want to save a bit value like 1 or 4 passing =\> 00000001 = 1 or 00000010 = 4 ....

The problem is that the output data of my pixel shader need to be in the range of \[0 - 1\].

How can I encode, for example, the value 00100001 = 33 in my surface.

I am doing this:

```
PixelShaderOutput PShader( PS_INPUT pin ) : COLOR0
{
    PixelShaderOutput output;
    ///bla bla bla
    output.color.a = 33 / 255;
    return output;
}

```

Is this the right way?

Will I be able to read it in the other side? I mean, in another shader, when I need to read this value, can I use `float value = ReadTexture(...) * 255;` where `value` will have 33? (or 00100001)

The GPU will make the right "convertion", cause 33 / 255 = 0,1294117647058824. Will it be encoded as 00100001 in the texture?

In this new shader I want to this value as a bitfield like:

```
bool xTextureRepeat = fmod(value , 64) >= 32;

```

# Answer
> 4 votes
Your method will **almost** work. There is a **rounding problem**: if `32/255` is converted to a floating-point value, and multiplied by `255`, it may become `31.99` and `fmod(value, 64) >= 32` will fail.

This will work better:

```
float value = round(ReadTexture(...) * 255);

```

This will work, too, in case you care about performance and wish to avoid a call to `round`, as long as your tests are in the form `fmod` / `>=`. Be careful with other kinds of tests:

```
float value = ReadTexture(...) * 255 + 0.5;

```

There is, however, **no precision problem**.

### Explanation

It's a bit complicated to explain why there is no precision issue here. In HLSL, the floating point format with the lowest precision has 11 bits of mantissa (10 encoded bits, plus an implicit leading bit).

Normally you would need either a) complex maths, or b) exhaustive testing of all the half precision range (not very complex, there aren't that many values) to really prove this. But I am really talking about the worst case, *ie.* half precision floating point encoding, which will never happen unless you specifically ask for it.

The most problematic value to send to the GPU would be `254/255`, which is approximately `0.9960784313725490196...`. Depending on rounding rules, this can become one of the following values when encoded as a half-precision float:

* `0.99560546875h` (encoded as `2^-1 * (1 + 1015 * 2^-10)`)
* `0.99609375h` (encoded as `2^-1 * (1 + 1016 * 2^-10)`)

Multiplying these by 255 yields either `253.87939453125` or `254.00390625` at full precision. But at half precision, these can become one of the following:

* `253.75h` (encoded as `2^7 * (1 + 1006 * 2^-10)`)
* `253.875h` (encoded as `2^7 * (1 + 1007 * 2^-10)`)
* `254h` (encoded as `2^7 * (1 + 1008 * 2^-10)`)
* `254.125h` (encoded as `2^7 * (1 + 1009 * 2^-10)`)

These will all be rounded to `254` even in the worst case. So you are pretty safe with using a floating point variable here.

# Answer
> 0 votes
Yes, by dividing and multiplying by 255 you should be able to make this work.

Just one note, better do 33.0 / 255.0 instead of 33 / 255 to ensure the compiler uses floating point division and not integer division.

# Answer
> 0 votes
just a point. you need to use: int value = round(ReadTexture(...) * 255); not float value = round(ReadTexture(...) * 255);

obs: clever way to avoid the round =P

# Answer
> 0 votes
You will also likely need to move the variables into uniform variables so the optimizer doesn't try merge too much of the math on you.

---
Tags: shaders, hlsl
---


# Question
Title: How can I change the path a sprite is following in real time?
Is there a common way to implement a character following path that is issued and replaced in real time?

For example: the character follows a path issued, and while it's on that path, if a new path is issued, the character abandons the existing one and follows the new path from where it is currently located.

---

Here's a more detailed explanation:

I am trying to make a real-time action game, like Diablo, but in 2D and tile-based. The player can issue new destinations on the map and the in-game character should walk towards that destination in real time.

I got the path finding part all worked out, but I am having issues with getting the character to smoothly abandon an existing path, and follow a new path (when a new destination is issued).

The character sometimes flickers when a new path is issued while it's following an existing path. If the character sprite is not at the centre of a tile, it will "teleport" to the centre of the tile it's on and follow the path from there on smoothly.

I tried to get around this problem by first checking if the player is on at the centre of a tile, and if not, I amend a node in the front of the new path to get the player to move to that tile. But this still doesn't get me the desired effect, because if the same destination is issued over and over, the character will just keep walking to the same tile instead of walking towards that destination.

# Answer
> 5 votes
I don't think there's anything special about switching from one path to another. You just abort the movement that was taking place, generate a new path from the current position to the destination, and start following the new path from your current position.

Your problem seems to be that you're teleporting your character to the center point of the first tile in the path (i.e. the tile your character is already in), but there's no need to do so.

Although this problem depends mostly on how you're processing the movement and how you're representing the path (either as world coordinates or as tiles), I think you can probably solve it simply by *dropping the first node of the path and start moving directly towards the second node* instead. See the picture below for clarification:

This basically means, make your current position *replace* the first node in the path, instead of appending it like you were doing. Example:

```
List<Vector2D> path = FindPath(player.Position, destination);
if(path.Count > 0)
{
    path[0] = player.Position;
}

```

---
Tags: 2d, animation, tiles, path-finding
---


title: How to make simple-graphics game

text:
# Question
Title: How to make simple-graphics game
I just played minecraft and its awesome. I wanted to make game for years. I'm just not very interested in visual part and very interested in programming and making smart stuff. Mostly i make c/python/php programs with no interface at all. Now i think i found what i was looking for.

So my question is: how can i make simple but smart games like minecraft ? Cross-platform games with java seems like such a great idea. What technology is it using ? OpenGL ? Any 3d engines ? Can you help me please find the way to make smart games with minimal interface ? I'm interested in all platforms.

It doesn't have to be 3d. 2d is cool also. There is just so many different physics engines, proprietary engines. Please help find the way to make small, smart, free games. (java/iOS/android/linux/win32).

Java is priority.

# Answer
> 4 votes
Check out Unity3d. It compiles to Mac, PC, Web, iOS, Android, Wii, XBox, and PS3. It doesn't use java at all, but it has a visual editor, three scripting languages (javascript, c#, and python), physics, particle systems, image effects, 3d sound, networking, and more.

# Answer
> 1 votes
It won't port straight to iOS or Android, but otherwise LWJGL is a good 3D Java library. http://lwjgl.org/ Not sure if there are any engines or SDKs that will support all the stated target platforms out of the box. Here's a 2D engine based on LWJGL : http://slick.cokeandcode.com/. LibGDX, http://code.google.com/p/libgdx/ is for Android.

# Answer
> 1 votes
Minecraft runs on the lightweight java game library engine, so I would look into the interface and API of it. Minecraft is pretty straight-forward with the coding, and how would I know this? Minecraft Coder Pack of course! Minecraft coder pack: http://mcp.ocean-labs.de/index.php/MCP\_Releases Lightweight Java Game Library: http://lwjgl.org/

---
Tags: java
---


# Question
Title: SpriteBatch.Begin() causes everyting else to be drawn incorrectly
I just added this:

```
_spriteBatch.Begin();
_spriteBatch.End();

```

to my app and was greatly confused by the fact that this causes pretty much everything else (all of my 3D objects, that is) to be drawn incorrectly. After the code above has executed, no Z-buffering seems to take place, but instead objects are just drawn in the exace same order as I send them to the scene - with the last object drawn being fully visible even while it is located behing other objects. It also screwes up the sampler state for my textures (which I can fix by setting a new SamplerState for the device).

What is going on and how do I fix it?

# Answer
> 4 votes
This can disable depth buffer. You should enable it again. It should be enough to set DepthStencil state to default.

```
GraphicsDevice.DepthStencilState = DepthStencilState.Default;

```

---
Tags: xna
---


# Question
Title: Drawing a one pixel wide line in 3D space
I'd like to draw a line in 3D space that is always exactly one pixel wide on screen, no matter how far away from the camera it is. (And the same for single points too).

Any hints on how I could do that?

# Answer
> 24 votes
**Rendering Lines - Method 1 (Primitives)**

For simple lines in 3D space you can draw them using a `LineList` or `LineStrip` primitive. Here's the minimal amount of code you have to add to an empty XNA project to have it draw a line from (0,0,0) to (0,0,-50). The line should appear to have roughly the same width no matter where the camera is located.

```
// Inside your Game class
private BasicEffect basicEffect;
private Vector3 startPoint = new Vector3(0, 0, 0);
private Vector3 endPoint = new Vector3(0, 0, -50);

// Inside your Game.LoadContent method
basicEffect = new BasicEffect(GraphicsDevice);
basicEffect.View = Matrix.CreateLookAt(new Vector3(50, 50, 50), new Vector3(0, 0, 0), Vector3.Up);
basicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45f), GraphicsDevice.Viewport.AspectRatio, 1f, 1000f);

// Inside your Game.Draw method
basicEffect.CurrentTechnique.Passes[0].Apply();
var vertices = new[] { new VertexPositionColor(startPoint, Color.White),  new VertexPositionColor(endPoint, Color.White) };
GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineList, vertices, 0, 1);

```

I basically created a simple `BasicEffect` to hold my view and projection transformations, and passed two vertices (storing position and color) to the `GraphicsDevice.DrawUserPrimitives` method to be rendered as a `LineList`.

Of course there are many ways to optimize it, most of which involve the creation of a `VertexBuffer` to store all of the vertices, and batching as many lines as possible into a single Draw call but that's irrelevant to the question.

---

**Rendering Points - Method 1 (SpriteBatch)**

As for drawing points, this used to be easy using point sprites but they were removed from XNA 4.0. There's a few alternatives though. The easiest way is to create a 1x1 white `Texture2D` object, and render it using `SpriteBatch` in the correct screen location, which you can easily find using the Viewport.Project method.

You can create the required `Texture2D` object like this:

```
Texture2D pixel = new Texture2D(GraphicsDevice, 1, 1);
pixel.SetData(new [] { Color.White });

```

And render it at location (x,y,z) like this:

```
// Find screen equivalent of 3D location in world
Vector3 worldLocation = new Vector3(0, 0, 50);
Vector3 screenLocation = GraphicsDevice.Viewport.Project(worldLocation, projectionMatrix, viewMatrix, Matrix.Identity);

// Draw our pixel texture there
spriteBatch.Begin();
spriteBatch.Draw(pixel, new Vector2(screenLocation.X, screenLocation.Y), Color.White);
spriteBatch.End();

```

---

**Rendering Lines - Method 2 (SpriteBatch)**

Alternatively, you can also draw lines using a `SpriteBatch` using the technique described here. In this case you'd simply need to find the screen space coordinate for both ends of the 3D line (once again using `Viewport.Project`) and then draw a regular line between them.

---

**Rendering Points - Method 2 (Small Line with Primitives)**

In the comments, eBusiness raised the following question:

> What about a line with the same start and end point, wouldn't that produce a point? Or would it simply be invisible?

I gave it a try and rendering a `LineList` using the *same* start and end points resulted in *nothing* being drawn. I found a way around it though so I'll describe it here for completeness.

The trick is not to use the same start and end points, but instead to draw a line so small, that it only *appears as one pixel* when drawn. So, in order to choose the correct end point, I first projected the world space point into screen space, moved it right one pixel *in screen space*, and finally projected it back into world space. That's the end point of your line in order to make it look like a dot. Something like this:

```
Vector3 GetEndPointForDot(Vector3 start)
{
    // Convert start point to screen space
    Vector3 screenPoint = GraphicsDevice.Viewport.Project(start, projection, view, Matrix.Identity);

    // Screen space is defined in pixels so adding (1,0,0) moves it right one pixel
    screenPoint += Vector3.Right;

    // Finally unproject it back into world space
    return GraphicsDevice.Viewport.Unproject(screenPoint, projection, view, Matrix.Identity);
}

```

Followed by rendering it as a normal line primitive.

---

**Demonstration**

Here's what I got drawing a white line in 3D space using a line list primitive, and red dots at both ends of the line using a 1x1 texture and SpriteBatch. The code used is pretty much what I wrote above. I've also zoomed in so you can confirm that they're exactly one pixel wide:

# Answer
> 2 votes
This is tagged as XNA so I'm assuming that's what you're asking about?

If so, this article should be helpful for lines:

http://msdn.microsoft.com/en-us/library/bb196414(v=xnagamestudio.40).aspx

Of course you can use your own view/projection matrices instead of theirs. Basically, `PrimitiveType.LineList` or `LineStrip` is how to draw lines at the GPU level.

As for points, you can no longer use PrimitiveType.PointList to draw points anymore in XNA 4.0. Instead you would have to make very small triangles. This sample provides a good baseline:

http://create.msdn.com/education/catalog/sample/primitives\_3d

For previous versions of XNA, if you're using one of those, you can go ahead and read the Point part of the XNA 3.0 version of the article posted above:

http://msdn.microsoft.com/en-us/library/bb196414(v=xnagamestudio.30).aspx

Note the link has:

```
graphics.GraphicsDevice.RenderState.PointSize = 10;

```

Obviously change that to `1`.

---
Tags: xna
---


# Question
Title: Should i be worried about loading so much data?
So a week ago or so i asked this question: A few queries about my Map Data (& ideas of improvement, seconded opinion required)

And the advice in the comment was to ask them as 3 separate questions. So I' going to focus on map loading, and my concerns. So recently i have been working on a new map editor, mainly creating some form of an entity system so that i can easily edit and manage any entities i have (animated tiles, enemies etc.). And i currently have animated tiles done.

But now I'm coming to the point were I'm going to-do the saving and loading in the editor. And I'm just curious to know if i should be worried about loading quite a-lot of data in some cases.

So this might be an example of things that would be in my map files;

* Map Data, the number of layers, the width & height of the map and finally then all the map tile data. (Currently in my old map format, this is all the data the map's contain!)
* Then having any Animated Tile data, their position, what animation file they use.
* Enemy Data, the enemy type, positions of the enemies, the starting enemy state.
* Level Exit Data, the position of the exit node, the destination of were the exit will take the player.

In terms of scale, i don't think a level will contain more than 20 enemies, in terms of Level Exit data, perhaps 3-4 max. Animation tiles, perhaps 20-40 max depending on the size of the level.

I'm just worried in that by loading up all this data it's going to take quite the hit on performance. So my question is purely, should i be worried? Or am i just being overly sensitive to loading this much data? In-fact in comparison to other games, is that a-lot of data to be loaded in with a map (that would be an interesting comparison to settle me, to see another games map and perhaps compare the amounts of data stored).

Thanks in advance for any help :)

# Answer
> 1 votes
No.

Unless you are doing something very naive or brute force, the sorts of numbers you're talking about here will barely be noticeable. Even if your map format was some sort of ugly ASCII file or XML file that needed parsing, I'd be very surprised that loading would even show up as a blip in the profile.

You most likely won't even notice loading time until you get up into the hundreds/thousands of tiles.

---
Tags: xna, c#, maps, data
---


# Question
Title: Is it legal to use car manufacturers' names in a game?
Is it legal to use car manufacturers' names in a game?

For example:

* to describe Audi's quattro drive system?
* to display a rendering of an Audi?
* to include a photo (to which I have rights) of an Audi?

# Answer
The problem with "Is it legal" questions is that:

* Laws differ from country to country, and from state to state - which jurisdiction are you in, and where do you expect your game to be distributed?
* Even something that appears to be legal may be ruled as not legal, or vice versa, should it be put to the test.

I'm not one of these people who says you should never ask legal advice from a non-lawyer, because even lawyers are not omniscient about law - many lawyers fight cases they wrongly think they can win. However you have to accept that no answer given to you is necessarily authoritative unless given by a judge sitting on your particular case. All you can do is arm yourself with knowledge.

Regarding the use of the word 'Audi' - http://en.wikipedia.org/wiki/Trademark

Regarding the appearance of an Audi - http://en.wikipedia.org/wiki/Trade\_dress

Regarding showing a picture of an Audi - http://en.wikipedia.org/wiki/Copyright (I reckon you'll be fine on this one)

Regarding describing the drive system - http://en.wikipedia.org/wiki/Patent (I think you're ok here too - if the system is patented, it's public knowledge, just not public to reproduce or exploit as an invention)
> 11 votes

# Answer
From experience you have two options:

Licence the vehicle(s): This will be either from the manufacturer directly or someone who already holds the licence (such as another developer that already has an exclusive licence for their use - they may choose to sub-licence). They're under no obligation to licence anything to you and will only do so if they're happy in the way in which their product is being portrayed and the context in which it appears. Depending on the manufacturer and prestige of the product the licensing costs can range from nothing right up to ridiculous amounts of money. They also like to have final approval on the finished in-game assets, etc, to ensure you're not degrading the appearance of the brand.

Don't licence the vehicles: This is the route Grand Theft Auto IV used in their last game. I highly doubt car manufacturers would want their brands associated with the type of gameplay in GTA, they worked around this by making a number of changes to the physical representation and names of the models such that it met certain legal requirements (yet you could still tell pretty much what they were meant to be).

In most of the major markets I would expect you to require a licence to do what you want, consulting a lawyer is always a fantastic idea if you're unsure of where the line falls.

Update: Some extra info on photo's from the World Intellectual Property Organization - 'Legal Pitfalls in Taking or Using Photographs of Copyright Material, Trademarks and People'.
> 10 votes

# Answer
On top of my head, the best example I can think of is Grand Theft Auto: All cars have the exact same shape as the real life models but Rockstar Games made up new names for them like "Cheetah" instead of Chevrolet etc..If they did it then I would say you can do the same ?
> 1 votes

---
Tags: legal
---


title: Opengl-es 1.1 draw blur on model?

text:
# Question
Title: Opengl-es 1.1 draw blur on model?
How can I draw blurred models/images in 3d space like here:

# Answer
> 3 votes
That is called Depth of Field effect. Here are few implementations in OpenGL:

---
Tags: opengl-es
---


# Question
Title: What are the performance implications of multiple windows with indivdual OpenGL contexts?
For an engine I'm developing I've decided to allow users to set up multiple windows showing differing views of the same "world." This is being developed using OpenGL (hopefully aiming for 3.2 core eventually if that affects the ansmer) and SDL 1.3. The basic structure I've got set up is:

```
class Window {
    SDL_Window *sdl_window;
    SDL_GLContext context;

    Window(...) {
        sdl_window = SDL_CreateWindow(...);

        // Rest of the setup of world etc.
    }

    gl_init() {
        context = SDL_GL_CreateContext(sdl_window);

        // Set up initial OpenGL settings.
    }

    render() {
        SDL_GL_MakeCurrent(sdl_window, context);

        // Rendering the world.

        SDL_GL_SwapWindow(sdl_window);
    }
}

```

This all compiles and runs fine with the rest of the demo code I've developed so far, simply showing a pair of slightly offset views. However, there's no really performance heavy stuff implemented yet.

* Is this the correct approach to use?
* Are there any major performance implications with switching the context twice (or more) a frame? (other than the expected double (or more) rendering occurring).
    + For example, does switching contexts force a flush of the graphics memory to the system RAM or something equally frame-rate killing?
* Is there an alternative method that would allow setting up two different viewpoints and rendering them in one pass?
* If this is the best way to do it is there a way of sharing data between contexts? I'm thinking once I switch to VBO's over display lists, if the views overlap in some way they should be sharing VBO's for that portion.

# Answer
> 5 votes
> Is there an alternative method that would allow setting up two different viewpoints and rendering them in one pass?

What do you mean by this? Having two contexts means having two *windows*. This means that you have two windows that can be positioned and operated independently of one another.

If all you're using these two windows to do is to have two viewports into the same scene, that's *really* not necessary. You can do that with one context and one window. Just use `glViewport` and `glScissor` to set up multiple views within the same window. You set one view, render stuff, then you set up another view, and render stuff to that.

> If this is the best way to do it is there a way of sharing data between contexts?

The big objects can be shared between contexts. wglShareLists is how you do it for Win32 OpenGL.

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


title: Running geometry shader only once

text:
# Question
Title: Running geometry shader only once
*(Unfortunately couldn't find the answer myself)*

**Does a neat way to cache the geometry shader results in `Direct3D10` or `OpenGL` exist?** (preferably `Direct3D10`).

I'm building my geometry based on texture sampling and I want to do it **only once.** So, when the first frame of the scene is rendered, this geometry is build and I want to substitute the geometry building process with *simple vertex / index buffer rendering.*

I hope this can be achieved without intervening into the non-shader code, but if it doesn't, what should I do? I guess the geometry can somehow be *"snapshotted"* right before the *rasterizing stage*, can it?

# Answer
> 8 votes
Yes; the feature that does this is called "stream-out". For D3D10, the documentation can be found here. It captures the geometry shader output to a vertex buffer you specify, which can then be re-used.

For OpenGL, the same functionality exists under the name "transform feedback". The relevant OpenGL spec can be found here.

---
Tags: 3d, geometry, directx10, geometry-shader
---


title: How to handle walking into walls?

text:
# Question
Title: How to handle walking into walls?
Say we have a player who's walking around in first person perspective. He would like to walk forward, but that would put him inside an object, and that's no good.

Right now what I do is... (pseudocode follows)

```
class Player(whatever):
  def __move_by(this, displacement):
    for object in scene:
      if(object.hitbox.collides_with(displacement)):
        return #nope.avi
    this.position += displacement

```

This isn't really good however. Often times I need to watch the console debug output to understand what I would be walking into. Also, not moving at all isn't what happens in "real world" games. I am however in trouble when putting into words, or code, what *is* it that happens in "real world" games.

What I do with NPCs is calculate the projection of the movement towards their goal along the direction they're heading to, as well as rotating them towards their goal in the process. However, here there's no "goal" distinct from the heading - if we ignore strafing, all the player can do is walk back and forward along his heading exactly.

So... how to handle this?

# Answer
Well, File-\>Make a Copy doesn't work for me so let's describe the answer the old way :)

First, calculate the intersection point between your movement vector and the wall. Second, compute the wall normal (vector perpendicular to the wall) at the intersection point. Next compute the dot product of your reversed movement vector and the normal (so both vectors have their origins at the same point and the angle is between 0 and +/-90 degrees; if the angle is 0 you just pick a direction at random) -- this way you'll know if the player should slide by the wall left or right. After that it's a matter of computing a vector parallel to the wall (i.e. perpendicular to the normal) in the correct direction and moving your character along this vector.
> 3 votes

---
Tags: first-person-shooter, control
---


# Question
Title: Fast and simple attenuation from a flaming torch
I have a single point light-source which is a flaming torch. I compute the distance from the light accurately.

I am not trying to have a particularly realistic torch effect, but I will be moving the light-source slightly each frame and perhaps introducing a slight flicker in strength.

I want near the light to be white - say up to a distance of 200 - and then getting darker and yellower until, say, 400 before fading rapidly to black at 450.

What is the best way to do smooth extinction like this?

Here's my current fragment shader, simply so I know that I have it centered correctly:

```
uniform vec4 COLOUR;
uniform sampler2D TEX_UNIT_0;
varying vec2 tex_coord_0;
varying vec3 normal;
varying vec3 light_0;
void main() {
    vec3 pixel = vec3(0.,0.,0.);
    vec3 N = normalize(normal);
    vec3 L = normalize(light_0);
    float lambert = max(dot(N,L),0.);
    if(lambert > 0.) {
        pixel = texture2D(TEX_UNIT_0,tex_coord_0).rgb;
        float att = 1.;
        float d = length(light_0);
        if(d > 300.) att *= .5;
        if(d > 350.) att *= .5;
        if(d > 400.) att *= .5;
        if(d > 450.) att *= .5;
        if(d > 500.) att = 0.;
        pixel *= att;
    }
    gl_FragColor = vec4(COLOUR.rgb * pixel * lambert,COLOUR.a);
}

```

# Answer
Probably the best way to control it exactly is to just bake attenuation into a low-res 1d texture and have your artist author the falloff. This'll also allow you to attenuate red/green/blue at different rates and change the attenuation function just by binding a different texture eg.

```

pixel = texture2D(TEX_UNIT_0, tex_coord_0).rgb;
float d = length(light_0);
lightCoord = clamp(d * LIGHT_0_INV_SCALE + LIGHT_0_BIAS, 0.0, 1.0);
pixel *= texture2D(TEX_UNIT_1, vec2(lightCoord.x, 0.0)).rgb;

```

Then setup your uniforms like this:

```

LIGHT_0_INV_SCALE = 1/lightRadius;
LIGHT_0_BIAS  = some value in [0..1];

```

Of course you can animate both of these properties cpu side in some random/linear fashion.
> 6 votes

---
Tags: opengl-es, glsl, lighting
---