text:
Behavior/Attribute GameComponent Architecture
I am a college student, and game development is a little hobby for me. I am writing a new game and I have been looking for a new approach to developing the game engine as to make it more flexible (and allow to provide myself with a solid foundation for future endeavors). I found a few articles about how rather than relying on deep inheritance to represent game entities (Which can lead to heavy root and leaf nodes in your inheritance tree, as well as diamond inheritance in some cases), a better approach is to model your logic in components (Better yet, behaviors and attributes).
Here is a presentation that illustrates this:
http://www.gdcvault.com/free/gdc-canada-09
"Theory and Practice of the Game Object Component Architec..."
I'm implementing this using XNA and C#. I have an Entity class:
class Entity
{
    private Game1 mGame;
    private Dictionary<AttributeType, object> mAttributes;
    private Dictionary<BehaviorType, Behavior> mBehaviors;

    public Entity(Game game)
    {
        mGame = game;
        mAttributes = new Dictionary<AttributeType, object>();
        mBehaviors = new Dictionary<BehaviorType, Behavior>();
    }

    public Game GetGame()
    {
        return mGame;
    }

    //Attributes
    public void SetAttribute<T>(AttributeType attributeType, T value)
    {
        if (mAttributes.ContainsKey(attributeType))
        {
            mAttributes[attributeType] = value;
            OnMessage<T>(MessageType.ATTRIBUTE_UPDATED, attributeType, value);
        }
        else
        {
            mAttributes.Add(attributeType, value);
            OnMessage<T>(MessageType.ATTRIBUTE_CREATED, attributeType, value);
        }
    }

    public T GetAttribute<T>(AttributeType attributeType)
    {
        if (!mAttributes.ContainsKey(attributeType))
        {
            throw new KeyNotFoundException("GetAttribute: Attribute with type: " + attributeType.ToString() + " not found.");
        }
        return (T)mAttributes[attributeType];
    }

    public bool HasAttribute(AttributeType attributeType)
    {
        return mAttributes.ContainsKey(attributeType);
    }

    //Behaviors
    public void SetBehavior(BehaviorType behaviorType, Behavior behavior)
    {
        if (mBehaviors.ContainsKey(behaviorType))
        {
            mBehaviors[behaviorType] = behavior;
        }
        else
        {
            mBehaviors.Add(behaviorType, behavior);
        }
    }

    public Behavior GetBehavior(BehaviorType behaviorType)
    {
        if (!mBehaviors.ContainsKey(behaviorType))
        {
            throw new KeyNotFoundException("GetBehavior: Behavior with type: " + behaviorType.ToString() + " not found.");
        }
        return mBehaviors[behaviorType];
    }

    public bool HasBehavior(BehaviorType behaviorType)
    {
        return mBehaviors.ContainsKey(behaviorType);
    }

    public Behavior RemoveBehavior(BehaviorType behaviorType)
    {
        if (!mBehaviors.ContainsKey(behaviorType))
        {
            throw new KeyNotFoundException("RemoveBehavior: Behavior with type: " + behaviorType.ToString() + " not found.");
        }
        Behavior behavior = mBehaviors[behaviorType];
        mBehaviors.Remove(behaviorType);
        return behavior;
    }

    public void OnUpdate(GameTime gameTime)
    {
        foreach (Behavior behavior in mBehaviors.Values)
        {
            behavior.OnUpdate(gameTime);
        }
    }

    public void OnMessage<T>(MessageType messageType, AttributeType attributeType, T data)
    {
        foreach (Behavior behavior in mBehaviors.Values)
        {
            behavior.OnMessage<T>(messageType, attributeType, data);
        }
    }
}

Where "AttributeType" and "BehaviorType" are just enums:
public enum AttributeType
{
    POSITION_2D,
    VELOCITY_2D,
    TEXTURE_2D,
    RGB_8888
}

The behavior class is a super-class of all other behaviors; behaviors are meant to be self contained and modular (For example, I might have a SpriteBatchRenderBehavior which knows only how to render an entity to the SpriteBatch, which should be usable in any new game that uses this framework).
abstract class Behavior
{
    //Reference to owner to access attributes
    private Entity mOwner;

    public Behavior(Entity owner)
    {
        mOwner = owner;
    }

    public Entity GetOwner()
    {
        return mOwner;
    }

    protected void SetAttribute<T>(AttributeType attributeType, T value)
    {
        mOwner.SetAttribute<T>(attributeType, value);
    }

    protected T GetAttribute<T>(AttributeType attributeType)
    {
        return (T)mOwner.GetAttribute<T>(attributeType);
    }

    public abstract void OnUpdate(GameTime gameTime);

    public abstract void OnMessage<T>(MessageType messageType, AttributeType attributeType, T data);
}

So an entity has a bag of labeled attributes (POSITION_2D, TEXTURE_2D, etc), each behavior can access the attributes of their owner through get/set methods. I'm running into a problem where attributes from my entity need to be shared between behaviors (not sure if this IS actually a problem). Basically, if I have a behavior that changes the position of an entity in the game world, it modifies the position attribute of the entity. I then add the SpriteBatchDrawBehavior to the entity, which depends on the entity having a position (so it knows where to draw the entity). My problem is, if I add the draw behavior before the movement behavior, there is no guarantee that the entity will have acquired a position attribute yet (in which case a key not found exception would be thrown).
I can always make sure the entity has a position by adding a behavior that guarantees it WILL have a position before adding a draw behavior (or any other behavior that would depend on this attribute), however this would make these behaviors coupled in a way they shouldn't be.
The other option is to inherit the draw behavior from a movement behavior which inherits from a position behavior (but this brings us back to the problem with diamond inheritance, etc, and child classes that have little to no ACTUAL relevance to their parent classes, other than having similar dependencies).
One more option is to write a check in my behaviors like: "If my owner doesn't have a position, then make a position attribute for him", but then this raises the question: which default value should be chosen for the new attribute? etc etc.
Any suggestions? Am I overlooking something?
Thanks!

FYI: looks like you're trying to write C++ in C#. We don't use getters like GetGame(). Look up "properties" and simplify your life.

Yikes - when they said you should model your entities into components, they didn't mean make every entity a grab-bag of enum-based attributes!
The point of component-based design is that, rather than having one large tree-heirarchy of classes (Penguin inherits from FlightlessBird inherits from Bird inherits from Animal inherits from...), like many games traditionally do, you build your classes up from component-classes which specify what properties that class has.  For example, your Penguin class might contain an instance of an EatsFish component, but wouldn't contain CanFly.
See here and here for a better description of component-based design than I could ever hope to give (I particularly like this article).

Note that the slides you linked to suggested using Mix-ins to model components.  C# does not support multiple-inheritance like C++ does, so you can't really "do" mix-ins.  You'll have to compose your classes the more normal way: using interfaces and/or composition.
Note also that they support using a messaging system, which is usually considered to be bad design (despite being widely used).
Finally, since you mentioned you're using XNA, I feel compelled to mention that XNA has built-in support for services.  This will solve the instantiation problems you're having. And more importantly, this really helps keep your code clean and separated... but for some ungodly reason it never seems to be mentioned in any XNA tutorials or books.

I want to keep this framework as portable as it can possibly be; wouldn't creating my game using XNA GameServices sort of tie my game down to XNA? Or is the GameService framework simple enough to implement on my own for use on other platforms (android, iphone, etc). Also, in the presentation that I referenced they show a health component that grabs a reference to a related attribute from the owner of the component: "GetAttribute(HEALTH_KEY);", which is why I chose to model my attributes in such a way.

@Travis: If you want to make it portable to android/iphone, C# is not a good choice.  You might want to look into cross-platform mobile libraries for Java or C++.  However, if C# is all you know, stick with that and worry about actually creating a game for now.  Worry about portability later - creating a game is hard enough without having to learn a new language on top of it!

Oh, haha I know that C# certainly isn't the best for portability, however the concepts used in this game engine design are portable to whatever platform (Which is what I'm focusing on). I have a pretty good grasp of writing games using android ndk, open gl es 2.0, and the c++ directx 10 libs, I'm just writing this game in C# and XNA because it's for a Microsoft Windows Phone event on campus.

Can you elaborate on how you would change Travis's code? I'm still struggling to understand component-based game design, and the articles you linked to are the same ones I've seen many times before; they're too high level and vague to really help understand the pattern (for me anyway). From my understanding of component-based design, it seems like Travis is on the right track. Can you be more specific about where you think he went wrong and how his code could be improved?

I've read the presentation from GDC Canada by Marcin Chady a few hours before reading your question and I think that you didn't understand the point of attributes. I personally (I didn't write the presentation, nor I do know how it really works in Radical Entertainment) think that you must create the needed attributes before actually using them.
The ChangePositionBehaviour and RenderBehaviour both use the Position attribute, but neither the first one, nor the second one do initialize the attribute. You must initialize it first. You have to tell the entity where it's located.
Let me show you it on a simple example of a Breakout clone:
You've got a Level class (it's a game level = room = map), which contains Brick object (entity). The Level knows, that the initial position of the Brick is at location 4.0f, 8.0f (X, Y) and it's speed is 0.0f, 1.0f. If it didn't know it, it couldn't have been a level, because you must specify objects' locations in a level definition (level data file). So, what does the level do? It creates a Brick entity and right after that (before any behaviour is called) it sets the position of the Brick to the initial one.
Brick.SetAttribute<Vector2>(AttributeType.POSITION_2D, new Vector2(4, 8))
Brick.SetAttribute<Vector2>(AttributeType.VELOCITY_2D, new Vector2(0, 1))

Then, you can simply continue. And when you need to draw the Brick, you already know the position of it. When you need to change the position of it (it's a movable brick, which moves from the left side of the screen to the right side, and then back), you just do:
Vector2 position = GetAttribute<Vector2>(AttributeType.POSITION_2D);
Vector2 speed = GetAttribute<Vector2>(AttributeType.VELOCITY_2D);
position += speed;
SetAttribute<Vector2>(AttributeType.POSITION_2D, position);

I hope you understood me. It's simple: the behaviours rely on attributes, so the attributes must be already set before you proceed to OnUpdate() and OnMessage().
By the way: (as I cannot comment with my newbie reputation on GameDev SE, I'm adding this btw text to my answer)
You don't need any multiple inheritance, so I really don't understand where is the leading answer of BlueRaja - Danny Pflughoeft going... The Theory and Practice of Game Object Component Architecture presentation is fully transformable to C# without any problems, as well as to any other OOP language. And I don't know what's wrong with message passing, because in this example, there isn't any other possible solution I can think of (you can't avoid using messages if you want this code to be generic, in my opinion). Maybe you could use custom event handlers and instead of messages, you'd pass event arguments. It could work too.

My suggestion would be to have an initialization function for the behaviors. When you add the behavior to the entity, it can add its attributes. When you initialize, you search for attributes you need and raise an error if they aren't there. That way you can add them all in any order, but they won't actually look for the attributes until initialization.
Alternatively, you can use your OnMessage infrastructure to ignore missing attributes when a behavior is added to the entity, then listen for all needed attributes to be added in the OnMessage for the behavior. If an attribute is missing when you try to use the behavior you can either throw an error or simply not execute the behavior. Whichever is more appropriate for your game.
Does any of that help?

I like your idea of having the behaviors initialize after construction to check if  required attributes exist. I think I might try doing that and see how it works out. I actually had the same idea with using the OnMessage methods to notify behaviors about the addition of new attributes; but it seems both of these solutions still depend on the order in which the components are added/initialized. With the message system, if a component adds an attribute, a one time message will be sent to all behaviors, however relevant behaviors may not have been added to the entity yet, missing the message.

@TravisSein The ones added after the message is sent should check for the attribute when they are added, that way if it existed before it's good. If it's created after, it'll get the message.


text:
Creating map files for a 3D game
I've created plenty of 2D games and now that I've gotten my hands dirty working with 3D in opengl I want to start a game. The issue is I don't know how I can store all the map data. Not only the terrain but the textures and objects in the world, lighting, what's intractable etc. it seems that it'll get way to big if I don't have an efficient system for storing and loading maps. So what methods or articles can you guys suggest on this?

Way too many answers for that =)  Start by taking a look at existing 3D engines, thousands of open sourced ones, and research what they're doing with terrain.

Firstly look up basic spacial geometry formats like Octrees and BSPs.
As for your actual map level format, chances are you will want something very customized to your game. Are you using 1 giant mesh for your game world (Like a FPS), a bunch of modular meshes something like an indoor Skyrim area or for the outdoor areas they would also probably have a heightmap (Stored as a texture? maybe a bunch of floats? Maybe inputs for a procedurally generated algorithm). Do you want a massive open gameworld like GTA/Just Cause or a bunch of small detailed areas? Do you need to embed lighting maps or is that done on the fly? Custom meshes/objects or all build from components?
You might actually want to start with something like XML or ASCII and just convert it into something binary at a later point once you have your details hammered out. You might find the XML gives you good enough performance anyway.
idGames actually use plain ASCII for their stuff and in doom3 at least it compiles most of the stuff on load since lighting now doesn't need to be prebaked as it's done on the hardware. It's split over a few different files but I think they are all ASCII (even the 'compiled' stuff). So you don't really need any superefficant packing methods.
You can look at using formats that are outputted from 3D modelling software like 3D Max, Maya, Blender and so on. That way you don't have to make a level editor. But you will have to find a way to embed game information in your 3D scenes.
COLLADA is a very general purpose 3D XML format. But it might be a bit too general and feature rich and requires some parsing and cleaning up. You will also have to fidn a way to gameify it (Maybe 1 file for overall level layout while keeping your mesh stuff in another file or even different format).
Some other random advise would be to give every object a unique id (at least the non-static ones), that way you can easily save/load just the changed data. It would probably also help with network replication for multiplayer.
Other advice would be to split up everything. Don't try and embed textures in your level format. If you do want to pack everything together for redistribution just zip it.

I think looking up BSP's etc is too complicated for a first game.
In a 2D game you basically store everything as an image and access it when you want. spritesheets, tiled maps etc.
In a very basic 3D game, the geometry is more complicated than just one image and is usually embedded in a file just like any other peice of code. You have vertex data describing walls etc.
Just create a level class that is a container for a number of walls and the floor etc, each of which is a class that calls in the right textures.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Is it worth making component based entity system?
I've been reading about component based entity-system for couple days now and I'm not quite sure if it is worth implementing in my next game. I haven't started making the game yet, but I have bunch of ideas for it. In my imaginations the game will be very similiar to QUBE and Portal (1). 3D puzzler, no enemies, no weapons ( although there may be some "guns", just like portal has portal-gun ). The "basis" of the levels would be constructed from voxel-like data just like in QUBE, but there may be some models aswell ( although, since this is one-man project and I'm no artist, the models will be simple and there wont be many of them ).
I couldn't imagine that I'll ever have more than 20-30 different entities, if even that many.
This is a project that I expect to be working with for a long time, so I'm now trying to properly research all the possible "engine"-architectures before I actually start making the game. I want the game to be flexible and that I could easily implement more features as I progress.
Questions:

After reading this, do you think I should implement component-based entity system or not? If yes, why?
If I were to implement component-based entity system ( or in a matter of fact, any entity-system at all ), what would "terrain"/"voxel data" be? Would it be entity?

EDIT: I forgot to mention, the other option would be just simple inheritance-based entity-system. The game will be done using C# + XNA ( and WPF for the level-editor ).

What exactly are the entities you have in mind? Maybe not a full list, but at least give us a few representative examples.

@jhocking Umm.. Well, the entities I have in my mind are just like button, laser, "hard-light" bridges, aerial faith plates, funnels etc. from Portal 2. Entities I've in mind are like that. Of course, there would be a "model entity" which can hold models, then for example "door entity" which would be constructed from voxels/cubes, but it would be animated somehow when the door is opened. And of course player would be entity.

http://gamedev.stackexchange.com/faq#dontask  This question reads more like "I want to participate in a discussion about the worth of component based entity systems" instead of "I have this problem I need solved.".  The answers are going to be just a polling of opinions more than anything else.

Feel free to bring this question to the chat, though. http://chat.stackexchange.com/rooms/19

Short answer: probably
Longer answer: A component-based entity system becomes more valuable quickly as the number of distinct entity types increases, so your saying "20-30 different entities" is an important consideration. However it doesn't really take many different entities for component-based to be a big advantage. 20 different entities would certainly benefit a lot from a component-based system, although you also don't think 20 is many entities so I'm curious what exactly you consider "different".
For example, I wouldn't consider an old brass key and an electronic keycard to be different entities, but rather two instances of the same entity with different art assets assigned to the entity. Would you consider those to be different entities?

Another important consideration besides the sheer number of entities is their complexity. A component-based system helps a lot with complex entities, but is just unnecessary overhead for simple entities.
Going back to my keys example, I probably wouldn't bother with a component-based system for keys. I would use a component-based entity system for enemies, but then you said your game won't have enemies. What exactly are the entities you have in mind? Maybe not a full list, but at least give us a few representative examples.

I consider "model-entity", which can hold any model that can be rendered, as one entity. I doubt I will in the end even have many "complex" entities in the end. To the last question, I replied to your comment in the OP where you asked the same question.

ah then for simple entities like that I wouldn't really recommend a component system. Where a component system is useful is for easily mixing and matching components of various complex entities (eg. a goblin has the model+physics+attacker+walking components, a dragon has the model+physics+attacker+flying components, a turret has the model+attacker components, etc.)

Yes there are benefits in entity complexity, yada yada yada, but the real benefit of an entity component system comes not from the ease of creating new entities, or the ease of changing entire sub-systems; it comes from the ability to leverage cache-effecient algorithms. With components, for example, your physics code only needs to know about the object's position, velocity, and collision volume. It doesn't care about the model being displayed, or that it happens to be tinted green, and it doesn't have to waste space in the cache for the entire entity. Unfortunately, these benefits aren't nearly as great in C#.
Short answer : Yes, but don't half-ass it. Make your components data-only, and enforce this rigorously. Define behavior in separate modules that update all like components at once, and separate disparate data into separate components as much as possible.
For reference, http://software.intel.com/en-us/articles/how-to-manipulate-data-structure-to-optimize-memory-use-on-32-bit-intel-architecture/

You mentioned you want the game to be flexible. Do you mean that as only adding new features (better lighting, physics, etc), or also flexibility in terms of game-design? If you also want the game-design part of the development to be flexible, component-based entity systems would be pretty useful.
Unfortunately, I can't give you a competent answer to your second question.
If you choose to implement a CBS, there's two important things you need to ensure:

That components have a way to communicate between themselves very fast (this implies passing the right components to all other components that need them, so they are able to access them directly).
There's a messaging system in place so that components can inform each other when something rare happens, without having to check their state every frame for something that only happens very rarely, like sending a message when the player gets hit.

I mean adding new features as in adding different puzzle-elements, such as what funnel, aerial faith plates etc. are in Portal 2. Of course, ease of changing render, physics etc. code is also important.

@Jakko What you describe (especially the puzzle elements: laser-shooters, moving platforms, etc) seem like things that would be implemented as entities, so I guess a CBS can be helpful in your case.

If the answer and the benefits arent't obvious to you immediately then it's probably not a good idea. Just make it work with the least amount of abstraction possible and when it's done perhaps some sort of "system" will emerge. But don't start by designing a system and then try to fit a game into it.

Based on what you have written I would say that a full on Entity/Component system may be over kill. A question to ask yourself is how deep and tangled do you see your inheritance hierarchy getting? EC Systems are good for cases where entities can take on functionality unexpectedly like if you have an RTS with flying units and ground units, and you decide you want a Mech type unit that can both fight on the ground and fly.
You could always split the difference. Have your game object inheritance hierarchy but if you start having functionality that does not neatly fit within it, factor that functionality out into a component. This is the approach I have been taking and have found it successful.
Anecdotally, I have found more success with having a simple GameObject hierarchy combined with components than having a "pure" EC set up with only a generic GameObject.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Telling which side of a voxel was hit by an object
In XNA, I have an axis-aligned BoundingBox representing the object's hit box, and a Vector3 representing the object's velocity. I also have a stationary 1x1x1 axis-aligned BoundingBox representing a voxel. Using object.box.intersects(voxel.box), I can tell that they intersect. However, I do not know which side of the voxel was first hit by the object.
I am assuming you can just take the direction from the center of the player to the center of the voxel and use that to determine which face it hit. However, my brain is not working right now and I can't figure out the math.
I already know how to respond when you learn which face was hit (from my previous question). I just don't know how to figure out which face the player hit.

Is the player hit box axis aligned?

Vector math should be very expensive, but is very accurate too. Consider.

You can always check each face that can collide. Since the bounding boxes are AA, you'll have these collision scenarios: (-> indicates collision, X_Plus represents the YZ plane on the X plus side of the box)

Box1_X_Plus -> Box2_X_Minus
Box1_Y_Plus -> Box2_Y_Minus
Box1_Z_Plus -> Box2_Z_Minus
Box1_X_Minus -> Box2_X_Plus
Box1_Y_Minus -> Box2_Y_Plus
Box1_Z_Minus -> Box2_Z_Plus

You can narrow the choices to half by checking if one box is further along an axis than the other. For example, if Box1 is at x=1 and Box2 is at x=5, there's no way that the Xminus side of Box1 could be colliding with the XPlus side of Box2, so you can remove it from the options.
I'm not sure exactly what would work, but you could do it something like:
public Face GetCollisionFaceOfPlayer(Vector3f voxelPos, Player player) {
    if(player.x < voxelPos.x) {
        //See if player Xminus is close enough to voxel XPlus
        if(Abs((player.Position.x - player.Width/2) - (voxelPos.x +.5f)) < PreDeterminedCollisionBufferDistance)
            return Face.XMinus;
    }
    else {
        //See if player XPlus is close enough to voxel XMinus
        if(Abs((player.Position.x + player.Width/2) - (voxelPos.x -.5f)) < PreDeterminedCollisionBufferDistance)
            return Face.XPlus;
    }
    //Other faces

}

Or you can keep track of the distances for all the faces it could be and return the minimum.

If the box is axis aligned you can simply take the highest absolute value of the three coordinates of the box centre to player vector. The collision is along that axis, and the coordinate is either positive or negative depending on which side of the box the player collided with.
If the player figure is an axis aligned box it's pretty simply to take it's size into consideration, say for instance it's 2 units high and 1 by 1 units wide, then you simply subtract half of the player boxes respective dimension from the absolute centre to centre distance before comparing. So you'd be looking for max(abs(distanceX)-.5, abs(distancey)-1, abs(distanceZ)-.5) (Of course set up as a series of if clauses so that you not only get to know the maximum value, but also which one of them constitute this.)

However, the player's box is not a cube, so the max-distance isn't necessarily the collision direction. This is what I put in originally, and it does not work.

Would you please be so kind as to not tell me what something is not. What collision figure do you use for the player?

My guess is that it's a cuboid, or a 3d rectangle (not square). Since the OP still calls it a box. But agreed, requiring us to guess isn't too helpful.


text:
How can I get rid of the diagonal wires in wireframe boxes?
I create a box with a material and set that material to be wire framed.
Box b1 = new Box(new Vector3f(1.0f, -2.0f, 1.0f), 1.0f, 1.0f, 1.0f);
Geometry geom1 = new Geometry("Box", b1);
Material mat1 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat1.getAdditionalRenderState().setWireframe(true);
mat1.setColor("Color", ColorRGBA.Blue);
geom1.setMaterial(mat1);

However, because the box is drawn using triangles there are diagonal wires visible:

How can I get rid of these diagonal wires (not draw them)?

Why? Wireframe is a debugging tool that makes polygons visible, it's not intended as a graphical effect. If you want to be selective about what wires to draw you probably need to implement your own wireframe renderer.

As said in the comments. Wireframe rendering is used to show what polygons are being drawn, and is generally only used when debugging.
To solve you problem...
What you want is to only draw lines around the edge of the cube. And there are many ways you can acheive this...

Render a texture on to the cube, which has alpha everywhere but the edges.
Use a pixel shader to turn all pixels that are not at the edge of the cube to alpha. <- This is recommended by me, as you will be able to set the line length around the cube.

I don't know how you are drawing, what libraries you are using...
In DirectX and OpenGL, you usually use vertex and index buffers to hold your geometry data. If the triangles in whatever format you are storing them in are still in the order of the quads they appear in, as is the case with at least some OBJ exporters, it can be relatively easy to figure out which vertices form a quad.
For example, in an obj file, a quad with the vertices 1,2,3 and 4 that was translated to triangles upon export might look like this (pseudo code):
f 1 2 3
f 3 4 1
which would look pretty much the same in your index buffer.
A very simple solution would be to keep a second index buffer for your quads,
where you could store the indices 1,2,2,3,3,4,4,1 or even 1,2,3,4,1. In directx there are the linelist and linestrip topology types which would render these indices as lines treated with your regular shading.
If you create your own file format for storing models in, it becomes easier as you could store quads where possible and tris when necessary in the file, and only translate them to triangles upon import.
I've done this, and since I usually create my 3D models with quads and only use tris where necessary I find a quad wireframe much more intelligible. It is relatively easy to implement provided you are lucky and your storage format accomodates you, but it does have a number of drawbacks.
For one thing it does not produce thick and soft wireframes. It also does not produce a shaded wireframe, but a completely transparent one, so to have your wireframe ontop of your regularly shaded geometry you would have to first draw your object and then draw your wireframe, so there is a performance hit. Still, even drawing the objects twice, once shaded once as wire, this still performs better than just directx' wireframe RasterizerState setting alone. This method is also likely to create z-fighting, which might make it necessary to increase the scale momentarily to avoid that.
Here you can see how it looks in my test implementation, you can see both the z-fighting and the moire patterns created by the aliasing of the lines (there are ways to draw antialised lines though):
https://i.stack.imgur.com/N6X3Y.png (sorry I can't embedd images here yet)
All in all nvidia's solution David posted looks very interesting, I've seen it in the samples and I've been meaning to take a closer look at that.

I found the following resource that might be helpful in implementing the technique described by Twitchy, although it's written for Direct3D. It's taken from the NVIDIA Direct3D SDK 10 Code Samples page. Quoting the page:

Render the wireframe of a mesh using filled triangles, coloring only the fragments near the edges of the triangle. This technique produce high quality thick antialised lines on the mesh edges, without any z fighting issues. This technique is a DirectX10 implementation of the SIGGRAPH 2006 sketch "Single-Pass Wireframe Rendering". This technique can be easily added in an existing graphics engine as it only requires one pass and all algorithm is based on the position of the vertices.

And you can find a whitepaper describing the technique in detail here. The downside is that it requires a geometry shader.


text:
Developing for iOS on Linux
I am looking for an engine or library to develop a game for iOS on Linux.
High level, low level, GUI, no GUI, does not matter too much. I am really looking for anything.
I'm not actually talking about deploying to iOS from Linux or anything like. I just want to do the bulk of the work on Linux, with minimal changes required to run it on iOS.
Edit: YES, I do have access to a Mac, but it is limited. So I want to be able to work on the project on my regular Ubuntu box.
Also, I am in the paid developer program, so I can deploy to iOS devices from the Mac.

MonoDroid should be getting Linux support at some point - if you write your game with MonoGame you can cross-compile it with very little effort. At the end of the day I think you do need a Mac.

Is a virtual machine an option?

@stephelton I now have full time access to a Mac, so this is no longer a problem. See my answer below.

You're pretty much screwed - while there are many libraries and frameworks that allow development on Linux, to do any serious testing you'll need a Mac (or Hackintosh, din't say it). Deployment is one problem, but testing on any simulator is another.
Linux also doesn't run Unity, which would be another good solution.
However, you can take a look at one of the many home rolled solutions. In particular, a really low level solution would be using SDL 1.3+ -- it has built in support for iOS as a target.

If it makes a difference, I do have some access to a Mac. See my updated OP.

You're best sticking to limited access to the Mac. You're going to waste hours getting a non-Mac system running and you won't even be able to test your code on the simulator, which means you won't be able to bug fix. Your whole workflow is going to be a convoluted mess.

If you want to test your app on a real iOS device and later release it, there is no legal way but to purchase a mac device. but If you are looking for a way to develop an app and test it on emulators, you can try using gnustep. note that can try an app written by gnustep, using a jail broken device.
besides if you don't mind working with C++ there is cocos2d-x you can try.
the last option (which also is illegal) is to use emulated MacOS.
this question is also somehow duplicate on StackOverFlow: https://stackoverflow.com/questions/276907/starting-iphone-app-development-in-linux

Illegal? Even if your copy of MacOS is original? Are you sure?

@Lohoris yeah, I'm sure about that. MacOS can only be installed on a mac device. though I've got some friends who deployed their iOS games using emulated MacOS, but Apple strictly forbids such an action.

And do you know if there is any sentence anywhere which actually confirms the validity of that clause, or it is just another random clause they put into contracts but has never been tested in a tribunal?

read it here: http://en.wikipedia.org/wiki/OSx86#Legal_issues_and_Apple_objections

lol that's really terrible, though not surprising after all

I now have full time use of a Mac, so I no longer need to develop for iOS on a Linux machine.
However, gameplay (gameplay3d.org), an open source project by Research In Motion (RIM), looks really good. It is primarily a 3D engine, and uses C++. It also has Lua scripting support.
I haven't actually tested gameplay on Linux, but it appears to have full support.

You can use Moai to develop iOS and Android apps from Windows, Mac, and Linux.
However, you're going to need a Mac in order to deploy or test your app.

I have looked at Moai in the past, but there is no official support for Linux. And I do have some access to a Mac, see my updated OP.

You can develop a game with flash and build it to iOS using Adobe Air
However, you're going to need a Mac in order to deploy or test your app.

Does Adobe Air work on Linux? Also, that last line applies to my answer as well; copied!

Well.. I'm not sure about compiling with adobe air, but he said he wants to do the bulk of the work on Linux, so he can develop in any ActionScript IDE and even run and test it on the flash player for linux.

Hey what's with the down vote with no comment or explanation? Not cool...


text:
Drawing a line from a random coordinate through a given point
When the mouse button is clicked, I want to draw a line from (0, random) to (640, y) which goes through the click position.

How would I calculate the y coordinate of the end of the line?

You have a Point with the origin, and a Point with the mouse position. Let's find the unitary directional vector:
Vector2 direction;
direction.X = mouse.X - origin.X;
direction.Y = mouse.Y - origin.Y;
Normalize(direction);

This way you'll get a vector that points from the origin to the mouse coords, and whose components satisfy the Pythagorean theorem. Now you only have to find the distance the line travels from the origin point until the X component is 640:
Point endPoint;
float distance = 640.0 / direction.X;
endPoint.X = origin.X + (direction.X * distance);
endPoint.Y = origin.Y + (direction.Y * distance);

The equation of a line through two known points is y − y1 = [(y2 − y1) / (x2 − x1)] · (x − x1). Substitute (x1, y1) = (0, random), x = 640, and then solve for y in terms of (x2, y2), which is your mouse's location.
When implementing it, you'd need to check for division by zero, in case the mouse position happened to be on the line x = 0.


text:
Testing whether two cubes are touching in space
Does anyone have any clean ideas on testing whether two cubes in 3D space touch? By touch I mean, touch at corners or on a face or on an edge. Say that the cubes are axis aligned and there is no nesting of the cubes. So either the cubes touch or they don't. There is no overlap of the cubes at all (except of course possibly an edge or corner point).
Everything I have thought of ends up needing a ton of cases. Also numerical stability is a factor. I don't want to just test == on all the edges/points.
I guess I could utilize some sort of epsilon instead of testing whether something == 0. The main thing however is minimizing the number of cases to test.

Are all the cubes the same size?

Are the boxes axis aligned, or free orientation?

If your cubes overlap or they just touch, they have to overlap or touch in all three axis. In one axis it looks like this (for two intervals a and b):

So what you have to test is:
if ((min_a <= min_b && min_b <= max_a) ||
    (min_b <= min_a && min_a <= max_b))

First part (before ||) is for case when min_a < min_b, second for case when min_b < min_a.
For all three axis it looks like this:
if (
   ((min_x1 <= min_x2 && min_x2 <= max_x1) || (min_x2 <= min_x1 && min_x1 <= max_x2)) &&
   ((min_y1 <= min_y2 && min_y2 <= max_y1) || (min_y2 <= min_y1 && min_y1 <= max_y2)) &&
   ((min_z1 <= min_z2 && min_z2 <= max_z1) || (min_z2 <= min_z1 && min_z1 <= max_z2))
   )

Where for example min_x and max_x are minimal and maximal coordinates of cube in x axis. x1 is for first cube, x2 for second.
As I sad, this tests overlaping, but because there is "<=" and not only "<", it test also "touching".
//EDIT:
If you want to have more stable solution (there can be some floating point value errors), you should use epsilon. So it will look like: min_x1 - epsilon <= min_x2 && min_x2 <= max_x1 + epsilon

This only works for AABB collisions, naturally.

I know. But author wrote: "Say that the cubes are axis aligned..."

An alternate way to check for AABB collisions is to rule out all cases where you can't collide.
if (min_x1 > max_x2) no collision
if (max_x1 < min_x2) no collision
if (min_y1 > max_y2) no collision
if (max_y1 < min_y2) no collision
if (min_z1 > max_z2) no collision
if (max_z1 < min_z2) no collision
otherwise, collision.

You certainly want to minimise the number of tests being performed. You can do the test using only three comparisons.
Let (x1,y1,z1) and (x2,y2,z2) be the centres of the cubes. Let a1 and a2 be their respective extents (ie. half their edge length). The cubes touch by your definition if and only if the distances between the projections of their centres is a1+a2 in each of the three directions of the coordinate system.
/* Returns true if two axis-aligned cubes touch or overlap */
return fabs(x1-x2)-(a1+a2) <= EPSILON
    && fabs(y1-y2)-(a1+a2) <= EPSILON
    && fabs(z1-z2)-(a1+a2) <= EPSILON;

Where EPSILON is a small number suitable for your typical object sizes and distances. Note that the above meethod will also return true if the cubes overlap, but since this does not happen, it is not a problem.
If the platform you target has fast min/max selection, you can do it using only one test:
/* Returns true if two axis-aligned cubes touch or overlap */
return max3(fabs(x1-x2),fabs(y1-y2),fabs(z1-z2))-(a1+a2) <= EPSILON;

Another example: http://pastie.org/3409055, where the extents in each direction are not identical (ie, there exists a1.x, a1.y, a1.z etc).

Various spatial tree algorithms are designed to prevent the extra checks you mention.  You could easily add to said structures via a single distance (sphere) check from the cube's center to cull bad results.  Or you could just sphere bound check each cube against the others (O(n^2)) to see if you need further tests.  Note that test can be done without a sqrt if you compare via squared radii.  The spatial trees (oct tree, quad tree, BST) take that O(N^2) term way, way down.  Of course AA boxes means you only need compare 6 values for collisions /left,right, right/left, top/bottom, bottom/top, front/back, back/front.  6 'less than or equal to' compares isn't that bad!

Most likely you will need a spatial data representation that allows for fast dismissal of uninteresting objects. The Octtree is one of the most used structures and fits perfectly with your requirements, plus they are easy to implement. A BSP Tree might be an alternative, depending how your data is set up.
A fast and dirty solution would be to a hash-map to store all points and a reference to all cubes sharing that point. The query would be very fast but at the cost of (a lot of) memory. Although for a small number of cubes that might be applicable.

if your cubes are axis aligned then you may construct tree interval Trees one for each axis.
An intervall tree is a data structure that let you query for an intervall overllapping or a point hit of a set of intervall.
If you can ensure that no cube will ever have an edge less than ε then you can easely see if a cube touches other cubes by querying your trees.
To understand how this works lets scale the problem down to "1D cubes" i.e. segments
It the testing segments is AB then take the points A-ε,A+ε,B-ε,B+ε check the intervall tree for the hit. For every segment that matches there are a few of possible relation with your testing segment:
Testing Segment   A- A+ B- B+
Case              -  -  -  -  impossible : no match
Case              X  -  -  -  touch: the segments are disjoint but very near
Case              -  X  -  -  overlap
Case              X  X  -  -  overlap: segments touches for more that 2 epsilon
Case              -  -  X  -  overlap
Case              X  -  X  -  impossible: no holes in segments
Case              -  X  X  -  overlap: the segments are nearly the same
Case              X  X  X  -  overlap: the segments are nearly the same
Case              -  -  -  X  touch: disjointed segments but very near
Case              X  -  -  X  impossible: no holes in segments
Case              -  X  -  X  impossible: no holes in segments
Case              X  X  -  X  impossible: no holes in segments
Case              -  -  X  X  overlap: segments touches for more that 2 epsilon
Case              X  -  X  X  impossible: no holes in segments
Case              -  X  X  X  overlap: the segments are nearly the same
Case              X  X  X  X  overlap: the segments are nearly the same

As you can see a segment touches our testing one if A- matches but A+ does not OR B+ matches but B- does not; in any other case (excluding the impossible ones) there is an overlap.
In interval trees other data can be stored alongside the start and the end of the intervall. This possibility can be used to give names to the segments so you can wrap the query function so given a couple of points it gives you a list of (segment_name,"touch") or (segment_name,"overlap").
Now we need a way to use 1D results to get 2D results, a way that possibly scale up to 3D and over.
We can say that a rectangle touches another if there is a touch in an axis and an overlap in the other (edge touch) or a touch in both axes (corner touch).
To do this we need to store our intervals into two separate trees taking care of naming intervals correctly.
Let say that we are looking if the rectangle (Ax,Ay)(Bx,By) touches some of the stored rectangle, then we have to query the X-tree for Ax,Bx and the Y-tree for Ay,By.
Lets suppose that the result is [("alpha","touch"),("beta","touch")] by X-tree and [("alpha","overlap")] for Y-tree whe can say that our rectangle touches "alpha" ("edge" touches) but don't touches "beta" nor other rectangles.
The test can be easely managed using a dictionary that keep the rectangle name as key and stores the X,Y values for example: {"alpha":[0,1],"beta":[0,-1]} means that "alpha" touches(0) in X and overlap(1) in Y while "beta" touches(0) in X but is disjoint in Y(-1).
This reasoning can be extended further adding other dimensions: there is a touch if at least one dimension touches and there are no disjoint dimensions:
3D (0:touch, 1:overlap)
X Y Z
0 0 0 corner touch
0 0 1 edge touch (over one of the four Z edge)
0 1 0 edge touch (over one of the four Y edge)
0 1 1 surface touch (over one of the two X surfaces)
1 0 0 edge touch (over one of the four X edge)
1 0 1 surface touch (over one of the two Y surfaces)
1 1 0 surface touch (over one of the two Z surfaces)
1 1 1 eerrr no touch... the cubes are nested (remeber, at least one dimension touch)

[Appendix]
To speed up the interval query match you can test only A- and B+; when you find a match with A- then you get the upper end of the segment that matches and measure the distance with A-: if the distance is greather then 2ε this means that the overlap is too large to be considered a touch so you don't have to continue.
The same has to be done with B+ but this time you have to check the value of B+ with the lower end of the matching segments, again to see if the overlap you find with the extended segment is too large to be considered a simple touch.
A balanced interval tree takes ~log(n) iterations to check if a point hits against n intervals, this means that if you keep (by using red black trees for example) your trees balanced you can check against a huge set in reasonable time


text:
Is there documentation on XNA other than at MSDN?
MSDN documentation of XNA seems to be incomplete and/or bad. Is there another resource available? And by documentation I mean of the library/framework itself, similar to what UNITY, SFML, or SDL all have available.

MSDN is the source for the official documentation, and while you can find tutorials and guides elsewhere you probably won't find a completely re-authored set of docs that are better than MSDN's. If you have a specific issue you can't figure out from the documentation, it may be better to post that as its own question.

You probably won't find documentation available that's as good or better than MSDN, any specific questions / problems, search here and elsewhere online and if you're still not sure post a question.
That said, take a look at the Education Catalog at the App Hub.
While not documentation, it provides many samples and lots of useful information.
Also, take a look at Shawn Hargreves' blog, there are many interesting posts relating to XNA.
There's also an index of older, useful posts.

Thanks for the input, I think Josh had the answer I was looking for though.

I've updated my post to incorporate his comment.

+1 for Shawn Hargreves' blog - I would his posts are better documentation for XNA than the MSDN.  Unfortunately, they won't continue - he recently moved off the XNA team :(

Just to add to George's great answer:
The DirectX documentation (on MSDN) contains many additional details that the XNA documentation does not provide. XNA is a wrapper over DirectX, after all.
Often you can easily guess (or check using PIX or perhaps ILSpy) the underlying DirectX methods that XNA is using, and then look up the documentation for those to find out what you need.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Optimize a render call to draw out several semi-transparent sprites
I'm writing a 2D side-scrolling style game in C++ and openGL. In this game I have several cloud sprites which are rendered across the top of the screen. They rotate and scale and such so they're not static. I'm wondering if there is any way that I can optimize this, because currently every time one of these sprites is rendered, GL has to perform blending between everything already rendered (like the background, etc) and these sprites.
I'm thinking something along the lines of rendering ONLY the clouds together all at once, and then performing a single call where the final result is rendered and blended into the main scene. Not sure how to even go about that or if it will even result in a performance gain. Any suggestions would be greatly appreciated!
Just for clarity, here is what a final render looks like. The clouds are formed by several smaller sprites being populated close together around certain points.

I dont know much about OpenGL, but in DirectX there is alot of speed to be gained by render
to texture techniques
http://ogltotd.blogspot.com/2006/12/render-to-texture.html

Thanks for this, this is along the lines of what I was thinking I just have yet to see if this will actually give a decent increase in performance on mobile. I'll get back to you.

I can tell you that when I created my 3D drag and drop level editor in DirectX, with a custom shader pipeline using Alpha Blending and Antiscopic filtering, it almost tripled my frames,

Marked as correct since you actually pointed me in the right direction. For some reason when I read the other answer, I feel like I'm being lectured by my step father. There was indeed a huge performance bottleneck and although I didn't end up using this exact technique, you still pointed me down the road where I eventually ended up using batching and an alternative GL call to render these batched objects, which greatly increased performance. Not such a waste of time after all I guess, premature optimization that is.

because currently every time one of these sprites is rendered, GL has to perform blending between everything already rendered (like the background, etc) and these sprites.

While rendering with blending isn't the fastest possible rendering mode, it isn't exactly slow either. It doesn't go to each "thing" it has rendered before and blend with it. It's just blending with the destination color in the framebuffer.

I'm thinking something along the lines of rendering ONLY the clouds together all at once, and then performing a single call where the final result is rendered and blended into the main scene.

This is a prime example of premature optimization being the root of all evil. You're "solving" an optimization problem, and your "solution" will not in fact solve the problem. It will create a new problem: overlapped blended objects won't work right. OpenGL's blending functions will only work when you're directly compositing with an opaque destination value. Composting with a transparent value, which you then layer on top of the destination, is not going to provide the correct results.
Don't optimize unless you know something is a performance bottleneck already. That knowledge can only be gained in one of two ways: having a lot of experience in a problem domain or having actual profiling data that shows where the bottleneck is. Just keep making your game; if it turns out to be a problem, you can find a way to solve it later. And you'll know that it is a problem rather than just guessing.

Thanks for the post. I do know for a fact that it is an issue, since I'm testing my game on 3 different mobile devices and 2 different desktops and this specific rendering call absolutely murders the framerate, unless I knock down the number of clouds to about 20 or so. They're not massive textures either. I understand that in the blending function it's performing ops with the destination colour. Does the "size" of the destination, that is both dimensions and the data it's already populated with, not have any effect on the blend performance?

I should clarify - the call murders the framerate on mobile. They're not crappy devices either, dual core tablet and phone etc etc.

@AscensionSystems: Blending is a per-sample/pixel operation. The performance of blending (minus other factors like texture access and bandwidth issues) only depends on the area being covered, not the data that it's blending with.

@AscensionSystems: "unless I knock down the number of clouds to about 20 or so." You were rendering more than 20? How many were you rendering? Are these 2D images of clouds or a particle system?

Yes I was rendering 50. I suppose in a way it is a particle system, I'm trying to render fairly realistic clouds. The clouds are formed by the merging of several smaller textured sprites.

I added a screenshot just for clarity.


text:
Necessary design skills to develop games using Unity, UDK, etc
With my question I want to know if DESIGN 2D/3D skills are necessary in order to create a game using some engine like UDK or Unity.
I have experience as a developer, and experience with openGL, I have also some experience with 3dMax, but Im NOT able to design something from scracth. I simply dont have the skills.
In this kind of engines, is there a way to create and customize levels or characters for example?
Thinking in something related, I will think in the character editor of games like World of Warcraft, etc. I would like to know if the creation of levels and characters would be  like that.

Obviously, assets will need to exist. If you want to make Cubes on a Plane: The Game you won't need much.  Unity is free for indie use (including a 30 day trial for all features) and UDK is free unless you make something like $50K on the game. So, grab them and find out if they will work for your needs: http://unity3d.com/unity/download/ & http://www.udk.com/download

Thanks, I checked both Unity and UDK, but my question is more like, not having any 3d design skills, is there a way to easily create characters? For example, if I want to create a cowboy, do I need to open 3dsMax and create EVEYTHING from scracth, or is there any tool that I can choose the shape, the clothes, the face, etc...

@chaosTechnician: rofl "Cubes on a Plane", brilliant, really brilliant. You deserve many Internets for that.

I'm going through the learning stages on character creation right now, and yes you'll need those skills to make those objects. (I'm a programmer).
I haven't used Unity in almost a year. When I was, I noticed it could only create primitives (cubes, spheres, etc...). So environment creation and character creation were out of the question.
In UDK/UE3 you can do a lot of environment work with their object brushes (create primitives, terrain, edit them, etc...), but the creation of detailed static meshes should still be done by a 3rd party modeling tool (3DSMax, Maya, Blender, etc....). Also for character creation in UDK, that must be done by a 3rd party tool because you need to rig the model.
Hope that helps

Also if you're a student you can get almost all of the tools you'll want to use for free.

Unreal and Unity do not have the kind of feature that you're looking for. There simply isn't a way to easily create a custom character with different sliders and then import it into your game, for that you will have to learn Maya, 3dsMax, or some similar program.
However! Since you have experience as a developer, you should try and feel comfortable with using simple meshes to prototype your games. You don't need all the detail of a animated/rigged/textured cowboy to prove that your game is worth making.
If your design is good and your code is reliable, finding art assets should be the last part you need to worry about.


text:
Can I use SpriteBatch when drawing sprites on a rotating 3D plane
I'd like to have my plane of sprites rotate similarly as in this game (YouTube Video). So basically, everything is drawn in 2D, but the 2D plane is then "rotated in 3D" (or camera is rotated). When rotated, sprites further away should look like they are further away.
Question:
Can I use SpriteBatch with this? IIRC SpriteBatch uses Orthographic view matrix, so probably not? If I can, how? If not, how would you suggest I draw the sprites?
PS. I am really bad at explaining problems so feel free to ask any questions.

I fixed up your question to mention that you're rotating the 2D plane of sprites - as per the video, rather than rotating individual sprites.

Yes!
Let's have a look at how SpriteBatch works:
SpriteBatch draws sprites onto a 2D plane. So if you had wanted to rotate your sprites so that they come "off" this 2D plane, then you'd probably have to find another solution. But, looking at your video, it looks like you want to rotate the entire 2D plane.
SpriteBatch's normal mode of operation uses a built-in orthographic projection matrix into client space. It also lets you pass in an optional global transformation matrix. You could use this global transformation to get your effect, but you'd also have to "pre-undo" the projection matrix that comes afterwards, and the maths is annoying.
But fear not - SpriteBatch has another mode of operation, where it can use any Effect, using that effect's vertex shader and transformation matrices. BasicEffect will do nicely here. Take a look at this article to get the basic principles.
Simply set BasicEffect.Projection matrix to a suitable perspective projection. And then set BasicEffect.World matrix so that your plane of sprites appears in the correct location (and the right way up!).
Take a look at this article as well. It describes the process in more detail.

Just to add a note for those needing to write a custom vertex shader for SpriteBatch - on the second linked article, there's a comment by Remi Gillig which might be helpful too. But in this case you won't need a custom vertex shader since just a regular BasicEffect instance with the correct parameters will do.

Can I use SpriteBatch when drawing sprites with 3D rotation

I'm afraid not.
You can however render the sprites you want to rotate together to a RenderTarget2D. Then skin a quad with the previously mentioned RenderTarget.
This describes the skin and draw a quad part.
Edit: watched the video on my phone :).
Anyways to achieve a similar effect you just need 1 quad and one render target. Draw you whole scene to a rendertarget and apply it to a single quad. you can then either move your camera or quad, whichever you find more convenient.

"and then draw it using an orthogonal camera." I thought I had to use normal ( perspective ) -camera? I want sprites futher away to actually look like they are furthe, like in that video. I thought that isn't possible with orthogonal camera :|

My bad I can't view youtube at work :/ and was assuming that you were going for a super paper mario effect (2d camera w/ 3d sprite transformations). But anyways you can use what ever type of camera you like.

"Technically", no. SpriteBatch exists for 2D sprites.
However, you can supply transformation matrices to the SpriteBatch, and unless I'm mistaken this allows you to skew and stretch your sprite to your heart's content. You would, of course, have to manually calculate everything, but you could fake 3D by clever transformation of 2D.

Can you represent skew using a XNA matrix? I don't think you can.

http://www.senocular.com/flash/tutorials/transformmatrix/

My bad I meant taper and you can't. "Things they cannot do include tapering or distorting with perspective" So using the transformation matrix isn't going to work.

Excellent reference though. I appreciate you sharing it.

@ClassicThunder Actually, you can. That reference Superbest linked describes 2D affine transformation matrices. XNA's matrices are 4x4 matrices and should be able to perform tapering operations. (You should be able to cancel out the built-in ortho matrix completely - see my answer. But I'll leave the maths for someone else ;)


text:
DX11 StreamOut to Vertex Buffer from GeometryShader, can't clear Buffer?
I'm trying to use a geometry shader to continuously modify the positions of vertices, and save the modfied verts in a buffer.
I have two vertex buffers, one is bound to the IA stage / the vertex shader input, the other to the SO stage / the geometry shader output.
After I draw a frame, I swap those two buffers so that (ideally) the saved vertices get modified and saved by the GS again.
What actually happens though is this:
I have two buffers, outVB and inVB, both are empty, and an initial, vertex generating vertex shader is set

(Frame 1) Draw(..), the initial vertices are processed, saved to outVB, and drawn
I set inVB as the SO target, and outVB as the input vertex buffer
(Frame 2) Draw(..), vertices are read from outVB, processed, saved to inVB, and drawn
I swap the buffers
(Frame 3) Draw(..), vertices are read from inVB, processed, (apparently not)saved, and drawn
I swap the buffers
(Frame 4) the same output appears as in Frame 2
I swap the buffers
(Frame 5) the same output appars as in Frame 3

and it continues alternating between those two frames, which lead me to believe the buffers still contain the data they held the first time they were written to.
Which makes sense, as the GS can only append new data to the provided buffer.
So I tried releasing and recreating the buffer that is to become the new stream out target before swapping them (I couldn't find any way to clear it), which makes it produce 5 unique frames (including the initial one), and it loops over the last 4 frames, which makes no sense to me at all.
Destroying the buffer holding the old data and recreating it seems to work, since it progresses beyond the states of Frame 2 and 3, but if it worked how can it revert back to the states of Frames 2 and 3 after drawing two more?
my shaders are really simple so far:
struct GS_OUT {
    float4 Pos : SV_POSITION;
    float4 Col : COLOR;
};

GS_OUT VS(GS_OUT input)
{
    return input;
}

[maxvertexcount(10)]
void GS(point GS_OUT input[1], inout PointStream<GS_OUT> PStream )
{
    float4 position = input[0].Pos + float4(0.1f, 0.1f, 0, 1);

    GS_OUT output;
    output.Pos = position;
    output.Col = float4(1,1,1,1);

    PStream.Append(output);
}

float4 PS(GS_OUT input) : SV_TARGET
{
    return inut.Col;
}

My code for flipping the buffers (not neat, I know I could just flip the pointers then assign, but I wanted to make sure everything happened in exactly the order I want):
void swapVBs()
{
    static bool flip = true;

    UINT bufferstride = 2*sizeof(XMFLOAT4);
    ID3D11Buffer *nobuffer = NULL;
    UINT offset = 0;

    D3D11_BUFFER_DESC vbdesc;
    vbdesc.BindFlags = D3D11_BIND_STREAM_OUTPUT | D3D11_BIND_VERTEX_BUFFER;
    vbdesc.ByteWidth = 640*360*2*sizeof(XMFLOAT4);
    vbdesc.CPUAccessFlags = 0;
    vbdesc.MiscFlags = 0;
    vbdesc.StructureByteStride = 0;
    vbdesc.Usage = D3D11_USAGE_DEFAULT;

    if (flip) // SO Target == inVB, Vertex Buffer == outVB
    {

        //clear SO target
        devcon->SOSetTargets(1, &nobuffer, 0);
        //make inVB Vertex Buffer
        devcon->IASetVertexBuffers(0, 1, &inVB, &bufferstride, &offset);

        outVB->Release();
        device->CreateBuffer(&vbdesc, NULL, &outVB);

        //make outVB SO target
        devcon->SOSetTargets(1, &outVB, 0);

    }

    if (! flip) // SO Target == outVB, Vertex Buffer == inVB
    {

        //clear SO target
        devcon->SOSetTargets(1, &nobuffer, 0);
        //make outVB Vertex Buffer
        devcon->IASetVertexBuffers(0, 1, &outVB, &bufferstride,  &offset);

        inVB->Release();
        device->CreateBuffer(&vbdesc, NULL, &inVB);

        //make inVB SO target
        devcon->SOSetTargets(1, &inVB, 0);

    }

    flip = !flip;
}

and the draw code is nothing more than
devcon->DrawAuto();
swapVBs();

So I guess I'm asking...how do I properly clear a ID3D11Buffer?
Why in the world does releasing and creating a new buffer not give me an empty buffer?

I found the problem,
ID3D11DeviceContext::SOSetTargets(..)  expects a pointer to an array of offsets as the third param, but I've been passing a nullpointer (thinking it would assume I don't want an offset).
The default behavoir seems to be to assume a value of -1, which makes the GS append writes to the last position in the buffer that was written to, which in my case always seems to have been the end, causing no new vertices to be written.
Passing an actual pointer to an UINT offset = 0; works like a charm and the geometry shader overwrites the contents of the buffer.

Yikes.  Good to know.  That definitely seems like a bug in D3D11, if that's what it's doing.


text:
How should I unbind and delete OpenAL buffers?
I'm using OpenAL to play sounds. I'm trying to implement a fire-and-forget play function that takes a buffer ID and assigns it to a source from a pool I have previously allocated, and plays it. However, there is a problem with object lifetimes.
In OpenGL, delete functions either automatically unbind things (e.g. textures), or automatically deletes the thing when it eventually is unbound (e.g. shaders) and so it's usually easy to manage deletion. However alDeleteBuffers instead simply fails with AL_INVALID_OPERATION if the buffer is still bound to a source.
Is there an idiomatic way to "delete" OpenAL buffers that allows them to finish playing, and then automatically unbinds and really them? Do I need to tie buffer management more deeply into the source pool (e.g. deleting a buffer requires checking all the allocated sources also)?
Similarly, is there an idiomatic way to unbind (but not delete) buffers when they are finished playing? It would be nice if, when I was looking for a free source, I only needed to see if a buffer was attached at all and not bother checking the source state.
(I'm using C++, although approaches for C are also fine. Approaches assuming a GCd language and using finalizers are probably not applicable.)

If you still need an answer, I used a garbage collection method in Gorgon engine: http://sf.net/p/gorgon-ge

Before deleting a buffer you must unbind it from each source that uses it (ex: alSourcei(mSourceId, AL_BUFFER, NULL); or delete all sources which are bound to the buffer.
You need to keep track of the length of each of your sounds to release them upon completions. You can do this using a structure for each source to keep the sound length and the time played (updated each game tick). Ex:
struct AudioVoice
{
    ALuint          mSourceId;
    ALuint          mMsDuration;
    ALuint          mMsPlayed;
};

If you use a component based system you can periodically check all running sources for completion and do the unbind/source delete there.
If you don't keep track of the play/pause changes in your code you will also want to check if the sources are playing before increasing the played time.
ALint sourceState;
alGetSourcei(mSourceId, AL_SOURCE_STATE, &sourceState);
if (sourceState == AL_PLAYING) { /* increase played time */  }

If you want to keep track of the sources bound to a buffer you can use a structure with the id of your buffer and a vector linking to the source structures this way you can even interrupt all sources which are bound to a buffer you need to release ASAP. Ex:
struct AudioData
{
    RKuint                      mMsDuration;
    ALuint                      mSourceId;
    std::vector<AudioVoice*>    mVoices;
};

This should be enough to get you on the right track. I can't give you more detailed code from my projects as they heavily rely on macros and hand made RTTI mechanisms.


text:
Should I go with OpenGL to see my future in Game Development industry?

Possible Duplicate:
Should I continue studying OpenGL or just switch to DirectX to  give me a better chance of landing a job in the game industry?

I tried Google but found quite old articles, so I am in search of an answer in context to year 2012.
Hi all, I don't know if you will consider this question appropriate for this community but I am constantly searching for a perfect answer.
What I have seen is that most of the games that are released these days are DirectX 1x based. Except for few games like Starcraft or Diablo which don't have high end graphics are using OpenGL.
So I have few questions to ask.
The platforms i would like to target are PC (windows), Xbox 360 and PS3 (must).

Should I go with learning OpenGL to see my future in game development industry? Or should I shift to Directx?
If I learn OpenGL first, will it be difficult to learn direcx then?
Which API is most suitable for indie development?
Which one of the two API's are better from coder's (programmer's) point of view? Like OOP and style of coding.

Is openGL being cross platform should be the only reason to choose it over Directx? Even when vendors are not providing enough stable drivers for it.
Thanks in advance.
I have read this post, but I have few questions.
Should I continue studying OpenGL or just switch to DirectX to  give me a better chance of landing a job in the game industry?

Firstly, if your making games, are you sure you want to be making game engines from scratch rather than using something like Unity, Unreal's engine and so on?

OpenGL is needed on Mobile phones, OSX and every console other than the X-Box (well the other console use their own thing thats a stripped down OpenGL similar to OpenGL ES since ES 2.0 wasn't out back then). So you will definitely need it in the games industry. You will probably also need DirectX. Having said that I think most game devs now program using premade off the shelf engines and don't worry about the graphics API (other than possibly things like shaders).
I don't know much DirectX (being a Linux user myself) but I can't see learning 1 really causing you problems learning the other. They should bother share similar underlying concepts. The main thing would be the coordinate system.
For an indie game developer it can depend. Indie games are niche products. Having support for other platforms such as OSX can give you a large number of extra sales as the number of game available on the platform is fairly limited and there more likely wanting to boost support for their platforms. You can also throw in Linux support for little extra and get some good PR (the main hassle is building for a whole bunch of different targets). Mobile phones are also something to look at as they all use OpenGL ES. Porting to WebGL is also another possibility with things like Google's Nativeclient and emscripten (Compiles code to JavaScript) or just redoing it in JavaScript (or even using JavaScript across the board the desktop, web and mobile).

Having said that, many indie devs make stuff using XNA and sell through the Xbox store. Since it's built right into the Xbox they get some good sales and XNA seems like a good platform.
4) Once again I'm not that familiar with DirectX.
I've heard John Carmack prefers DirectX and I also saw the dev working on the infinity universe engine say similar things (But they went to DX11 from whatever OGL version they where targeting, Carmack would probably have been using an older OpenGL version). But OpenGL has had massive changes recently, many of which have made coding in it much easier (uniform buffer objects, GLSL uniform routines). Those changes will take a while to roll out.
OpenGL doesn't have much OOP. It does however refer to things as 'Objects' (VertexBufferObjects, VertexArrayObjects, TextureObjects, FrameBufferObjects). Those things are fairly easy to wrap in a class for whatever language your using. You don't need to implement the whole API just the parts you want. There is a C++ binding called OGLplus although it's newish and not widely used.
From what I can see from Googling DirectX also requires similar OOP frameworks to be produced.
If they both need the frameworks then the coding probably doesn't matter to much since you should only be using it in the framework.
Finally OpenGL gets some flac for having broken implementation on some system (Such as netbooks with Intel chipsets, even the ones that do work are often only OpenGL 2.x).
Or being out of date on many system (The latest version of OSX 10.7.x has 3.2, the previous version 10.6.x was 3.0, then 10.5.x is either 2.0, 1.5 or 1.3 depending on the video card (Minecraft sticks to 1.3 as it's render target for basically this reason), those systems are going to be stuck at that OpenGL version forever unless the users pay for an upgrade and 10.5 was only released in 2007 so you will have to live with it for a while longer). One good thing is you can just target what extensions you want and make your framework support fallbacks (For example you can make a VertexBufferObject class that will use the 1 vertex at a time fixed pipeline functionality if the VBO extension is missing). Also remember OSX doesn't support DirectX at all.

I'm going to say that you nailed the right answer in your first sentence.  Don't bother with OpenGL/DirectX/Whatever.  Just use something like Unity.

First thanks for such a detailed answer. The only problem I am facing in choosing OpenGL is that it does not have good tools to work on.
Even I thought to go with Unity3D at first but I wanted to get a good hold on 3D programming first before stepping out and learning other software.

also if you could tell me a good way to learn OpenGL. If you could suggest me few books that would be great.
And how about SuperBible covering 3.x.
Will it be difficult to learn 4.x if I start with SuperBible covering 3.x?

@TimHolt If the intended position is a gameplay programmer or level designer, then yes, learning Unity or UDK is very appropriate.  However, if the intention is to work on an engine, then every gritty low-level detail should be examined, even compilers :)

@Priyank: OpenGL 3.x and 4.x are very similar. In fact if you use shaders and Vertex Buffer Objects (VBOs), you can make programs that work with OpenGL 1.5+ while still being similar in overall design to 3.x/4.x programs. But newer versions of OpenGL make code a lot simpler. For example you don't have to bind uniform variables to specific ids as you can do it in your GLSL code using the layout keyword. You can store all your uniforms in a shared uniform buffer object rather than upload one at a time to each shader. You can use uniform routines to shrink the number of shaders you need.

@Priyank: The OpenGL programming guide (Red Book) is getting a new 8th edition in June/July that should helpfully teach a modern OpenGL approach (the 7th teaches OpenGL 3.x but relies heavily on deprecated functionality). The OpenGL 4.0 Shading Language cookbook teaches quite a bit about 4.x even though it's GLSL. The newer OpenGL Superbible but it relies on a toolkit. Also online tuts: This and Wikibooks

The answer whenever a beginner asks 'should I learn this or that' is always: Learn everything you can. Honestly, I don't understand why people would think they can only possibly learn one of the alternatives.
And yes, your chances of getting a job writing rendering code as your first games industry job are slim unless you are so into rendering that you write some amazing demos, in which case you'd probably not be asking this question. And even if you did get hired to work on rendering it's most likely to be working on modifications to an existing engine where the knowlege of maths related to graphics and the skill of being able to read and understand other people's code is worth 100x the knowlege of any particular API.
For all those reasons I'd suggest writing as much code as you can as early as you can and to do that in OpenGL, simply because it's a 'C' style API and thus easier for a beginner to get to grips with.
btw. I have to correct the myth that comes up time and time again whenever OpenGL vs. DirectX is discussed, to paraphrase "that DirectX is used on Windows and XBox and OpenGL is used everywhere else". This is not true. OpenGL is useful for MacOS or Linux development, although neither are big games platforms. And OpenGL in it's ES form is most widely used on mobiles and tables these days. But NO current generation games console uses OpenGL, in fact the only games console I'm aware of that ever used it was the N64. PS3 and Wii developers post commands buffers directly the GPU using libraries supplied by the platform and Xbox 360 uses a modified form of DirectX.

I think you said absolutely correct that one should learn everything or at least try. Even I too want to do this. But I just want to know that learning which one of the two API's would help me understand the basics of 3D programming easily and in a better way.
and I think that PS3 uses OpenGL ES with Sony's extensions.

As a beginner, I think shooting for cross-platform is a huge mistake.  It's just adding an extra layer of complexity that you don't need right now; what you need is to focus on learning core concepts and how they fit in to the overall flow of a graphics pipeline and structure of a program.
Either of OpenGL or Direct3D will give you that.
I have to admit right now that I'm biased so take the next two points with an appropriately sized grain of salt.

Driver quality is hugely important and even more so for a beginner.  If something goes wrong you need a fairly reasonable reassurance that it's due to a problem in your own code and not a driver bug.  Direct3D drivers are just so much higher quality, owing to not needing to support decades of accumulated legacy, having a simpler driver model and a tighter certification process.
Tools, documentation, examples, etc tend to be better for Direct3D.  In particular you get the debug runtimes and PIX, both of which are extremely valuable for hunting down problems in your code.

U62's final paragraph is correct - OpenGL is not as portable as it is often made out to be.  You can achieve a certain level of portability by restricting youself to a common subset of full OpenGL and OpenGL ES, but again with the extra layer of complexity thing.  It's most definitely not a simple "recompile and off you go" however, and even if it were you would still have to deal with other platform-specific subsystems (sound, memory, input, file access, threading, networking, windowing, etc) - the code for which may even dwarf the rendering code.


text:
How can I calculate a vertex normal for a hard edge?
Here is a picture of a lovely polygon:

Circled is a vertex, and numbered are its adjacent faces.  I have calculated the normals of those faces as such (not yet normalized, 0-indexed):
Vertex 1 normal 0:   0.000000   0.000000    -0.250000
Vertex 1 normal 1:   0.000000   0.000000    -0.250000
Vertex 1 normal 2:  -0.250000   0.000000     0.000000
Vertex 1 normal 3:  -0.250000   0.000000     0.000000
Vertex 1 normal 4:   0.250000   0.000000     0.000000

What I'm wondering is, how can I determine, taken as given that I want this vertex to represent a hard edge, whether its normal should be the normal of 1/2 or 3/4?  My plan after I glanced at the sketch I used to put this together was "Ha!  I'll just use whichever two faces have the same normal!" and now I see that there are two sets of two faces for which this is true.
Is there a rule I can apply based on the face winding, angle of the adjacent edges, moon phase, coin flip, to consistently choose a normal direction for this box?
For the record, all of the other polygons I plan to use will have their normals dictated in Maya, but after encountering this problem, it made me really curious.

You'll need to duplicate the normal for the corner N times (where N is the number of "sides" it is shared amongst). If you try to use one value for all "sides," you'll end up averaging it, and your lighting will not appear to have that hard edge that you're looking for.

So presuming I was using OpenGL indexed vertices, because I am, you're saying I couldn't use this vertex for all five of these triangles, I'd have to duplicate it for 1/2, 3/4, and 5?

You can use the same vertex for all 5 triangles it touches; you'll just use the same index to point to it where appropriate. Since the 5 triangles in question need 3 different normals, you'll have to have 3 different normals and use the correct indices for them. However, the vertices involved with triangles 1 and 2 all share the same normal. In fact, for your rectangular prism, you'll only need 6 different normals.

Woah!  I don't know why, but having multiple normals per vertex hadn't even occurred to me.  Thanks!

Glad to help! Hint: you probably need 8 vertices and 6 normals.  And probably 4, 8, or 24 tex coords...


text:
How to pause and resume a game in XNA using the same key?
I'm attempting to implement a really simple game state system, this is my first game - trying to make a Tetris clone.  I'd consider myself a novice programmer at best. I've been testing it out by drawing different textures to the screen depending on the current state.
The 'Not Playing' state seems to work fine, I press Space and it changes to 'Playing', but when I press 'P' to pause or resume the game nothing happens. I tried checking current and previous keyboard states thinking it was happening to fast for me to see, but again nothing seemed to happen. If I change either the pause or resume, so they're both different, it works as intended.
I'm clearly missing something obvious, or completely lacking some know-how in regards to how update and/or the keyboard states work.
Here's what I have in my Update method at the moment:
    protected override void Update(GameTime gameTime)
    {
        KeyboardState CurrentKeyboardState = Keyboard.GetState();

        // Allows the game to exit
        if (CurrentKeyboardState.IsKeyDown(Keys.Escape))
            this.Exit();

        // TODO: Add your update logic here

        if (CurrentGameState == GameStates.NotPlaying)
        {
            if (CurrentKeyboardState.IsKeyDown(Keys.Space))
                CurrentGameState = GameStates.Playing;
        }

        if (CurrentGameState == GameStates.Playing)
        {
            if (CurrentKeyboardState.IsKeyDown(Keys.P))
                CurrentGameState = GameStates.Paused;
        }

        if (CurrentGameState == GameStates.Paused)
        {
            if (CurrentKeyboardState.IsKeyDown(Keys.P))
                CurrentGameState = GameStates.Playing;
        }

        base.Update(gameTime);
    }

When playing and you hit the P key your if(CurrentGameState == GameStates.Playing) block is executed, changing the state to paused. Then the if(CurrentGameState == GameStates.Paused) block that follows also runs (because you just changed the state to paused above and the P key state hasn't changed), changing the game state back to playing. This is why you never experience the paused state.
At the very least, I'd make the code for each state exclusive within the update method, either by using a switch statement or the following:
if (CurrentGameState == GameStates.NotPlaying)
{
  // do stuff
}
else if (CurrentGameState == GameStates.Playing)
{
  // do stuff
}
else if (CurrentGameState == GameStates.Paused)
{
  // do stuff
}

The else if statement made the difference. I had to add in a previous keyboard state to keep it from updating every frame...I was almost there on my own. I knew it would be something obvious.

As others have mentioned: Immediately after you set the gamestate to paused, it enters the following if-block and sets the state back to playing.
Sure, the simple fix is to include an else between the two states, but that will cause yet an other problem because IsKeyDown will return true in sequential updates, and since updates happen 40+ times per second, you will temporarily unpause for one frame, then pause the very next, and back and forth until the key is released.
The real solution is to detect the moment when the key is released (or pressed if you want to do it backwards). This can be done by storing the previous keyboard state, and comparing that to the current keyboard state. Something like:
if (LastKeyboardState.IsKeyDown(Keys.P) && !CurrentKeyboardState.IsKeyDown(Keys.P))
{
    // The 'P' key has just been released
    // This will only fire ONCE when the 'P' key is released
}

I would recommend making a wrapper class for the keyboard that handles this for you, but that is up to you.

Since there are many ways to skin a cat, Here's another:
bool gamePaused = false;
KeyboardState currentKB, previousKB;
protected override void Update(GameTime gameTime)
{
    previousKB = currentKB;
    currentKB = Keyboard.GetState();

    if (currentKB.IsKeyDown(Keys.Escape)) Exit();
    if (currentKB.IsKeyUp(Keys.P) && previousKB.IsKeyDown(Keys.P)) gamePaused = !gamePaused;

    if (gamePaused) return;

    //do update stuff here

    base.Update(gameTime);
}

There is a simple explanation here.

Look closely at the logic you have to pause and unpause:
if (CurrentGameState == GameStates.Playing)
{
    if (CurrentKeyboardState.IsKeyDown(Keys.P))
        CurrentGameState = GameStates.Paused;
}

if (CurrentGameState == GameStates.Paused)
{
    if (CurrentKeyboardState.IsKeyDown(Keys.P))
        CurrentGameState = GameStates.Playing;
}

If your game is playing and you have pressed P this frame, the first set if statements' conditions will be true.  This will change CurrentGameState to Paused which will then make the second set of conditions true, chaning it back to Playing.
You'll probably just need to set up a series of conditionals that exclusively check the game state at the beginning of the frame.  Either by using a switch statement instead of a series of ifs or at least putting subsequent ifs within else blocks:
if (CurrentGameState == GameStates.Playing)
{
    if (CurrentKeyboardState.IsKeyDown(Keys.P))
        CurrentGameState = GameStates.Paused;
}
else if (CurrentGameState == GameStates.Paused)
{
    if (CurrentKeyboardState.IsKeyDown(Keys.P))
        CurrentGameState = GameStates.Playing;
}

Yep, else if saved the day. Too bad I can't give you both credit...and I can't even up vote due to lack of rep.


text:
Attributes and Behaviours in game object design
Recently I have read interesting slides about game object design written by Marcin Chady Theory and Practice of the Game Object Component Architecture. I have prototyped quick sample that utilize all Attributes\Behaviour idea with some sample data.
Now I have faced a little problem when I added a RenderingSystem to my prototype application. I have created an object with RenderBehaviour which listens for messages (OnMessage function) like MovedObject in order to mark them as invalid and in OnUpdate pass I am inserting a new renderable object to rederer queue. I have noticed that rendering updates should be the last thing made in single frame and this causes RenderBehaviour to depend on any other Behaviour that changes object position (i.ex. PhysicsSystem and PhysicsBehaviour).
I am not even sure if I am doing this the way it should be. Do you have any clues that might put me on the right track?

As a rule of thumb there is no right or wrong way of doing the rendering, it all depends on your architecture and game.
Rendering is usually done outside of the component based system, despite this you will either reference your models from a renderable system where the updates on position will be done or the models will fetch the latest animations frame and position themselves before each draw.
Usually I simply duplicate data (position, skeleton, animation) and sync it when needed.