# Question
Title: Does CADisplayLink automatically control the app's timestep?
I'm writing an iOS game that uses OpenGL ES 2.0. I have my 'OpenGLView' which contains a

```
- (void)setupDisplayLink {
    CADisplayLink* displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(render:)];
    [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}

```

And then my

```
- (void)render:(CADisplayLink*)displayLink {

```

function which at the end of the processing calls

```
[_context presentRenderbuffer:GL_RENDERBUFFER];

```

Like most people I've found the http://gafferongames.com/game-physics/fix-your-timestep/ tutorial but I've been thinking.

With a CADisplayLink, has the framerate limiting been done for me already by iOS, meaning I don't need to calculate the timing of each frame?

Also, as a sanity check, the 'render' function is where *all* my game logic goes? I'm currently treating it as the equivalent of a

```
while (!quit) {
  do_stuff();
  render();
}

```

loop you see in traditional game loop designs, or is this only for rendering?

# Answer
> 3 votes
A `CADisplayLink` does indeed do framerate limiting. Under normal operation, you will never get `-render:` messages any faster than the display's refresh rate.

I'm not sure what the standard practice for doing game logic in `-render:` is, but I can tell you two things: one, `CADisplayLink` was not designed to run both your rendering and your game logic, and two, it's easier but less performant to let it handle both.

For example, if you overshoot a frame slightly once, `CADisplayLink` may wait for the next refresh before calling into your code, which would deprive you of useful time in which you could be updating your game state. But you also can't simply go into a standard "until-quit" game loop (at least on the main thread): your display link will not fire then.

The first thing I'd be tempted to try is a `CADisplayLink` that only does rendering, and a `dispatch_async`-driven update loop, where the game's update step dispatches another update step when it completes. In theory, that would allow `-render:` to happen if necessary, but immediately start another update step if not. If you want a fixed timestep, you may be able to use `dispatch_after` to force your next update frame to wait a certain duration.

I have no idea if the above is workable, unfortunately, this is merely the first thing I'd try.

---
Tags: ios
---


title: Shader and Custom Vertex Format Errors

text:
# Question
Title: Shader and Custom Vertex Format Errors
I am creating an editor of sorts that allow you to create 3D voxel models. I just got started and have ran into a few errors. Here is what it is producing:

I think the problem has to do with the way I am handling my vertex format (VertexPositionNormalColor) shader or the way either of them are written:

```
    struct VertexPositionNormalColor {
        Vector3 position;
        Vector3 normal;

        Color color;

        public readonly static VertexDeclaration VertexDeclaration = new VertexDeclaration(
            new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
            new VertexElement(sizeof(float) * 3, VertexElementFormat.Vector3, VertexElementUsage.Normal, 1),
            new VertexElement(sizeof(float) * 6, VertexElementFormat.Vector4, VertexElementUsage.Color, 0)
        );

        public VertexPositionNormalColor(Vector3 position, Vector3 normal, Color color) {
            this.position = position;
            this.normal = normal;
            this.color = color;
        }
    }

```

Shader code:

```
struct ColoredVertexToPixel  {
    float4 Position     : POSITION;
    float4 Color        : COLOR0;
};

struct ColoredPixelToFrame  {
    float4 Color        : COLOR0;
};

ColoredVertexToPixel ColoredVertexShader(float4 inPosition : POSITION, float3 inNormal : NORMAL, float4 inColor : COLOR0)  {
    ColoredVertexToPixel Output = (ColoredVertexToPixel)0;

    float4 worldPos = mul(inPosition, World);
    float4 viewPos = mul(worldPos, View);

    Output.Position = mul(viewPos, Projection);
    Output.Color = inColor;

    // TODO: Implement basic lighting

    return Output;
}

ColoredPixelToFrame ColoredPixelShader(ColoredVertexToPixel PSIn)  {
    ColoredPixelToFrame Output = (ColoredPixelToFrame)0;

    Output.Color = PSIn.Color;

    return Output;
}

technique ColoredBlock  {
    pass Pass0  {
        VertexShader = compile vs_2_0 ColoredVertexShader();
        PixelShader = compile ps_2_0 ColoredPixelShader();
    }
}

```

I also tryed the object creation code in another project with a different effect file and vertex format and it worked fine. This is defiantly a shader/vertex format error as I set each vertex with the exact same color, so maybe the color and position data in the shader is getting with each other?

Any ideas?

Thanks

# Answer
> 3 votes
First, and since you are using only one normal channel, I would change the `UsageIndex` of your `VertexElementUsage.Normal` from 1 to 0.

And for your color channel, your vertex buffer is expecting a `VertexElementFormat.Vector4`, that is, 4 float components. The type used for colors in XNA is a special 32-bit encoded value, so change it to `VertexElementFormat.Color`.

---
Tags: xna, c#, hlsl, vertex, color
---


# Question
Title: Why is antialiasing dependent on sampling?
I am thinking about the best ways to render two dimensional objects in the highest detail possible using modern graphics technology and it occurred to me that when I simplify a situation enough, I ought to be able to calculate the exact percentage of coverage of a triangle over a pixel, at least for the cases where an edge spans a pixel. This is, after all, the primary issue that multisampling and supersampling are dealing with, the issue of coverage.

I now realize that the question of how to exactly produce the coverage of the pixel that the vertices lie on is a much more difficult one.

Is it fair for me to say that it is theoretically possible to perform such a calculation on programmable shaders? After all, it's quite possible to compute the area covered by an arbitrary triangle which lies over a grid, on all the grid cells.

I guess I seem to have already come up with an explanation of why not do antialiasing this way: the corners.

# Answer
If you are dealing with more than one triangle in your world, the corners aren't even the only problem. If you're rendering an antialiased triangle over a known background, you can calculate the coverage at a pixel and blend using that alpha. But if you then render a second triangle over the first one, you have to ask a question: Did this second triangle block the first one? Did the first one block the second? Did they not overlap at all? Did they partially overlap? For an unbounded number of triangles, it's a very hard problem to solve "perfectly"—you have to remember every triangle that intersects that pixel (unless there are clever algorithms that I am unfamiliar with).

It's *possible* to perform such a calculation, it's simply impractical.
> 4 votes

# Answer
A pixel is a single sample of the various geometrical shapes at that point. Supersampling is essentially a way of better approximating those shapes. An analogy is the rectangle method as a way of estimating the area under a curve, and which produces better estimates for more, smaller rectangles.

It is possible to beat such approximative methods if you have access to the original geometry, just as you can calculate the area under a curve precisely if you know the formula for the curve. The problem with computer graphics is that by the time you want to render a single pixel, you've discarded all those triangles many operations ago. A computer with enough resources could remember every triangle that affects a given pixel and then, once all the triangles were drawn, could construct the final pixel value based on that. Obviously that would be immensely impractical so instead we take a representative sample from each triangle and throw away the precise information. Supersampling means we take more information from each one and reduce the aliasing, but it can't be avoided entirely once you cross over from the analogue domain into the digital.
> 0 votes

---
Tags: graphics, shaders, rendering, antialiasing
---


title: Designing a game - Where to start?

text:
# Question
Title: Designing a game - Where to start?
A friend of mine and I are planning a game together to work on in our free time. It's not an extensive game, but it's not a simple one either.

He's working on the story behind the game while I'm working on the graphics and code.

I don't really know where to start with the game. We know what the basic type of game it's going to be and how it would be played, but I'm having a hard time of actually knowing where to begin.

I have Xcode open but I don't really even know what I should be designing first.

What is some advice for this writer's block? Where is a good place to start with a game? Should I design all the graphics and layout before even touching Xcode? Should I program the things I know I'll have difficulty with first before getting to the easy stuff?

# Answer
> 30 votes
Start by getting something up and playable. Don't spend more than an hour on graphics, just render the game with rubbish placeholders. Games don't have objective requirements to build to: the key requirement is that it be fun, and evaluating whether a game is fun or not requires playing it; as a result, game design should follow an iterative approach. (I recommend Tom Wujec on the marshmallow challenge as an orientation on iterative design.

# Answer
> 16 votes
Create something on paper, and by that I mean make a mock-up board and cut-out pieces. Make rules and play your game on the paper mock-up. Use that to break out your code design into feature sets and modules that you can work on. This process will help your friend design the story and how the game works, too.

You may be tempted to write extra features into your code, avoid that. You are prototyping to see what will work.

Once you have a small piece up and running you should work iteratively and at each iteration get just one more feature running. When something isn't playing well go back and changes features. Keep iterating and changing.

The basic idea is to have the long term vision based on your paper mock-up, and from that a series of short term goals to work on that get you to where you want to go a piece at a time and without the stress of "omg what do I do next?"

# Answer
> 4 votes
Evaluate your requirements first. Coding without a plan creates a lot of waste later.

What does the game functionally need to do? What frameworks do you need to make that work? What are the elements that can be borrowed from existing frameworks, and what do you need to write yourself?

Before opening Xcode, it might help to just make paper cutouts, and run through all of the game interfaces and dialogs first. This will give you some idea of what you need to create in Interface Builder.

Next, how do things interact? What are the distinct styles of interaction required? That should give you some idea how the controllers need to be divvied up, started and stopped.

Don't plan it to death, but clearly define your requirements, and as soon as you can break the project into bite sized (30min-1hour) pieces, you're ready to start coding.

Looking at 2 days, 2 weeks, or worse, 2 months worth of tasks engages a fight or flight reaction. Break it into small enough pieces that you can bite each one off sequentially without choking, and my guess is you'll know exactly which bite to start with, and which one to go after next.

# Answer
> 3 votes
If the game is supposed to fit into an existing genre, or it is somehow similar to another game, simply try to make a crude, simple imitation of that game, or make a "typical" example of the genre. If you are not a good coder, follow a tutorial which will walk you through making a game similar to yours.

After a while, you should naturally feel the urge to "diverge" from your model, and start taking the game in your own direction. From there it's a downhill road of adding a feature there, fixing a bug here, and generally improving in small steps.

If there is a certain concept that is somehow unique to your game, you might also start by building the simplest demonstration of that concept. There's also the option of simply building your game around that concept.

# Answer
> 2 votes
Do the things that give you a playable prototype as soon as possible.

The first 1-2 weeks you propably can not make good estimates, because you are new to the engine. So in the first week(s) its probably a waste of time to do estimates. But do note the time you spent for stuff, so you have some experience you can base your first estimates on. After that time start to plan, estimate and set priorities!

Three things I've learnt from the last 6 months where I was part of a not successful game project (I was paid to be the dev implementing game logic):

1. Do not change your plan every day! It's obviously a good thing to go an agile path, but if you end up changing your goals every day, clearly something is wrong.
2. Keep track of the time you spend on your work. Compare estimated and effective times. At first you will probably note a big difference, but over time you should be able to make better estimates.
3. Take estimates into account when setting priorities.

Important: From time to time take a look back on the project and see what went well and what did go wrong. I guess you can identify parts where you spent too much time on something not needed. Try to leave such things out the next time. (For example: If you work on a gadget that your player can use 1 or 2 times in the game for 2 seconds, don't spend a whole month on the implementation.)

# Answer
> 1 votes
If you don't know how to properly design a project, i suggest reading chapter 1 of Bruce Eckel's Thinking in C++ (the book is free), there's a section named "Analysis and design". It's a good introduction.

Be sure to checkout Bruce Eckel's Thinking in C++ Volume 2.

---
Tags: game-design
---


title: XNA sword sprite collision detection

text:
# Question
Title: XNA sword sprite collision detection
I am new to XNA and I am having problems with collision detection when I rotate my sword. I am using a rectangle bounding box approach and I don't know how I can rotate my rectangle together with the sword sprite.

http://picpaste.com/pics/f10268c108e885498a4ae603ab030a60.1328941784.png

Any suggestions on how can i solve my problem is really appreciated. Thanks!

# Answer
I believe this article will be of some help to you. It has sample code that will show you how to rotate the points on a rectangle but also show you how to use the separating axis theorem to detect collisions on a rotated shape (in this case your collision box). On a side note, the web site is also a great resource for learning XNA.

http://www.xnadevelopment.com/tutorials/rotatedrectanglecollisions/rotatedrectanglecollisions.shtml

One other solution might be to use a few points (instead of rectangles) that change when the animation changes. Then use those points to detect collisions. I've heard of storing these points alongside animation frame data in an .xml file. Might make for a simpler approach than using the separating axis theorem. Hope this helps. Good luck.
> 2 votes

# Answer
use a bounding circle instead with the 0-90 degree angle being the distance you can slash vertically for example.
> 0 votes

---
Tags: xna, game-design
---


# Question
Title: Real time data retrieval - database vs file system
I'm planning to develop a game in which I want to draw 3d models in real time using some given x,y,z coordinates. The coordinates will be given at an average of 30 coordinates per second. Drawing will happen maximum of 15 seconds (450 coordinate sets)

For faster retrieval what, is the most efficient way of retrieving data? Is it storing in file system (storing coordinates in a text file etc.) or storing the coordinates in a database (SQL).

# Answer
For real-time retrieval you wouldn't use a text file or a database - you'd have the data in memory. It's not clear why you would want to persist these details to the disk if you're just rendering them on-screen.
> 4 votes

# Answer
No matter where do these coordinates come from (database or filesystem), before drawing them, you should load them into memory and cache them for drawing. Is your memory big enough to contain all coordinates? I guess it shouldn't be a problem.
> 2 votes

---
Tags: coordinates, databases
---


# Question
Title: Unable to connect to UDP server using ip as hostname
i have a little promblem. When i connect to my UDP server using localhost as a hostname, everything goes fine, but when i use my ip as a hostname, the client cant connect to the server. What could couse such issue? As i know the server and the client are fine, because i had the same problem with other servers. But if i'm not right, i give you the code... Server:

```
import java.io.*;
import java.net.*;
import java.util.*;

public class UDPServer extends Thread {
    public final static int PORT = 7331;
    private final static int BUFFER = 1024;

    private DatagramSocket socket;
    private ArrayList<InetAddress> clientAddresses;
    private ArrayList<Integer> clientPorts;
    private HashSet<String> existingClients;
    public UDPServer() throws IOException {
        socket = new DatagramSocket(PORT);
        clientAddresses = new ArrayList();
        clientPorts = new ArrayList();
        existingClients = new HashSet();
    }

    public void run() {
        byte[] buf = new byte[BUFFER];
        while (true) {
            try {
                Arrays.fill(buf, (byte)0);
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                socket.receive(packet);

                String content = new String(buf, buf.length);

                InetAddress clientAddress = packet.getAddress();
                int clientPort = packet.getPort();

                String id = clientAddress.toString() + "," + clientPort;
                if (!existingClients.contains(id)) {
                    existingClients.add( id );
                    clientPorts.add( clientPort );
                    clientAddresses.add(clientAddress);
                }

                System.out.println(id + " : " + content);
                byte[] data = (id + " : " +  content).getBytes();
                for (int i=0; i < clientAddresses.size(); i++) {
                    InetAddress cl = clientAddresses.get(i);
                    int cp = clientPorts.get(i);
                    packet = new DatagramPacket(data, data.length, cl, cp);
                    socket.send(packet);
                }
            } catch(Exception e) {
                System.err.println(e);
            }
        }
    }

    public static void main(String args[]) throws Exception {
        UDPServer s = new UDPServer();
        s.start();
    }
}

```

Client:

```
import java.io.*;
import java.net.*;
import java.util.*;

class MessageSender implements Runnable {
    public final static int PORT = 7331;
    private DatagramSocket sock;
    private String hostname;
    MessageSender(DatagramSocket s, String h) {
        sock = s;
        hostname = h;
    }
    private void sendMessage(String s) throws Exception {
        byte buf[] = s.getBytes();
        InetAddress address = InetAddress.getByName(hostname);
        DatagramPacket packet = new DatagramPacket(buf, buf.length, address, PORT);
        sock.send(packet);
    }
    public void run() {
        boolean connected = false;
        do {
            try {
                sendMessage("GREETINGS");
                connected = true;
            } catch (Exception e) {

            }
        } while (!connected);
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            try {
                while (!in.ready()) {
                    Thread.sleep(100);
                }
                sendMessage(in.readLine());
            } catch(Exception e) {
                System.err.println(e);
            }
        }
    }
}
class MessageReceiver implements Runnable {
    DatagramSocket sock;
    byte buf[];
    MessageReceiver(DatagramSocket s) {
        sock = s;
        buf = new byte[1024];
    }
    public void run() {
        while (true) {
            try {
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                sock.receive(packet);
                String received = new String(packet.getData(), 0, packet.getLength());
                System.out.println(received);
            } catch(Exception e) {
                System.err.println(e);
            }
        }
    }
}
public class UDPClient {

    public static void main(String args[]) throws Exception {
        String host = null;
        if (args.length < 1) {
            System.out.println("Usage: java ChatClient <server_hostname>");
            System.exit(0);
        } else {
            host = args[0];
        }
        DatagramSocket socket = new DatagramSocket();
        MessageReceiver r = new MessageReceiver(socket);
        MessageSender s = new MessageSender(socket, host);
        Thread rt = new Thread(r);
        Thread st = new Thread(s);
        rt.start(); st.start();
    }
}

```

# Answer
As the above commenters were mentioning, you are probably in a subnet behind a router using a NAT configuration. This gives your network one single external IP. You need to figure out and use your local IP in the network. Use ipconfig/ifconfig (depends on your OS) to figure this out. For Windows, open a command prompt. (Click start then run and enter "cmd") And then enter "ipconfig", you can then find your IPv4 address under the relevant device/connection.

Ok, so going to elaborate a little more. In this case your phone is the router. If it's configured to use NAT, it can only have one external IP for all the devices in it's subnet. You can connect to the "outside" but they can't explicitly connect to you. In order to remedy this you're going to have to adjust your phone settings or connect using an alternative.

For a better and more specific explanation check out this page I grabbed from the top of a google search.
> 0 votes

# Answer
The problem is with how you created the `DatagramSocket`. as stated in DatagramSocket refrence you are using `DatagramSocket(int port)` which only bind server on ***local loopback*** device. To grant access to other computers to connect your server you need to use either `DatagramSocket(int port, InetAddress laddr)` or `DatagramSocket(SocketAddress bindaddr)`. in these cases you can specify an IP address. to let users to connect from any computer connected to your device use '0.0.0.0' as an IP address as stated here.
> 2 votes

---
Tags: java, udp
---


# Question
Title: 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?

# Answer
> 5 votes
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);

```

# Answer
> 1 votes
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.

---
Tags: mathematics
---


# Question
Title: 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!

# Answer
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.
> 5 votes

# Answer
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.
> 1 votes

# Answer
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?
> 0 votes

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


# Question
Title: Where do you search/look for game developers for an indie game startup?
I just recently saw stackoverflow had a game dev sister site so here I am, wondering if you experienced fellows know where one can search/look for game developers for an indie game startup? In other words:

I have a game idea which I've written down with as much detail as possible (so anyone else can understand how it works) and now I'm looking for a heavy php programmer with whom to pair up in order to go from idea to reality. I'm a front-end/interface designer and an intermediate programmer. I recognize my project requires heavy programming skills which I do not have as of today =)

So, what websites, communities or places do you recommend I go look into? Where do good programmers interested in indie games go look for projects if they don't have their own?

Thanks in advance G.Campos

# Answer
When you say "indie game startup" there is one key piece of info you need to specify: is this a paid position?

If so, Joel's "field guide to developers" and some other articles on finding great programmers in general are just as generally applicable to game programmers: http://www.joelonsoftware.com/articles/FieldGuidetoDevelopers.html

If not, then beware. Your question can basically be restated as: "Okay, so everyone has a Great Idea for a game, including any programmer I'd be working with. How do I convince a programmer to work on MY idea and not their own?" And the answer is, you probably can't, for the same reason that you would probably not abandon your idea just to be slave labor on someone else's project.
> 9 votes

# Answer
Anyplace where video gamers congregate in large enough number will have many people looking to connect, whether it be projects to help on, or helpers for projects:

Gamedev.net, which has both a forum with a 'Help Wanted' subforum, and a dedicated Classifieds section on the site.

tigsource.com has a similar help wanted forum, and a special section for Unpaid work.

Reddit's r/gamedev/classifieds: http://www.reddit.com/r/gamedevclassifieds

Probably many more, but these are a good start.
> 1 votes

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


# Question
Title: Programatically replace color gradient on sprite
Say I have the following image:

I want to tint the yellow parts on this sprites shoulder/arms by a random color. In other questions on this site, they suggest using a chroma key and replacing the constant color with whatever color I wanted, but that solution wouldn't keep the gradient.

The other solution I've seen is that I should cut out the part I want to change the color of and make it an overlay. That would work, but would require a lot of effort since I have many poses for this character + animations.

Any ideas?

# Answer
> 7 votes
You could programmatically make a mask by converting the image to HSV color space and specifying a hue range that captures the yellow parts you want while leaving alone the rest of the colors. For instance, you might select the pixels with hue between 50 and 70 (assuming yellow is a 60). Then do the tinting by adding an offset to the hue of those pixels, while keeping the same saturation and value. For example, subtracting 60 from the hue will turn the guy red, adding 60 will make him green, etc.

# Answer
> 0 votes
I'm not certain but I think you could define a color by a ratio between the RGB values then modify the color of any pixel that has a close enough ratio to that which you're working with (keeping the magnitude, thus darker colors closer to 0 will stay the same distance from 0 and keep the gradient)

Keep in mind though, that many ways that will get the yellow of the shoulders will also get the yellow of the visor unless you are careful to exclude it somehow (or want that effect).

Another note, if you are worried about speed and don't need to change the color on the same entity in runtime, apply your shader once to the entire sprite sheet and render it into memory as the new sprite sheet to use. That way you only have to do it once and you can save the entire image out to make sure that everything looks the way you like.

---
Tags: xna, shaders, color
---


title: Biased, conservative random walk

text:
# Question
Title: Biased, conservative random walk
I have a sprite which has `Velocity` and `Position`, either stored as `Vector2`. At each `Update` cycle, velocity is added to the position.

I would like to give the sprite a third vector, `Target`. New targets may be given at any iteration. I would like the sprite to essentially move in a random walk pattern, however two parameters must be exposed:

1. A typical random walk is equally likely to increase or decrease the distance to any given `Target` (plus the small chance of tangential movement). I must be able to bias my random walk such that, while still random, the direction on which the sprite "decides" should be more likely to bring it closer to `Target`.
2. The random walk should be "smooth"- the sprite should not rapidly change direction, as this will look like it's "flickering" or "trembling" to the player. It should gradually veer this way or that, moving randomly, while slowly getting closer when averaged.

What is a good, simple way to do this? If possible, give the answer as a `Vector2 RandomWalk(Vector2 target)` method.

I already have a `NextGaussian(mean, stdev)` method available, if that is helpful.

# Answer
I would take the "wander" steering-behavior (source code can be found here) and tweak it in a way so that the random numbers are biased towards your target.
> 4 votes

# Answer
To get a smooth random walk, you could use Catmull-Rom splines. This kind of spline takes a sequence of points and generates smooth curves that pass through each point. So, you could generate random waypoints for the sprite to move through and animate it along a Catmull-Rom spline through the waypoints. For the spline to work you'll need a total of four waypoints: the previous two and the next two. When the sprite reaches a waypoint, throw away the oldest one of your set of four and generate a new one, then continue animating along the spline.

As for eventually heading toward the target, one idea would be to offset the distribution of the random walk toward the target. For instance, if you'd usually pick a random waypoint using a Gaussian distribution centered on the current position of your sprite, you could instead offset the center of the Gaussian by some preset distance toward the target. The relative sizes of the offset and the Gaussian's standard deviation would determine how biased the motion is.
> 6 votes

# Answer
Here's something I whipped up in about 20 minutes. We take the direction from the walker to the target, pick a direction within a certain amount of degrees of that direction (an amount that decreases as the walker gets closer to their target). This algorithm also accounts for distance to target so that it will not walk past the target. Long story short, it basically wobbles left and right a small random amount and homes in on the target as it gets closer.

To test this algorithm I placed the walker at (10, 0, 10), and the target at (0, 0, 0). The first time the algorithm ran it randomly chose a position for the walker to walk to of (3.73f, 0, 6.71f). After the walker reached that position it chose (2.11f, 0, 3.23), then (0.96f, 0, 1.68f), then (0.50f, 0, 0.79f), then it walked straight to the target because it was within a minimum tolerance distance.

Graphed out from a bird's eye view the path would look like the points in the image below, starting at 'W' (walker) and ending at 'T' (target). If you want a more natural movement you would precalcuate a few points ahead of time, and create a spline, giving you many more points you can have the walker follow. I've estimated what this path would look like after being made into a spline, and that is represented by the line in the image.

**And here's the example code:**

```
Vector3 WalkerPosition = new Vector3(10, 0, 10);
Vector3 TargetPosition = Vector3.Zero;

public Game1()
{
    // Each time you reach the next walk-to position, call this again.
    // Eventually you'll reach your target, assuming the target isn't moving away
    // from the walker faster than the walker can reach them.
    Vector3 NextWalkToPosition = PickRandomTarget();
}

public Vector3 PickRandomTarget()
{
    // For this code sample we'll assume that our two targets are on
    // the same horizontal plane, for simplicity.

    Vector3 directionToTarget = ( TargetPosition - WalkerPosition );
    float distance = directionToTarget.Length();
    directionToTarget.Normalize();

    float distanceThisIteration = distance * 0.5f;

    // We should never walk too little or too far, to make this more realistic
    // you could randomize the walking distance each iteration a bit.
    distanceThisIteration = MathHelper.Clamp(distanceThisIteration, 1.0f, 10.0f);

    // We're within minimum distance to the target, so just go straight to them
    if (distanceThisIteration > distance)
    {
        return TargetPosition;
    }

    directionToTarget *= distanceThisIteration; // Walk roughly halfway to the target

    // Now we pick a new walking direction within an FOV that gets smaller as
    // we get closer to the target. We clamp the FOV between 0 and 90 degrees (45 degrees in either direction).
    const float walkerAggroRadius = 30.0f; // Walker aggros when within 30 units of target

    // Any distance outside of 30 we'll just treat as 30.
    float distanceMod = MathHelper.Clamp(distance, 0.0f, walkerAggroRadius);

    // We need a percentage value representing the current distance between the min 0, and max, 30
    float percentageAlongDistance = distanceMod / walkerAggroRadius;

    // We want FOV from center, so we cut the final FOV result in half
    float maxFOVAtThisDistance = MathHelper.Lerp(0.0f, MathHelper.PiOver2, percentageAlongDistance) * 0.5f;

    // Now we pick a random FOV from center within our maxFOV based on how far we are
    // from the target
    Random rand = new Random(System.DateTime.Now.Second);
    float randFOV = (float)(rand.NextDouble() * maxFOVAtThisDistance);

    // Right now our FOV value is an FOV from a vector pointing directly at our target, we now
    // need to randomly choose if we're going to aim to the left or right of the target. We'll
    // treat a result of 0 as left, and 1 as right
    int randDirection = rand.Next(2);
    if (randDirection == 0) // Left
    {
        // Rotate our direction vector left by randFOV radians
        return WalkerPosition + RotateAroundPoint(directionToTarget, Vector3.Zero, Vector3.UnitY, -randFOV);
    }
    else // Right
    {
        return WalkerPosition + RotateAroundPoint(directionToTarget, Vector3.Zero, Vector3.UnitY, randFOV);
    }
}

// Generic helper function to rotate a vector by a specific amount of degrees
public Vector3 RotateAroundPoint( Vector3 point, Vector3 originPoint, Vector3 rotationAxis, float radiansToRotate )
{
    Vector3 diffVect = point - originPoint;

    Vector3 rotatedVect = Vector3.Transform(diffVect, Matrix.CreateFromAxisAngle(rotationAxis, radiansToRotate));

    rotatedVect += originPoint;

    return rotatedVect;
}

```

Based on your specific game you can tweak distances, FOV, randomness, and frequency that this is run, until it suits your needs. I'm sure the algorithm could be cleaned up a bit and optimized, I didn't spend much time on that, I just wanted it to be easy to read.
> 2 votes

---
Tags: xna, c#, random, linear-algebra
---


title: How do I create a horizon?

text:
# Question
Title: How do I create a horizon?
I added a sky to my raytracer that gets sampled when a ray completely misses any object.

What I'm doing here is if a ray completely misses anything in the scene, it returns the Perlin noise function at (ray.direction.x, ray.direction.y, ray.direction.z) - in other words it "samples a sphere around the origin".

But it "looks wrong" (because the sky looks like it's *facing* you).

How can I improve the sky and make it look more like the earth's horizon?

Or is this more or less what it should look like, and I should simply add more geometry on the floor?

# Answer
> 7 votes
Alternatively you could use a **cube map** with a sky texture instead of using perlin noise. And I also think that will make your scene look better due to having more detail and variation in the environment mapping. That's exactly what I did when I implemented my raytracer.

Another reason I recommend this, is that the environment does not need to be only clouds. It can have mountains, it can be an indoor scene, can be a scene from mars. Using a cube map the only thing you need to do is swap the texture and you're done.

So the first step will be to find a cube map that fits your needs. It could be stored as six separate textures, or as a single texture like the one below. Also check this link for more info on how to create your own:

Then on your code, I'd recommend creating a `CubeMap` class to encapsulate the sampling calculations. This class should know how to load the cube map texture, and given a *ray* it should be able to know in *which* face and in *what* position to sample. In my implementation I found it easier to store each of the six faces in separate texture objects, and branch based on the direction of the ray:

```
class CubeMap
{
    public void Load(string path);
    public Color GetSample(Ray ray);
    private Texture[6] faces;
}

```

In case you don't have a `Texture` class yet, just create your own. It can be as simple as a two dimensional array of colors. So, just as a reference, and with no guarantee on the efficiency or soundness of this implementation, here's the code I used on my project - CubeMap and CubeFace.

# Answer
> 2 votes
You might try using 2D Perlin with (ray.dir.x/ray.dir.z, ray.dir.y/ray.dir.z). The projects the direction vector onto the Z=1 plane. It should give you the effect of an infinite (flat) sky.

# Answer
> 1 votes
You might want to check Iñigo Quilez's (iq) Dynamic Clouds article out -- It looks like something that might fit your ticket.

---
Tags: sky, perlin-noise
---


# Question
Title: What is the difference between Vector2.Transform and this method?
I've been working on some steering behaviors and ran into trouble with my logic for converting points in world space into points in local space. I had this (it's not optimized for multiple points yet, but that is not the point of my question):

```
public Vector2 WorldPointToLocal(Vector2 point)
{
    var tx = -Vector2.Dot(this.Location, this.Heading);
    var ty = -Vector2.Dot(this.Location, this.HeadingPerpendicular);
    var rotationMatrix = new Matrix
    {
        M11 = this.Heading.X,
        M12 = this.HeadingPerpendicular.X,
        M21 = this.Heading.Y,
        M22 = this.HeadingPerpendicular.Y,
        M31 = tx,
        M32 = ty
    };

    return Vector2.Transform(point, rotationMatrix);
}

```

This did not work. The returned point was always well outside the expected range. I had collated most of the mathematics from various sources and began to suspect that `Vector2.Transform` wasn't doing what I thought it was supposed to do. I found an alternative implementation in C and translated it into C#:

```
private Vector2 VectorTransform(Vector2 vector, Matrix matrix)
{
    var tempX = (matrix.M11 * vector.X) + (matrix.M21 * vector.Y) + matrix.M31;
    var tempY = (matrix.M12 * vector.X) + (matrix.M22 * vector.Y) + matrix.M32;

    return new Vector2(tempX, tempY);
}

```

When I used this implementation instead of `Vector2.Transform`, everything worked perfectly.

However, I don't want to leave it at that. I'd like to understand *why* `Vector2.Transform` does not do the same thing, and whether there's anything I can do to leverage it instead of writing my own. The API documentation doesn't help at all and I'm a bit clueless when it comes to matrix mathematics.

# Answer
> 1 votes
Your translation component is in the wrong basis vector. Vector2.Transform transforms by (x,y,0,1), so the translations should be in the fourth basis to correctly translate.

# Answer
> 4 votes
When the documentation is not enough, I like using a decompiler such as dotPeek to see what's really happening behind the scenes. Running dotPeek on `Vector2.Transform` gave me this implementation:

```
/// <summary>
/// Transforms the vector (x, y, 0, 1) by the specified matrix.
/// </summary>
/// <param name="position">The source vector.</param><param name="matrix">The transformation matrix.</param>
public static Vector2 Transform(Vector2 position, Matrix matrix)
{
  float num1 = (float) ((double) position.X * (double) matrix.M11 + (double) position.Y * (double) matrix.M21) + matrix.M41;
  float num2 = (float) ((double) position.X * (double) matrix.M12 + (double) position.Y * (double) matrix.M22) + matrix.M42;
  Vector2 vector2;
  vector2.X = num1;
  vector2.Y = num2;
  return vector2;
}

```

From this you can see that the vector that is being transformed is actually `(x, y, 0, 1)` and the difference from your code is that you're doing:

```
... + matrix.M31;
... + matrix.M32;

```

While `Vector2.Translate` is doing:

```
... + matrix.M41;
... + matrix.M42;

```

So moving `tx`and `ty` to `M41` and `M42` *should* give you the same results as your custom method.

---
Tags: xna, matrix, rotation
---


# Question
Title: Using component based entity system practically
Yesterday, I've read a presentation from GDC Canada about Attribute / Behaviour entity system and I think it's pretty great. However, I'm not sure how to use it practially, not just in theory. First of all, I'll quickly explain you how this system works.

---

Each game entity (game object) is composed of **attributes** (= data, which can be accessed by behaviours, but also by 'external code') and **behaviours** (= logic, which contain `OnUpdate()` and `OnMessage()`). So, for example, in a Breakout clone, each brick would be composed of (example!): *PositionAttribute*, *ColorAttribute*, *HealthAttribute*, *RenderableBehaviour*, *HitBehaviour*. The last one could look like this (it's just a non-working example written in C#):

```
void OnMessage(Message m)
{
    if (m is CollisionMessage) // CollisionMessage is inherited from Message
    {
        Entity otherEntity = m.CollidedWith; // Entity CollisionMessage.CollidedWith
        if (otherEntity.Type = EntityType.Ball) // Collided with ball
        {
            int brickHealth = GetAttribute<int>(Attribute.Health); // owner's attribute
            brickHealth -= otherEntity.GetAttribute<int>(Attribute.DamageImpact);
            SetAttribute<int>(Attribute.Health, brickHealth); // owner's attribute

            // If health is <= 0, "destroy" the brick
            if (brickHealth <= 0)
                SetAttribute<bool>(Attribute.Alive, false);
        }
    }
    else if (m is AttributeChangedMessage) // Some attribute has been changed 'externally'
    {
        if (m.Attribute == Attribute.Health)
        {
            // If health is <= 0, "destroy" the brick
            if (brickHealth <= 0)
                SetAttribute<bool>(Attribute.Alive, false);
        }
    }
}

```

If you're interested in this system, you can read more here (.ppt).

---

My question is related to this system, but generally every component based entity system. I've never seen how any of these really work in real computer games, because I can't find any good examples and if I find one, it's not documented, there are no comments and so I don't understand it.

So, what do I want to ask? How to design the behaviours (components). I've read here, on GameDev SE, that the most common mistake is to make many components and simply, "make everything a component". I've read that it's suggested to not do the rendering in a component, but do it outside of it (so instead of *RenderableBehaviour*, it should maybe be *RenderableAttribute*, and if an entity has *RenderableAttribute* set to true, then `Renderer` (class not related to components, but to the engine itself) should draw it on screen?).

But, how about the behaviours / components? Let's say that I've got a level, and in the level, there's a `Entity button`, `Entity doors` and `Entity player`. When player collides with the button (it's a floor button, which is toggled by pressure), it's pressed. When the button gets pressed, it opens the doors. Well, now how to do it?

I've come up with something like this: the player has got *CollisionBehaviour*, which checks if player collides with something. If he collides with a button, it sends a `CollisionMessage` to the `button` entity. The message will contain all necessary informations: who collided with the button. The button has got *ToggleableBehaviour*, which will receive `CollisionMessage`. It'll check who did it collide with and if the weight of that entity is big enough to toggle the button, the button gets toggled. Now, it sets the *ToggledAttribute* of the button to true. Alright, but what now?

Should the button send another message to all other objects to tell them that it has been toggled? I think that if I did everything like this, I'd have thousands of messages and it'd get pretty messy. So maybe this is better: the doors constantly check if the button which is linked to them is pressed or not, and changes its *OpenedAttribute* accordingly. But then it means that the doors' `OnUpdate()` method will be constantly doing something (is it really a problem?).

And the second problem: what if I have more kinds of buttons. One is pressed by pressure, second one is toggled by shoting at it, third one is toggled if water is poured on it, etc. This means that I'll have to have different behaviours, something like this:

```
Behaviour -> ToggleableBehaviour -> ToggleOnPressureBehaviour
                                 -> ToggleOnShotBehaviour
                                 -> ToggleOnWaterBehaviour

```

Is this how real games work or am I just stupid? Maybe I could have just one *ToggleableBehaviour* and it'll behave according to the *ButtonTypeAttribute*. So if it's a `ButtonType.Pressure`, it does this, if it's a `ButtonType.Shot`, it does something else...

So what do I want? I'd like to ask you if I'm doing it right, or I'm just stupid and I didn't understand the point of components. I didn't find any good example of how do the components really work in games, I found just some tutorials describing how to make the component system, but not how to use it.

# Answer
> 46 votes
Components are great, but it can take some time to find a solution that feels good to you. Don't worry, you'll get there. :)

***Organizing components***

You're pretty much on the right track, I'd say. I'll try to describe the solution in reverse, starting with the door and ending with the switches. My implementation makes heavy use of events; below I describe how you can use events more efficiently so they don't become a problem.

If you have a mechanism for connecting entities between them, I'd have the switch directly notify the door that it has been pressed, then the door can decide what to do.

If you can't connect entities, your solution is pretty close to what I'd do. I'd have the door listen for a generic event (`SwitchActivatedEvent`, maybe). When the switches get activated, they post this event.

If you have more than one type of switch, I'd have `PressureToggle`, `WaterToggle` and a `ShotToggle` behaviors too, but I'm not sure the base `ToggleableBehaviour` is any good, so I'd do away with that (unless, of course, you have a good reason for keeping it).

```
Behaviour -> ToggleOnPressureBehaviour
          -> ToggleOnShotBehaviour
          -> ToggleOnWaterBehaviour

```

***Efficient event handling***

As for worrying that there's too many events flying around, there's one thing you could do. Instead of having every component be notified of every single event that occurs, then have the component check if it's the right type of event, here's a different mechanism...

You can have an `EventDispatcher` with a `subscribe` method that looks something like this (pseudocode):

```
EventDispatcher.subscribe(event_type, function)

```

Then, when you post an event, the dispatcher checks its type and only notifies those functions that have subscribed to that particular type of event. You can implement this as a map that associates types of events with lists of functions.

This way, the system is significantly more efficient: there's a lot less function calls per event, and components can be sure that they received the right type of event and not have to double check.

I've posted a simple implementation of this some time ago on StackOverflow. It's written in Python, but maybe it can still help you:
https://stackoverflow.com/a/7294148/627005

That implementation is quite generic: it works with any kind of function, not just functions from components. If you don't need that, instead of `function`, you could have a `behavior` parameter in your `subscribe` method — the behavior instance that needs to be notified.

***Attributes and behaviors***

I've come to use attributes and behaviors myself, instead of plain old components. However, from your description of how you'd use the system in a Breakout game, I think you're overdoing it.

I use attributes only when two behaviors need access to the same data. The attribute helps keep the behaviors separate and the dependencies between components (be they attribute or behaviors) do not become entangled, because they follow very simple and clear rules:

* Attributes do not use any other components (neither other attributes, nor behaviors), they are self sufficient.
* Behaviors do not use or know about other behaviors. They only know about *some* of the attributes (those that they strictly need).

When some data is only needed by one and only one of the behaviors, I see no reason to put it in an attribute, I let the behavior hold it.

---

**@heishe's comment**

Wouldn't that problem occur with normal components as well?

Anyway, I don't have to check event types because every function is sure to receive the right type of event, *always*.

Also, the behaviors' dependencies (ie. the attributes that they need) are resolved on construction, so you don't have to go looking for attributes every on every update.

And lastly, I use Python for my game logic code (the engine is in C++, though), so there's no need for casting. Python does its duck-typing thing and everything works fine. But even if I didn't use a language with duck-typing, I'd do this (simplified example):

```
class SomeBehavior
{
  public:
    SomeBehavior(std::map<std::string, Attribute*> attribs, EventDispatcher* events)
        // For the purposes of this example, I'll assume that the attributes I
        // receive are the right ones.
        : health_(static_cast<HealthAttribute*>(attribs["health"])),
          armor_(static_cast<ArmorAttribute*>(attribs["armor"]))
    {
        // Boost's polymorphic_downcast would probably be more secure than
        // a static_cast here, but nonetheless...
        // Also, I'd probably use some smart pointers instead of plain
        // old C pointers for the attributes.

        // This is how I'd subscribe a function to a certain type of event.
        // The dispatcher returns a `Subscription` object; the subscription
        // is alive for as long this object is alive.
        subscription_ = events->subscribe(event::type<DamageEvent>(),
            std::bind(&SomeBehavior::onDamageEvent, this, _1));
    }

    void onDamageEvent(std::shared_ptr<Event> e)
    {
        DamageEvent* damage = boost::polymorphic_downcast<DamageEvent*>(e.get());
        // Simplistic and incorrect formula: health = health - damage + armor
        health_->value(health_->value() - damage->amount() + armor_->protection());
    }

    void update(boost::chrono::duration timePassed)
    {
        // Behaviors also have an `update` function, just like
        // traditional components.
    }

  private:
    HealthAttribute* health_;
    ArmorAttribute* armor_;
    EventDispatcher::Subscription subscription_;
};

```

Unlike behaviors, attributes don't have any `update` function — they don't need to, their purpose is to hold data, not to perform complex game logic.

You can still have your attributes perform some simple logic. In this example, a `HealthAttribute` might ensure that `0 <= value <= max_health` is always true. It can also send a `HealthCriticalEvent` to other components of the same entity when it drops below, say, 25 percent, but it can't perform logic any more complex than that.

---

**Example of an attribute class:**

```
class HealthAttribute : public EntityAttribute
{
  public:
    HealthAttribute(Entity* entity, double max, double critical)
        : max_(max), critical_(critical), current_(max)
    { }

    double value() const {
        return current_;
    }

    void value(double val)
    {
        // Ensure that 0 <= current <= max
        if (0 <= val && val <= max_)
            current_ = val;

        // Notify other components belonging to this entity that
        // health is too low.
        if (current_ <= critical_) {
            auto ev = std::shared_ptr<Event>(new HealthCriticalEvent())
            entity_->events().post(ev)
        }
    }

  private:
    double current_, max_, critical_;
};

```

---
Tags: c#, component-based, entity-system
---


title: Server hosting and costs

text:
# Question
Title: Server hosting and costs
I'm developing a game that will require renting a server. The server will be used to host scores, clans, friends(on/off), match making, lobby, and chat. The game/match will be hosted by each player (to lower the cost). How much would a server like this cost? Any hosting recommendation? How much would it cost if the server hosts the games/matches too?

I want to know a base price (imagine a card game or turn based RPG, even though my game is real time).

# Answer
> 4 votes
I would check the costs for housing a server at a local provider. Then you can put your own server together. Thats your base price.

Then you can go to check prices for cloud services. Depending on traffic this can get pricy, that's why I personally would stick to a server on your own and only go in the cloud, if your server gets too many requests..

Check out this related posts:

What options do I have for game hosting

Which server platform to choose

What's the best server architecture for real-time games?

# Answer
> 0 votes
If you're not doing game simulation, everything else has low CPU and bandwidth requirements. So you could look at using a cloud-based service like Amazon's EC2. Amazon even offers a free micro instance for a year, so it might be worth checking out.

I've found that cloud-hosted systems like this aren't a great fit for actual game simulation, both because it requires more CPU time (that you're paying for), and because it doesn't tend to respond quickly to spikes in CPU load. But for other tasks like what you mention, it could be a great fit.. and you can easily benchmark your costs by running a server locally and testing your CPU and bandwidth requirements per user.

---
Tags: networking, server, client-server, costs, hosting
---


# Question
Title: How to implement the interaction between engine parts?
I want to ask a question about how the information exchange between game engine parts should be implemented.

The engine is separated in four parts: logic, data, UI, graphics. In the beginning I made this exchange through the flags. For example if the new object is added in the data, the flag `isNew` in a object's class will be set as `true`. And after that the graphics part of the engine will check this flag, and will add the object into the game world.

Though, with this approach I was to write much code to process every flag of each kind of object.

I thought of using some event system, but I don't have enough experience to know whether this would be the right solution.

Is the event system the only appropriate approach, or should I use something else?

I’m using Ogre as the graphics engine, if that matters.

# Answer
My favorite game engine structure is the interface and object\<-\>component model using messaging for communication between almost all parts.

You have multiple interfaces for main engine parts such as your scene manager, resource loader, audio, renderer, physics, etc.

I have the scene manager in charge of all objects in the 3D scene/world.

Object is a very atomic class, containing only a few things that are common to almost everything in your scene, in my engine the object class holds only position, rotation, a list of components, and a unique ID. Every object's ID is generated by a static int, so that no two objects will every have the same ID, this allows you to send messages to an object by its ID, rather than having to have a pointer to the object.

The list of components on the object is what gives that objects is main properties. For example, for something that you can see in the 3D world, you would give your object a render component that contains the information about the render mesh. If you want an object to have physics you would give it a physics component. If you want something to act as a camera, give it a camera component. The list of components can go on and on.

Communication between interfaces, objects, and components is key. In my engine I have a generic message class that contains only a unique ID, and a message type ID. The unique ID is the ID of the object you want the message to go to, and the message type ID is used by the object receiving the message so it knows what type of message it is.

Objects can handle the message if they need, and they can pass the message on to each of their components, and components will often do important things with the message. For example, if you want to change and object's position you send the object a SetPosition message, the object may update its position variable when it gets the message, but the render component may need to message to update the position of the render mesh, and the physics component may need the message to update the physics body's position.

Here is a very simple layout of scene manager, object, and component, and message flow, that I whipped up in about an hour, written in C++. When run it sets the position on an object, and the message passes through the render component, then retrieves the position from the object. Enjoy!

Also, I've written a C# version and Scala version of the below code for anyone that might be fluent in those rather than C++.

```
#include <iostream>
#include <stdio.h>

#include <list>
#include <map>

using namespace std;

struct Vector3
{
public:
    Vector3() : x(0.0f), y(0.0f), z(0.0f)
    {}

    float x, y, z;
};

enum eMessageType
{
    SetPosition,
    GetPosition,
};

class BaseMessage
{
protected: // Abstract class, constructor is protected
    BaseMessage(int destinationObjectID, eMessageType messageTypeID)
        : m_destObjectID(destinationObjectID)
        , m_messageTypeID(messageTypeID)
    {}

public: // Normally this isn't public, just doing it to keep code small
    int m_destObjectID;
    eMessageType m_messageTypeID;
};

class PositionMessage : public BaseMessage
{
protected: // Abstract class, constructor is protected
    PositionMessage(int destinationObjectID, eMessageType messageTypeID,
                    float X = 0.0f, float Y = 0.0f, float Z = 0.0f)
        : BaseMessage(destinationObjectID, messageTypeID)
        , x(X)
        , y(Y)
        , z(Z)
    {

    }

public:
    float x, y, z;
};

class MsgSetPosition : public PositionMessage
{
public:
    MsgSetPosition(int destinationObjectID, float X, float Y, float Z)
        : PositionMessage(destinationObjectID, SetPosition, X, Y, Z)
    {}
};

class MsgGetPosition : public PositionMessage
{
public:
    MsgGetPosition(int destinationObjectID)
        : PositionMessage(destinationObjectID, GetPosition)
    {}
};

class BaseComponent
{
public:
    virtual bool SendMessage(BaseMessage* msg) { return false; }
};

class RenderComponent : public BaseComponent
{
public:
    /*override*/ bool SendMessage(BaseMessage* msg)
    {
        // Object has a switch for any messages it cares about
        switch(msg->m_messageTypeID)
        {
        case SetPosition:
            {
                // Update render mesh position/translation

                cout << "RenderComponent handling SetPosition\n";
            }
            break;
        default:
            return BaseComponent::SendMessage(msg);
        }

        return true;
    }
};

class Object
{
public:
    Object(int uniqueID)
        : m_UniqueID(uniqueID)
    {
    }

    int GetObjectID() const { return m_UniqueID; }

    void AddComponent(BaseComponent* comp)
    {
        m_Components.push_back(comp);
    }

    bool SendMessage(BaseMessage* msg)
    {
        bool messageHandled = false;

        // Object has a switch for any messages it cares about
        switch(msg->m_messageTypeID)
        {
        case SetPosition:
            {
                MsgSetPosition* msgSetPos = static_cast<MsgSetPosition*>(msg);
                m_Position.x = msgSetPos->x;
                m_Position.y = msgSetPos->y;
                m_Position.z = msgSetPos->z;

                messageHandled = true;
                cout << "Object handled SetPosition\n";
            }
            break;
        case GetPosition:
            {
                MsgGetPosition* msgSetPos = static_cast<MsgGetPosition*>(msg);
                msgSetPos->x = m_Position.x;
                msgSetPos->y = m_Position.y;
                msgSetPos->z = m_Position.z;

                messageHandled = true;
                cout << "Object handling GetPosition\n";
            }
            break;
        default:
            return PassMessageToComponents(msg);
        }

        // If the object didn't handle the message but the component
        // did, we return true to signify it was handled by something.
        messageHandled |= PassMessageToComponents(msg);

        return messageHandled;
    }

private: // Methods
    bool PassMessageToComponents(BaseMessage* msg)
    {
        bool messageHandled = false;

        auto compIt = m_Components.begin();
        for ( compIt; compIt != m_Components.end(); ++compIt )
        {
            messageHandled |= (*compIt)->SendMessage(msg);
        }

        return messageHandled;
    }

private: // Members
    int m_UniqueID;
    std::list<BaseComponent*> m_Components;
    Vector3 m_Position;
};

class SceneManager
{
public:
    // Returns true if the object or any components handled the message
    bool SendMessage(BaseMessage* msg)
    {
        // We look for the object in the scene by its ID
        std::map<int, Object*>::iterator objIt = m_Objects.find(msg->m_destObjectID);
        if ( objIt != m_Objects.end() )
        {
            // Object was found, so send it the message
            return objIt->second->SendMessage(msg);
        }

        // Object with the specified ID wasn't found
        return false;
    }

    Object* CreateObject()
    {
        Object* newObj = new Object(nextObjectID++);
        m_Objects[newObj->GetObjectID()] = newObj;

        return newObj;
    }

private:
    std::map<int, Object*> m_Objects;
    static int nextObjectID;
};

// Initialize our static unique objectID generator
int SceneManager::nextObjectID = 0;

int main()
{
    // Create a scene manager
    SceneManager sceneMgr;

    // Have scene manager create an object for us, which
    // automatically puts the object into the scene as well
    Object* myObj = sceneMgr.CreateObject();

    // Create a render component
    RenderComponent* renderComp = new RenderComponent();

    // Attach render component to the object we made
    myObj->AddComponent(renderComp);

    // Set 'myObj' position to (1, 2, 3)
    MsgSetPosition msgSetPos(myObj->GetObjectID(), 1.0f, 2.0f, 3.0f);
    sceneMgr.SendMessage(&msgSetPos);
    cout << "Position set to (1, 2, 3) on object with ID: " << myObj->GetObjectID() << '\n';

    cout << "Retreiving position from object with ID: " << myObj->GetObjectID() << '\n';

    // Get 'myObj' position to verify it was set properly
    MsgGetPosition msgGetPos(myObj->GetObjectID());
    sceneMgr.SendMessage(&msgGetPos);
    cout << "X: " << msgGetPos.x << '\n';
    cout << "Y: " << msgGetPos.y << '\n';
    cout << "Z: " << msgGetPos.z << '\n';
}

```
> 21 votes

# Answer
I think it is the best way to use Scene Manager and Interfaces. Have messaging implemented but I would use it as secondary approach. Messaging is good for inter-thread communication. Use abstraction (interfaces) wherever you can.

I don't know much about Ogre, so I'm speaking generally.

At core, you have main game loop. It gets input signals, calculates AI (from simple motion to complex AI and game logic), loads resources\[, etc\] and renders current state. This is basic example, so you can separate engine into these parts (InputManager, AIManager, ResourceManager, RenderManager). And you should have SceneManager which holds all objects that are present in game.

Every of these parts and their sub-parts have interfaces. So try to organize these parts to do their and only their job. They should use sub-parts that interact internally for the purpose of their parent-part. That way you wont get in embroil without chance of unrolling without total rewrite.

p.s. if you're using C++ consider using RAII pattern
> 2 votes

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


title: Farseer DebugViewXNA: scaling problem

text:
# Question
Title: Farseer DebugViewXNA: scaling problem
I'm trying to get into Farseer and XNA. Before I do any real graphics, I want to use the Farseer debug view only. The problem ist, that I don't really know which matrix to use and the other thing is that my objects look "squeezed". But in detail:

```
this.oGraphicsMgr.SupportedOrientations = DisplayOrientation.Portrait;
this.oGraphicsMgr.IsFullScreen = false;
this.oGraphicsMgr.PreferredBackBufferWidth = 640;
this.oGraphicsMgr.PreferredBackBufferHeight = 960;
this.oGraphicsMgr.ApplyChanges();

this.oWorld = new World( Vector2.Zero );

```

My gaming field is 640x960 screen units (pixels).

The setup of the debug view:

```
this.oDebugView = new DebugViewXNA( this.oWorld )
{
    DefaultShapeColor = Color.Red,
    SleepingShapeColor = Color.Pink,
    StaticShapeColor = Color.Yellow,
};
this.oDebugView.LoadContent( this.GraphicsDevice, this.Content );
this.oDebugView.AppendFlags( DebugViewFlags.Shape );
this.oDebugView.AppendFlags( DebugViewFlags.DebugPanel );
this.oDebugView.AppendFlags( DebugViewFlags.PolygonPoints );
this.oDebugView.AppendFlags( DebugViewFlags.CenterOfMass );
this.oDebugView.AppendFlags( DebugViewFlags.Controllers );

```

I create a circular body and place it in the middle of the screen. "Puck" inherits from Body.

```
public Puck(World oWorld) : base( oWorld )
{
    FixtureFactory.AttachCircle( 0.1, 1f, this );
    this.Restitution = RESTITUTION;
    this.BodyType = FarseerPhysics.Dynamics.BodyType.Dynamic;
}

```

My game's draw method:

```
protected override void Draw( GameTime oGameTime )
{
    GraphicsDevice.Clear( Color.CornflowerBlue );
    Matrix oProj = Matrix.Identity;
    this.oDebugView.RenderDebugData( ref oProj );
base.Draw( oGameTime );
}

```

The output is a window that is 640x960 pixels. In the middle I can see what is supposingly a circle but it is drawn elliptical: twice as high as it is wide.

1. It will only be shown as a circle if my game field's width and height are equal. As soon as they differ, the debug view draws all objects stretched using the ratio of width to height. Why? How to avoid?
2. I'm not using a camera. After long trying I figured out that Matrix.Identity is the only projection matrix that will actually make the debug view draw everything in the correct size. But to my understanding it should instead be a scaled matrix, transforming my physic units into screen units.
3. I want my gaming field to be 3x2 meters and the puck 0.2m diameter. Therefore I will have to define a scale factor from sim units to screen units. But nowhere can I see that the debug view would require this. How can it possibly know how big a shape has to be drawn?

# Answer
> 2 votes
Here is my code for drawing Farseer debug objects. They line up perfectly with my real world objects. I had to play around with it for a long time before I got it to draw just right. This may be of use to you.

```
Matrix proj = Matrix.CreateOrthographicOffCenter(0f, Viewport.Width, Viewport.Height, 0f, 0f, 1f);
Matrix view2 = Matrix.CreateScale(32);
view2 *= view;
_worldDebug.RenderDebugData(ref proj, ref view2);

```

The "view" above, is the matrix used when drawing everything else.

---
Tags: xna-4.0, farseer-physics-engine
---


title: Convert game replay into video format

text:
# Question
Title: Convert game replay into video format
My game outputs a replay file for each individual game and allows the player to watch past games.

Just a quick example of what our replay files look like:

```
m 6 2098.25 917.125 -1 0 224 56ööööö843949615
m 2 1715.25 1835.25 1 0 224 44ööööö843949621
m 11 1661.125 1890.875 1 0 224 56ööööö843949627
m 5 1818.125 929.0 0 1 224 56ööööö843949633
death 9 3 4 5ööööö843949663
hit 9 3 4 48 26 2114 1987 2.8266926 1865 1891ööööö843949663

```

Some info on the identifiers:

```
Movement: // m (player id) (x coord) (y coord) (x-movement) (y-movement) (remaining health) (shot energy remaining) (timestamp)

Death: // death (dead player id) (killer player id)

Hit: // hit (hit player id) (hitter player id) (weapon (1-4)) (damage dealt) (life remaining ) (x coord) (y coord) (angle of hit) (total damage dealt) (total damage taken)

```

There are a lot more than what I listed, but you get the idea.

What's in the replay files are essentially the same as what is sent to the server during a live game.

Right now, if we want to take a video of the game, we just go into our replay system and record it with Fraps, but I'd like to convert our replays into some kind of video format.

I know this may be a bit far-fetched, but I thought I'd give it a shot here.

The game is written in Java and is sprite based.

# Answer
> 2 votes
Building a good video capturing system into your game is going to be quite challenging. Especially if you want to record in real-time. If your replay system allows for a slower playback, then it's going to be easier to avoid frame skips etc., but then you'll have a problem with audio recording.

You should test if you have enough CPU cycles to record in real-time, or if you need to capture video with a lower frame-rate and then "record" audio separately.

I don't know what technology you use for rendering, but getting rendered frames shouldn't be too hard. When using OpenGL you could use a render-to-texture approach. In any case I suggest you have a look at an existing recording API like Xuggler. It will allow you to add separate frames to a buffer that will then be encoded to a video file. They also have some tutorials that might help you getting started.

---
Tags: video, replays
---


title: How to choose a 3d modeling software?

text:
# Question
Title: How to choose a 3d modeling software?
What should you be aware before making a choice?

# Answer
> 0 votes
That is a vague question. But still.

Choosing 3d modeling software is personal thing. There are number of softwares available and many of them have big number of features. So you should try demo of every one of them, try to model something more then simple, and whichever "clicks" is the one for you. Except for the price feature.

You have popular max and maya but are pretty expensive. you have as good houdini (with good free version, 'apprentice') and XSI (which is as good and cost less then max and maya and from personal experience has best workflow of all)

and there is free blender for which also has all the "big" features, and is **free**. But it's UI IMHO is unintuitive. But it's free.

---
Tags: 3d, models
---


# Question
Title: Can I legally sell an XNA game made with Visual C# Express Edition?
I've dowloaded Visual C# Express Edition and when it starts up it says "for evaluation purposes only." What does this mean?

Does this mean I have to buy the full version to legally sell my game I make with it? Or can I just use the free express edition? I really dont want to make a game and then find out I can't sell it.

# Answer
> 35 votes
Yes, you can.

See this StackOverflow answer: https://stackoverflow.com/questions/3969484/can-i-produce-a-commercial-application-using-visual-studio-express-2010

There was an FAQ for the 2008 edition with a line that explicitly said that yes, you can. It's hard to dig up anything conclusive for 2010, but Microsoft actively goes around encouraging developers to download Express edition and sell their applications developed with it.

The reason that Visual Studio Professional and up cost money is because they offer features like plugin support, project management, and testing tools. Their primary customers are large companies with complicated development environments. They couldn't care less about indie developers using their compiler and IntelliSense without paying.

To get rid of the "Evaluation Only", you need to register your copy.

# Answer
> -3 votes
Read the license. As far as I know, the 2010 express editions *do* allow commercial use, unless the license has changed.

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


# Question
Title: How does one specify raster operations in XNA?
I'm looking for a way to add a sprite using a particular logic operation (like XOR). I can't find anything on Google and I'm not sure where to look in the documentation.

I've looked into `SpriteBatch.Begin(...)` and its `Draw` method and several options in the `GraphicsDevice` class, but I'm not recognizing anything capable of this. I'm still pretty new to XNA so I may just not have recognized the terminology to do this.

# Answer
The `GraphicsDevice.RasterizerState` property is how you alter raster settings.

There are three default states built in but I don't believe the `RasterizerState` is what you are looking for.

```
RasterizerState.CullCounterClockwise
RasterizerState.CullClockwise
RasterizerState.CullNone

```

I'm not sure what you mean by xor sprites together. However, from the below comment I'm assuming you want to use an overlay for a crosshair. If you do want to use an overlay you could use alter the BlendState as Jonathan Dickinson pointed out.

> Aside from just another tool in the toolbelt, I'm looking into how to make a crosshair for targeting. An inverted crosshair (in my experience/opinion) is the best crosshair

Just set the below as the BlendState in SpriteBatch.Begin(). Also worth noting is that if the SortMode is SpriteSortMode.Immediate you can alter the all of the GraphicsDevice's properties without calling Spritebatch.Begin again.

```
        GraphicsDevice.BlendState = new BlendState {

            ColorSourceBlend = Blend.Zero,
            ColorDestinationBlend = Blend.InverseSourceColor,

            AlphaSourceBlend = Blend.Zero,
            AlphaDestinationBlend = Blend.InverseSourceColor

        };

```
> 1 votes

# Answer
One option may be defining a new BlendState...and choose the right BlendFunction and Factors to get the xor operation. I'm not sure it can be done, but it is the easier way and should be your first option.

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.blendstate.alphablendfunction.aspx

The second option is using a HLSL shader and rendertargets.

```
1. You draw to rendertargetA you sprites
2. if you want to do a xor operation..
     3. you assign the texture source in your shader from rendertargetA
     4. you draw with your xor shader to rendertargetB
     5. exchange rendertarget reference, RendertargetA is now B, and viceversa
6. Draw from your rendertarget A to the backbuffer.

Or something similar... :)

```
> 0 votes

---
Tags: xna-4.0
---


# Question
Title: How does an AAA graphical workflow look like?
So this is how I understand it:

An artist models the thing in Zbrush or Mudbox. It now has 10+ million polygon. He exports it in Zbrush as a normal map + low poly model. (this works?) The model now has ~20-30k polygons?

Now the artist imports the low poly model into 3dsmax or Maya, applies the normal map somehow as well, so it will look in the modelling program just like it would ingame. Then he starts adding bones and then skins the model. Then animation, then export. As I understand it, somehow all the textures of a model get "baked" into a single texture which the engine will understand?

Do people still make textures in Photoshop and then UV unwrap the model by hand, then apply the textures? I never understood how someone can make the laid out texture of a face in Photoshop, and somehow he knows that it will look good on the model. Do they paint the textures in Zbrush? But Zbrush doesn't have all the photoshop tools.

What if I want to make a terrain, or an indoor level? Do I just model the whole thing in 3dsmax? What if the textures don't show up in the engine the way they do in 3dsmax?

# Answer
This is extremely difficult to answer because trade secrets such as the artists' pipelines for major developers are protected by long, strict NDAs. I'll do my best to summarize what I have learned as a student in the field.

The best answer I can start with is that it varies for every developer. What you described with the model first being created in Zbrush or Mudbox is fairly common, as I understand. The texture 'baking' is more varying. This is entirely dependent on what the engine requires. If it can handle a single texture containing all the information, then that's what the artist will make. This probably isn't that common though.

Generating textures in Photoshop after unwrapping the model is, to the best of my knowledge, still very common (though Photoshop might not be the particular picture-editor used). I've heard of an artist who uses GIMP to generate his textures.

As for terrain, the engine used probably supports its generation. For example, Unity 3D has a built-in terrain editor. All that must be supplied are the textures which will be painted onto the terrain. Another example is the engine that Saints Row: The Third was built on. A demo video showed a developer placing roads in the city, and the road segment being placed would automatically change to fit the road around it. Tools like this are implemented by the engine and tools programmers in order to streamline the development process. However, as someone pointed out in a comment, constructing these roads is really the job of the level designer.

Summary: The art pipeline is heavily dependent on in-house trade secrets, and the game engine. One of the only ways to learn the details is to enter the field.

Oh, and lastly, Pixar is well known for making public their advances and techniques in graphics, so they might have some information on their pipeline. It will vary from a game though, since they have the option of offline rendering.
> 4 votes

# Answer
There are articles around the internet. Some development teams post development blogs, it depends on who they're marketing the game to, it's often good marketing to show some "behind the scenes" magic.

http://www.pathofexile.com/news/2011-05-10/dev-diary-modelling

CCP's Eve Online has one of the most geeky fanbase, they post alot of blogs on the technology behind running an MMO (beside the normal balance changes, they post on server maintnence, graphics, development team management, etc.). Their blogs are a great resource.

http://community.eveonline.com/devblog.asp?a=blog&bid=732

http://community.eveonline.com/devblog.asp?a=blog&nbid=3217

These are just examples, they probably don't relate to your question directly. I'd love to provide direct help, but i've never been seriously researching 3D technology, so i don't have anything specific bookmarked. I'm just here to tell you, the information is out there, you just have to dig it out.
> 1 votes

---
Tags: 3d, 3d-meshes
---


# Question
Title: How can I stop the next screen from briefly displaying at the start of a CCTransitionFadeTR?
I am testing transitions in cocos2d, and am running into a problem.

I have a `MainMenu` screen which contains a button. The idea is that clicking on the button will trigger a `CCTransitionFadeTR` transition to a `WhackMain` screen where there is a `CCLabelTTF` which displays "Hello World".

But when I press the button and start the transition, the `WhackMain` screen appears at full opacity for a moment before the transition from `MainMenu` to `WhackMain` begins. The transition appears to be working correctly, apart from `WhackMain` being visible for a moment before the transition begins.

How can I keep this from happening?

Here is my code, if it will help identify the problem:

**MainMenu.m**:

```
#import "MainMenu.h"
#import "WhackMain.h"

@implementation MainMenu

+(CCScene *) scene1 {
// 'scene' is an autorelease object.
CCScene *scene1 = [CCScene node];

// 'layer' is an autorelease object.
MainMenu *layer1 = [MainMenu node];

// add layer as a child to scene
[scene1 addChild: layer1];

// return the scene
return scene1;
}

-(id) init {
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init])) {

    CGSize winSize = [[CCDirector sharedDirector] winSize];

    // Create a label for display purposes
    _label = [[CCLabelTTF labelWithString:@"Last button: None"
                               dimensions:CGSizeMake(320, 50) alignment:UITextAlignmentCenter
                                 fontName:@"Arial" fontSize:32.0] retain];
    _label.position = ccp(winSize.width/2,
                          winSize.height-(_label.contentSize.height/2));
    [self addChild:_label];

    // Standard method to create a button
    CCMenuItem *starMenuItem = [CCMenuItemImage
                                itemFromNormalImage:@"ButtonStar.png" selectedImage:@"ButtonStarSel.png"
                                target:self selector:@selector(starButtonTapped:)];

    // position the label on the center of the screen
    starMenuItem.position =  ccp( winSize.width /2 , winSize.height/2 );

    CCMenu *starMenu = [CCMenu menuWithItems:starMenuItem, nil];
    starMenu.position = CGPointZero;
    [self addChild:starMenu];
}
return self;
}

- (void)starButtonTapped:(id)sender {
  [_label setString:@"Last button: *"];
  [[CCDirector sharedDirector] replaceScene:[CCTransitionFadeTR
                                           transitionWithDuration:2 scene:[WhackMain scene2]]];
}

// on "dealloc" you need to release all your retained objects
- (void) dealloc {
[super dealloc];
}

@end

```

**WhackMenu.m**:

```
#import "WhackMain.h"
#import "MainMenu.h"

@implementation WhackMain

+(CCScene *) scene2 {
// 'scene' is an autorelease object.
CCScene *scene2 = [CCScene node];

// 'layer' is an autorelease object.
WhackMain *layer2 = [WhackMain node];

// add layer as a child to scene
[scene2 addChild: layer2];

// return the scene
return scene2;
}

-(id) init {
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init])) {

    // create and initialize a Label
    CCLabelTTF *label = [CCLabelTTF labelWithString:@"Hello World" fontName:@"Marker Felt" fontSize:64];

    // ask director the the window size
    CGSize size = [[CCDirector sharedDirector] winSize];

    // position the label on the center of the screen
    label.position =  ccp( size.width /2 , size.height/2 );

    // add the label as a child to this Layer
    [self addChild: label];
}
return self;
}

// on "dealloc" you need to release all your retained objects
- (void) dealloc {
[super dealloc];
 }

@end

```

# Answer
Well I tried to recreate your problem in one my projects but it doesn't appear for my case.

There are 2 things you can do here.
1. Install new cocos2d framework,
2. If 1st one doesn't work you can schedule a timer that initializes all your nodes in the given scene after 1 sec like this

```
[self schedule:@selector(somefunction:) interval:1.0f];

```

Which is also not a bad choice as when changing the scene the memory usage is at peak and in this way you will reduce the risk of crashing the app due to low memory warnings.

Mostly people use a loading screen which contains nothing more than a label but if you are have problems in transition than i would say go for the second option even if 1st one works.
> 0 votes

---
Tags: cocos2d-iphone, objective-c
---


# Question
Title: Compressing textures and recompressing textures
Which tools are considered best-quality for compressing textures for use in OpenGL? Which can be used from the Linux commandline?

And which lossless compressors give good ratio/speed on compressed textures?

(I see that Skyrim's BSA archives are typically only half the size of the DDSes they contain)

# Answer
You'll usually find the graphics card manufacturers provide decent tools for compression textures, such as Nvidia here. These seem to be supported on multiple platforms.

For hardware accelerated rendering you'll not find any lossless formats supported that offer any compression. The most popular current formats supported for example by graphics cards under DirectX are DXT1/3/5 for images, DXTN for normal maps. I don't use OpenGL but I'd expect these to be supported even if called something slightly different.

I've typically seen DXT textures zip to about half their original size, so it's possible just using zlib will get you the same end result (then decompress before uploading to the gfx hardware).
> 6 votes

# Answer
Compressed textures always(\*) have fixed compression ratios. Basically all of the formats I've seen take a tile of texels (such as 4x4) and store just enough information to regenerate the tile, or something that resembles that tile closely enough. Comparing different compression methods you have a tradeoff between blurriness and noisiness, but the basic principles (patented, of course) seem to be the same everywhere.

Paletted textures can also be seen as a primitive compression method.

The positive side of these kinds of compression is that it's (relatively) easy to build hardware that can perform random access reads from it. If you'd store your textures as PNGs or JPGs in memory, you'd have to decompress, on average, 50% of the image on every texture fetch. That's just not feasible =)

Due to these limitations, the "compressed" textures can be compressed further with traditional compression methods, like ZLIB

(\*) today, at least. Who knows, maybe someone will think of something new.
> 0 votes

---
Tags: opengl, textures, dds
---