# Question
Title: Optimizing UV Map Sheet Based On Surface Area?
I am trying to get my UV Map Sheets Optimized Based On Surface Area , I need Them optimized cause my scene area is huge and i want to use them in UDK so i am trying to get maximum possible optimization and i am running out of time

Here is What i Try TO Achieve :

**Default 3DS Max** :

**Optimized By HAND** *THIS IS WHAT I WANT Or Even Better If There Is Automated Intelligence Tool*

Also I know this Tools **Flatiron** , **UVPacker** But They Are No Use

# Answer
UVLayout is a professional tool which is specialized in optimizing UV layouts and general UV editing.

Here are some of the features (I highlighted the ones that are probably interesting for your use-case) (source):

> * OBJ import and export
> * Edge-loop Detection for quicker UV seam selection
> * Symmetry Editing for faster flattening of symmetrical meshes
> * Edge Straightening on shell boundaries and interiors
> * Flattening Brushes for local tweaks of the automatically generated UVs
> * **Auto Packing of UV shells to minimize wasted texture space**
> * **Auto Stacking of similar shells for shared texture space usage**
> * Subdivision Surface calculations based on limit surface shape
> * Unlimited Undo of all editing functions
> * Plugin Interface for integration into other applications
> 1 votes

# Answer
Try using Blender to Average then Pack your UV Map. When averaging, it fairly distributes texture space to each surface; and when packing, it fits all the islands into your texture.

For a good quick tutorial on UV Unwrapping in Blender, check out this video from Blender Cookie. (It applies to the latest versions of blender)

Here is a screenshot of a silly cow I made, which gives you a rough idea of UV management in Blender (its not too difficult) (Bigger Version)

I've circled in red the little corner you have to drag to pull out a new panel. After doing so, click on the little box next to the corner you just dragged, and click on Uv/Image editor. If you see a rectange-ish image, click the little 'x' next to the 'Render Result' text that shows up at the middle bottom, where you can see 'CowTex' in my image.

Then click on your cow in the 3d view, tab to go into edit mode, and press A to select all your faces. You should be able to see your current UV layout in the UV/Image editor panel you pulled out.

Then, like I mentioned before, Average and Pack your islands by either using the toolbar lik you see in the image, or Ctrl-A and Ctrl-P. Blender also has a few other ways of helping you with your UV layout, such as iteratively optimizing it, which gives you great results if you give it time.

An advantage of using Blender over other commercial UV solutions is that it is free and open source (in addition to possibly being better than those solutions).

Good luck! :)
> 2 votes

---
Tags: udk, optimization, uv-mapping
---


title: How does A* pathfinding work?

text:
# Question
Title: How does A* pathfinding work?
I would like to understand on a fundamental level the way in which A\* pathfinding works. Any code or psuedo-code implementations as well as visualizations would be helpful.

# Answer
> 65 votes
### Disclaimer

There are tons of code-examples and explanations of A\* to be found online. This question has also received lots of great answers with a lot of useful links. In my answer I'll try to provide an illustrated example of the algorithm, which might be easier to understand than code or descriptions.

---

### Dijkstra's algorithm

To understand A\*, I suggest you first have a look at Dijkstra's algorithm. Let me guide you through the steps Dijkstra's algorithm will perform for a search.

Our start-node is `A` and we want to find the shortest path to `F`. Each edge of the graph has a movement cost associated with it (denoted as black digits next to the edges). Our goal is to evaluate the minimal travel cost for each vertex (or node) of the graph until we hit our goal node.

This is our starting point. We have a list nodes to examine, this list currently is:

```
{ A(0) }

```

`A` has a cost of `0`, all other nodes are set to *infinity* (in a typical implementation, this would be something like `int.MAX_VALUE` or similar).

We take the node with the lowest cost from our list of nodes (since our list only contains `A`, this is our candidate) and visit all its neighbors. We set the *cost* of each neighbor to:

```
Cost_of_Edge + Cost_of_previous_Node

```

and keep track of the previous node (shown as small pink letter below the node). `A` can be marked as solved (red) now, so that we don't visit it again. Our list of candidates now looks like this:

```
{ B(2), D(3), C(4) }

```

Again, we take the node with the lowest cost from our list (`B`) and evaluate its neighbors. The path to `D` is more expensive than the current cost of `D`, therefore this path can be discarded. `E` will be added to our list of candidates, which now looks like this:

```
{ D(3), C(4), E(4) }

```

The next node to examine is now `D`. The connection to `C` can be discarded, as the path isn't *shorter* than the existing cost. We did find a shorter path to `E` though, therefore the cost for `E` and its previous node will be updated. Our list now looks like this:

```
{ E(3), C(4) }

```

So as we did before, we examine the node with the lowest cost from our list, which is now `E`. `E` only has one unsolved neighbor, which is also the target node. The cost to reach the target node is set to `10` and its previous node to `E`. Our list of candidates now looks like this:

```
{ C(4), F(10) }

```

Next we examine `C`. We can update the cost and previous node for `F`. Since our list now has `F` as node with the lowest cost, we're done. Our path can be constructed by backtracking the previous shortest nodes.

---

### A\* algorithm

So you might wonder why I explained Dijkstra to you instead of the A\* algorithm? Well, the only difference is in how you weigh (or sort) your candidates. With Dijkstra it's:

```
Cost_of_Edge + Cost_of_previous_Node

```

With A\* it's:

```
Cost_of_Edge + Cost_of_previous_Node + Estimated_Cost_to_reach_Target_from(Node)

```

Where `Estimated_Cost_to_reach_Target_from` is commonly called a *Heuristic* function. This is a function that will try to estimate the cost to reach the target-node. A good heuristic function will achieve that less nodes will have to be visited to find the target. While Dijkstra's algorithm would expand to all sides, A\* will (thanks to the heuristic) search in the direction of the target.

Amit's page about heuristics has a good overview over common heuristics.

# Answer
> 26 votes
A\* path finding is a best-first type search that uses an additional heuristic.

The first thing you need to do is divide up your search area. For this explanation the map is a square grid of tiles, because most 2D games use a grid of tiles and because that's simple to visualize. Note however that the search area can be broken up in any way you want: a hex grid perhaps, or even arbitrary shapes like Risk. The various map positions are referred to as "nodes" and this algorithm will work any time you have a bunch of nodes to traverse and have defined connections between the nodes.

Anyway, starting at a given starting tile:

* The 8 tiles around the starting tile are "scored" based on a) the cost of moving from the current tile to the next tile (generally 1 for horizontal or vertical movements, sqrt(2) for diagonal movement).
* Each tile is then assigned an additional "heuristic" score--an approximation of the relative worth of moving to each tile. Different heuristics are used, the simplest being the straight-line distance between the centers of the given tile and end tile.
* The current tile is then "closed", and the agent moves to the neighboring tile that is open, has the lowest movement score, and the lowest heuristic score.
* This process is repeated until the goal node is reached, or there are no more open nodes (meaning the agent is blocked).

For diagrams illustrating these steps, refer to this good beginner's tutorial.

There are some improvements that can be made, mainly in improving the heuristic:

* Taking into account terrain differences, roughness, steepness, etc.
* It is also sometimes useful to do a "sweep" across the grid to block out areas of the map that are not efficient paths: a U shape facing the agent, for example. Without a sweep test, the agent would first enter the U, turn around, then leave and go around the edge of the U. A "real" intelligent agent would note the U shaped trap and simply avoid it. Sweeping can help simulate this.

# Answer
> 14 votes
It's far from the best, but this an implementation I did of A\* in C++ a few years ago.

It's probably better that I point you to resources than attempt to explain the entire algorithm. Also, as you read through the wiki article, play with the demo and see if you can visualize how it is working. Leave a comment if you have a specific question.

1. A\* on Wikipedia
2. A\* Java demonstration

# Answer
> 6 votes
You might find ActiveTut's article on Path Finding useful. It goes over both A\* and Dijkstra's Algorithm and the differences between them. It's geared toward Flash developers, but it should provide some good insight on the theory even if you don't use Flash.

# Answer
> 4 votes
One thing that's important to visualize when dealing with A\* and Dijkstra's Algorithm is that A\* is directed; it tries to find the shortest path to a particular point by "guessing" which direction to look. Dijkstra's Algorithm finds the shortest path to /every/ point.

# Answer
> 3 votes
So just as a first statement, A\* is at heart a graph exploration algorithm. Usually in games we use either tiles or other world geometry as the graph, but you can use A\* for other things. The two ur-algorithms for graph traversal are depth-first-search and breadth-first-search. In DFS you always fully explore down your current branch before looking at siblings of the current node, and in BFS you always look at siblings first and then children. A\* tries to find a middle-ground between these where you explore down a branch (so more like DFS) when you are getting closer to the desired goal but sometimes stop and try a sibling if it might have better results down its branch. The actual math is that you keep a list of possible nodes to explore next where each has a "goodness" score indicating how close (in some kind of abstract sense) it is to the goal, lower scores being better (0 would mean you found the goal). You select which to use next by finding the minimum of the score plus the number of nodes away from the root (which is generally the current configuration, or current position in pathfinding). Each time you explore a node you add all its children to this list and then pick the new best one.

# Answer
> 3 votes
On an abstract level, A\* works like this:

* You treat the world as a discrete number of connected nodes, eg. a grid, or a graph.
* To find a path across that world, you need to find a list of adjacent 'nodes' within that space, leading from the start to the goal.
* The naïve approach would be this: calculate every possible permutation of nodes that begin with the start node and finish at the end node, and choose the cheapest. This would obviously take forever on all but the tiniest spaces.
* Therefore alternative approaches attempt to use some knowledge about the world to guess which permutations are worth considering first, and to know whether a given solution can be beaten. This estimate is called a heuristic.
* A\* requires a heuristic that is *admissible*. This means that it never overestimates.
    + A good heuristic for pathfinding problems is the Euclidean distance because we know that the shortest route between 2 points is a straight line. This never overestimates the distance in real-world simulations.
* A\* begins with the start node, and tries successive permutations of that node plus each neighbour, and its neighbour's neighbours, etc., using the heuristic to decide which permutation to try next.
* At each step, A\* looks at the most promising path so far and picks the next neighbouring node that appears to be 'best', based on the distance travelled so far, and the heuristic's estimate of how far would be left to go from that node.
* Because the heuristic never overestimates, and the distance travelled so far is known to be accurate, it will always pick the most optimistic next step.
    + If that next step reaches the goal, you know it has found the shortest route from the last position, because this was the most optimistic guess of the valid ones remaining.
    + If it didn't reach the goal, it is left as a possible point to explore from later. The algorithm now chooses the next most promising possibility, so the logic above still applies.

---
Tags: algorithm, path-finding
---


# Question
Title: What is the proper use of CADisplayLink, and where do I put game logic?
I have an iOS OpenGL ES 2.0 game and currently have a *CADisplayLink* with a :render method. In this render method I do all the game's logic updates and drawing.

Is this correct? Or should my game logic go somewhere else - and if it should go elsewhere... where?

The reason I'm asking is that I've been writing a game and it's starting to exhibit strange behaviour which I suspect is related to the game logic taking longer than a frame to compute, and after following a few different 'fix your timestep'/framerate independent drawing type posts I can't quite match it to how iOS handles things since in iOS there isn't a 'main' style loop.

# Answer
Calling game and update logic when CADisplayLink fires is the correct way of doing things on iOS. Have you profiled your game to see what is taking a long time and interfering with a smooth frame rate?

A nice way of keeping logic updates smooth and decoupled from rendering on iOS is to handle updates when CADisplayLink is called then signal another thread to render and swap the framebuffer. This does introduce some synchronization headaches and issues with OpenGL contexts on different threads, but it's worth investing time in.

The iPhone Doom port uses this sort of solution. There's a good code review here: http://fabiensanglard.net/doomIphone/index.php

Note, iPhone Doom uses an NSTimer, but the principle is the same for updates with CADisplayLink.
> 4 votes

# Answer
I think you can find your answer by checking out the cocos2d-iphone sdk. It uses both OpenGL ES 2.0 and CADisplayLink also its written very well so you might as well us it if you are making a 2D game.

If u are looking for 3D game or application then cocos3d is good.
> 0 votes

---
Tags: ios, opengl-es2, cadisplaylink
---


# Question
Title: How to go from Texture2DContent to Texture2D in a content processor?
I'm using reflection to create a manifest of all assets, strongly typed.

It's working fine for my own types: I get the type of the asset, if a processor is ran on it I get the output type. Then I check to see if there's a `ContentSerializerRuntimeTypeAttribute` applied to the type. If so, then I get the `RuntimeType` value and do a `Type.GetType()` to get the type back.

The problem I have is if the type is `Texture2DContent` (for example) as that doesn't have the `ContentSerializerRuntimeTypeAttribute`.

**How can I go from a `Type` representing `Texture2DContent` to a `Type` representing `Texture2D`?**

I know I can just check for `EndsWith("Content")` as a last resort, but how to I get the namespace qualified type so I can get my `Type` object?

# Answer
Find all Types that inherit from `ContentTypeWriter` and have generic argument of `Texture2DContent` (actualy i think writer exists only for TextureContent), create instance of them and then call `GetRuntimeType`
> 2 votes

---
Tags: xna, c#, xna-content-pipeline, metaprogramming
---


# Question
Title: Testing whether two cubes are touching in space
Does anyone have any clean ideas on testing whether two cubes in 3D space touch? By touch I mean, touch at corners or on a face or on an edge. Say that the cubes are axis aligned and there is no nesting of the cubes. So either the cubes touch or they don't. There is no overlap of the cubes at all (except of course possibly an edge or corner point).

Everything I have thought of ends up needing a ton of cases. Also numerical stability is a factor. I don't want to just test == on all the edges/points.

I guess I could utilize some sort of epsilon instead of testing whether something == 0. The main thing however is minimizing the number of cases to test.

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

So what you have to test is:

```
if ((min_a <= min_b && min_b <= max_a) ||
    (min_b <= min_a && min_a <= max_b))

```

First part (before ||) is for case when min\_a \< min\_b, second for case when min\_b \< min\_a.

For all three axis it looks like this:

```
if (
   ((min_x1 <= min_x2 && min_x2 <= max_x1) || (min_x2 <= min_x1 && min_x1 <= max_x2)) &&
   ((min_y1 <= min_y2 && min_y2 <= max_y1) || (min_y2 <= min_y1 && min_y1 <= max_y2)) &&
   ((min_z1 <= min_z2 && min_z2 <= max_z1) || (min_z2 <= min_z1 && min_z1 <= max_z2))
   )

```

Where for example `min_x` and `max_x` are minimal and maximal coordinates of cube in x axis. `x1` is for first cube, `x2` for second.

As I sad, this tests overlaping, but because there is "\<=" and not only "\<", it test also "touching".

*//EDIT*:

If you want to have more stable solution (there can be some floating point value errors), you should use epsilon. So it will look like: min\_x1 - epsilon \<= min\_x2 && min\_x2 \<= max\_x1 + epsilon

# Answer
> 2 votes
An alternate way to check for AABB collisions is to rule out all cases where you can't collide.

```
if (min_x1 > max_x2) no collision
if (max_x1 < min_x2) no collision
if (min_y1 > max_y2) no collision
if (max_y1 < min_y2) no collision
if (min_z1 > max_z2) no collision
if (max_z1 < min_z2) no collision
otherwise, collision.

```

# Answer
> 2 votes
You certainly want to minimise the number of tests being performed. You can do the test using **only three comparisons**.

Let `(x1,y1,z1)` and `(x2,y2,z2)` be the centres of the cubes. Let `a1` and `a2` be their respective extents (*ie.* half their edge length). The cubes touch by your definition if and only if the distances between the projections of their centres is `a1+a2` in each of the three directions of the coordinate system.

```
/* Returns true if two axis-aligned cubes touch or overlap */
return fabs(x1-x2)-(a1+a2) <= EPSILON
    && fabs(y1-y2)-(a1+a2) <= EPSILON
    && fabs(z1-z2)-(a1+a2) <= EPSILON;

```

Where `EPSILON` is a small number suitable for your typical object sizes and distances. Note that the above meethod will also return true if the cubes overlap, but since this does not happen, it is not a problem.

If the platform you target has fast min/max selection, you can do it using only one test:

```
/* Returns true if two axis-aligned cubes touch or overlap */
return max3(fabs(x1-x2),fabs(y1-y2),fabs(z1-z2))-(a1+a2) <= EPSILON;

```

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

# Answer
> 0 votes
Most likely you will need a spatial data representation that allows for fast dismissal of uninteresting objects. The Octtree is one of the most used structures and fits perfectly with your requirements, plus they are easy to implement. A BSP Tree might be an alternative, depending how your data is set up.

A fast and dirty solution would be to a hash-map to store all points and a reference to all cubes sharing that point. The query would be very fast but at the cost of (a lot of) memory. Although for a small number of cubes that might be applicable.

# Answer
> 0 votes
if your cubes are axis aligned then you may construct tree interval Trees one for each axis.

An intervall tree is a data structure that let you query for an intervall overllapping or a point hit of a set of intervall.

If you can ensure that no cube will ever have an edge less than ε then you can easely see if a cube touches other cubes by querying your trees.

To understand how this works lets scale the problem down to "1D cubes" i.e. segments

It the testing segments is AB then take the points A-ε,A+ε,B-ε,B+ε check the intervall tree for the hit. For every segment that matches there are a few of possible relation with your testing segment:

```
Testing Segment   A- A+ B- B+
Case              -  -  -  -  impossible : no match
Case              X  -  -  -  touch: the segments are disjoint but very near
Case              -  X  -  -  overlap
Case              X  X  -  -  overlap: segments touches for more that 2 epsilon
Case              -  -  X  -  overlap
Case              X  -  X  -  impossible: no holes in segments
Case              -  X  X  -  overlap: the segments are nearly the same
Case              X  X  X  -  overlap: the segments are nearly the same
Case              -  -  -  X  touch: disjointed segments but very near
Case              X  -  -  X  impossible: no holes in segments
Case              -  X  -  X  impossible: no holes in segments
Case              X  X  -  X  impossible: no holes in segments
Case              -  -  X  X  overlap: segments touches for more that 2 epsilon
Case              X  -  X  X  impossible: no holes in segments
Case              -  X  X  X  overlap: the segments are nearly the same
Case              X  X  X  X  overlap: the segments are nearly the same

```

As you can see a segment touches our testing one if A- matches but A+ does not OR B+ matches but B- does not; in any other case (excluding the impossible ones) there is an overlap.

In interval trees other data can be stored alongside the start and the end of the intervall. This possibility can be used to give names to the segments so you can wrap the query function so given a couple of points it gives you a list of (segment\_name,"touch") or (segment\_name,"overlap").

Now we need a way to use 1D results to get 2D results, a way that possibly scale up to 3D and over.

We can say that a rectangle touches another if there is a touch in an axis and an overlap in the other (edge touch) or a touch in both axes (corner touch).

To do this we need to store our intervals into two separate trees taking care of naming intervals correctly.

Let say that we are looking if the rectangle `(Ax,Ay)(Bx,By)` touches some of the stored rectangle, then we have to query the X-tree for `Ax,Bx` and the Y-tree for `Ay,By`.

Lets suppose that the result is `[("alpha","touch"),("beta","touch")]` by *X-tree* and `[("alpha","overlap")]` for *Y-tree* whe can say that our rectangle touches "alpha" ("edge" touches) but don't touches "beta" nor other rectangles.

The test can be easely managed using a dictionary that keep the rectangle name as key and stores the X,Y values for example: `{"alpha":[0,1],"beta":[0,-1]}` means that "alpha" touches(0) in X and overlap(1) in Y while "beta" touches(0) in X but is disjoint in Y(-1).

This reasoning can be extended further adding other dimensions: there is a touch if at least one dimension touches and there are no disjoint dimensions:

```
3D (0:touch, 1:overlap)
X Y Z
0 0 0 corner touch
0 0 1 edge touch (over one of the four Z edge)
0 1 0 edge touch (over one of the four Y edge)
0 1 1 surface touch (over one of the two X surfaces)
1 0 0 edge touch (over one of the four X edge)
1 0 1 surface touch (over one of the two Y surfaces)
1 1 0 surface touch (over one of the two Z surfaces)
1 1 1 eerrr no touch... the cubes are nested (remeber, at least one dimension touch)

```

**\[Appendix\]**

To speed up the interval query match you can test only A- and B+; when you find a match with A- then you get the upper end of the segment that matches and measure the distance with A-: if the distance is greather then 2ε this means that the overlap is too large to be considered a touch so you don't have to continue.

The same has to be done with B+ but this time you have to check the value of B+ with the lower end of the matching segments, again to see if the overlap you find with the extended segment is too large to be considered a simple touch.

A balanced interval tree takes ~log(n) iterations to check if a point hits against n intervals, this means that if you keep (by using red black trees for example) your trees balanced you can check against a huge set in reasonable time

---
Tags: geometry, collision-detection, computational-geometry
---


# Question
Title: How to move the camera in XNA only after few moments?
I made the camera position 10 units from an object, but not behind it. I dont want the camera position behind the object right away when it rotates, I want that when I will rotate the object, the camera position will move slowly until it will be behind the object.

# Answer
> 1 votes
Use a function that Interpolates between the two values such as MathHelper.Lerp or MathHelper.SmoothStep to smoothly rotate to the desired angle.

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


# Question
Title: How do I create a Dynamic Text Button AS3?
I am having difficulties creating a button that has Dynamic text in it for my interactive quiz game.

The text on the button has to change to show a selectable answer based off of what the current question is.

I have this all working well with plain dynamic text fields (and multidimensional arrays) but when I try getting it to work in a button, flash doesn't recognize the textfield that I placed in the button and I get an error.

After doing some googleing I learned that it is normal for flash to not link to a textfield within a button movieclip.

I would be happy if there any strategies that you could suggest for me to achieve Dynamic Text Buttons.

Thanks! Graeme

# Answer
Just use a `MovieClip` instead of a button. You can still draw your button-states as different frames on the timeline and use ActionScript to trigger the correct behavior. You could even write a new base-class for your buttons that you can then apply to all your buttons.

Here's how such a class (`McButton.as`) could look like:

```
package  {
    import flash.display.MovieClip;
    import flash.events.MouseEvent;

    /**
     * Simulate button behavior with a MovieClip.
     * This assumes:
     * - normal state on frame 1
     * - rollover on frame 2
     * - active on frame 3
     */
    public class McButton extends MovieClip {

        public function McButton()
        {
            super();
            mouseChildren = false;
            useHandCursor = buttonMode = true;

            addEventListener(MouseEvent.ROLL_OVER, handleMouse, false, 0, true);
            addEventListener(MouseEvent.ROLL_OUT, handleMouse, false, 0, true);
            addEventListener(MouseEvent.MOUSE_DOWN, handleMouse, false, 0, true);
            addEventListener(MouseEvent.MOUSE_UP, handleMouse, false, 0, true);

            gotoAndStop(1);
        }

        private function handleMouse(evt:MouseEvent):void
        {
            switch(evt.type){
                case MouseEvent.MOUSE_UP:
                case MouseEvent.ROLL_OVER:
                    gotoAndStop(2);
                    break;

                case MouseEvent.ROLL_OUT:
                    gotoAndStop(1);
                    break;

                case MouseEvent.MOUSE_DOWN:
                    gotoAndStop(3);
                    break;
            }
        }
    }
}

```

Then you just create your buttons as MovieClips in the Library and assign the `McButton` as their base-class (instead of `flash.display.MovieClip`), as seen in the following screenshot:
> 0 votes

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


# Question
Title: Is there a tool to import a sprite sheet into Flash as a frame-based animation?
I'm looking for a tool that can help create a Flash-based animation given a spritesheet -- basically the reverse of Spriteloq.

I'd like to take a sheet like the one below, import it into Flash, and then use Spriteloq (or a similar tool) to re-export as an optimized sheet that is compatible with the game engine I'd like to use -- instead of creating software that can read the specific sheet.

# Answer
> 1 votes
Look into either FlashPunk or Flixel. They are bitmap-based (as opposed to vector-based) game libraries in ActionScript 3 that support importing image files like yours as animated sprites.

---
Tags: flash, animation, spritesheet
---


# Question
Title: DirectX11, how to properly update a staging buffer with a structured buffer's count using CopyStructureCount
Alright, I'm not quite sure what is going on with my code at the moment.

I'm currently getting around to defining behavior for my particle system, and to better do this I need to know how many particles are in the buffer on the CPU side. (The particles are held in a structured buffer GPU side)

So I'm using a staging buffer with CPU read access that gets the particle buffer's size using CopyStructureCount and then mapping the staging buffer and reading the count.

This works fine for the first 2 or 3 frames. The count I get from the staging buffer matches how many particles have been spawned. However, once the buffer hits about 400 particles or so all of a sudden my count from the staging buffer resets. I don't have my system killing any particles off at the moment so I know these values are incorrect. I also know there isn't anything wrong my particle system either. I can render, update, and spawn them no problem. (I just need the particle count to help me figure out how many I can spawn and optimize the rendering draw count a tiny bit.)

Here is how I read the staging buffer.

```
struct ParticleUpdatePass_ParticleCountBuffer {
    unsigned int particleCount;
};

// Yeah, I know. Lots of function calls. (Inlined though) I've got wrapper classes for all the D3D11 resources.
pDeviceManager->GetDeviceContext()->CopyStructureCount(particleCountReadBuffer.GetBuffer(), 0,
    _emitter.GetActiveStateBuffer()->GetUnorderedAccessView().GetUnorderedAccessView());
D3D11_MAPPED_SUBRESOURCE _subresource;
particleCountReadBuffer.Map(_subresource, 0); // Essentially translates to - pDeviceManager->GetDeviceContext()->Map(pBuffer, 0, D3D11_MAP_READ, &_subresource;);
ParticleUpdatePass_ParticleCountBuffer _countBuffer(*(ParticleUpdatePass_ParticleCountBuffer*)_subresource.pData);
particleCountReadBuffer.Unmap(0); // pDeviceManager->GetDeviceContext()->Unmap(pBuffer, 0);
_emitter.SetParticleCount(_countBuffer.particleCount);

```

**So my question is essentially, what could I possibly be doing wrong?**

**Edit** \- I'm starting to think that the problem isn't in reading and copying the structure count but in my actual particle update code. I'm using two buffers each update. One contains the particle's initial state, and the other receives the updated particles and they swap. I actually started checking the count for both buffers and saw that the "empty" buffer is retaining a count. I don't see why the initial state buffer wouldn't be getting completely consumed though.

It may be slightly off topic but I'm going to post my update shader. Notice that it also relies on a structure count being copied to a constant buffer. Based on the implementation from this book

```
struct Particle {
    float3 position;
    float  time;
    float3 direction;
    float pad;
};

ConsumeStructuredBuffer<Particle> beforeState : register(u0);
AppendStructuredBuffer<Particle>  afterState : register(u1);

cbuffer SimulationParameters : register(b0) {
    float3 cameraSpaceDelta; // Used to update the particles with how much the camera has moved.
                             // Prevents particles from following the camera around as their space is transformed.
    float timeDelta,
          expirationTime,
          velocity;
};

cbuffer ParticleCount : register(b1) {
    uint particleCount; // Needs the structure count copied from the particle buffer.
};

[numthreads(512, 1, 1)]

void CS(uint3 DispatchThreadID : SV_DispatchThreadID) {
    uint _id = (DispatchThreadID.x)
               + ((DispatchThreadID.y) * 512)
               + ((DispatchThreadID.z) * 512 * 512);

    if (_id < particleCount) {
        Particle p = beforeState.Consume();

        p.time += timeDelta;
        //if (p.time < expirationTime) {
            // Particles are in camera space so they need to be moved with it.
            // Direction also probably needs transformed but that's irrevelevant for the moment.
            p.position -= cameraSpaceDelta;
            p.position += p.direction * timeDelta * velocity;
            afterState.Append(p);
        //}
    }
}

```

**Edit 2** \- Alright so now I've narrowed it down to my particle spawn shader. Not doing any buffer swapping or particle updating. (Just spawning to the same buffer frame after frame) The count is correct the first two frames but then it starts lagging behind. This makes absolutely no sense to me. My thoughts are that the hidden structure count isn't correctly updating (this is out of my control) or I'm just not reading the staging buffer correctly. (Don't think this is the issue either since it stays close)

Here is my particle spawn shader...

```
struct Particle {
    float3 position;
    float  time;
    float3 direction;
    float pad;
};

AppendStructuredBuffer<Particle> simulationState : register(u0);

cbuffer SimulationParameters : register(b0) {
    float3 emitterLocation,
           directionVector;
};

[numthreads(8, 1, 1)]

void CS(uint3 GroupThreadID : SV_GroupThreadID, uint3 DispatchThreadID : SV_DispatchThreadID) {
    Particle p;

    p.position = emitterLocation;
    p.direction = directionVector;
    p.time = 0.0f;
    p.pad = 0.0f;

    simulationState.Append(p);
}

```

# Answer
Alright, think I found the culprit! My count is behaving correctly now. Apparently a structured buffer's count doesn't get initialized upon declaring and creating it. It is initialized while binding that buffer to the pipeline. So the first time my buffer is bound to the pipeline, it needs to have 0 for the count parameter and every other time -1 to use the current count. I also have to be careful and bind my appended buffer with 0 (not -1) every frame since it is suppose to be empty prior to each update.

http://msdn.microsoft.com/en-us/library/ff476404(VS.85).aspx for the function details.
> 1 votes

---
Tags: shaders, directx11, particles
---


# Question
Title: Approaches to partner trick taking card game AI
I am creating an android game out of a partner based trick taking card game. What are some generic approaches to AI players for these types of games and what are the advantages/disadvantages of each?

# Answer
> 2 votes
Implementing an AI for a trick taking game would pretty much just involve implementing the same strategy a human player would use. In this you're in luck, as trick taking game strategy has been widely covered, and I'm sure you'd be able to find a wealth of information on strategies for games like Bridge and 500.

You're helped even more by an AI's ability for perfect memory of cards played, and ability to accurately calculate card probabilities. The hard part would be coding in the subjective cues that partners use to convey their actions, such as leading a low card with the expectation of your partner trumping it.

Your best bet in my opinion would be to find a strategy which is heavy on maths and probability measuring, and use that as the basis for your AI.

---
Tags: ai, card-game
---


title: How are 3D images drawn?

text:
# Question
Title: How are 3D images drawn?
When A computer is to draw a 3d model, does it use maths similar to vector projection? Like when a 3d model is drawn and rotated, does it use vectors/and maybe some other math to know where to draw each of the edges?

If so, is this calculation made everytime the screen is refreshed?

Just want to see if I can create a basic square that looks like its spinning in 3D space. Just for the challenge, not anything practical.

Sorry if I wasn't clear, it is one of those questions where it's difficult to explain.

# Answer
Yes, the computer needs to do a lot of calculations in order to able to render a 3D scene into a naturally 2D screen.

This can be done on the CPU but nowadays it's almost always done on the GPU. This entire process is usually referred to as the **Graphics Pipeline** which I've written about before. Read that post since I believe it summarizes most of the process.

To answer your specific questions:

> does it use maths similar to vector projection?

It uses a lot of different "types of math". It uses a lot of linear algebra which involves vectors and matrices. It deals with transformations such as converting coordinates between different spaces. It uses lighting model calculations to determine the shading of your scene. And it uses *many* other algorithms too.

> If so, is this calculation made everytime the screen is refreshed?

Typically, yes. Most games run on top of a game loop, so the entire pipeline is processed every frame. But under some other environments you could also update it on demand whenever the scene changes (e.g. on WindowsForms by calling Invalidate() to force a redraw of your control).

> Just want to see if I can create a basic square that looks like its spinning in 3D space. Just for the challenge, not anything practical.

You could fake this by simply "skewing" the square as it rotates around, giving the impression that it's 3D. But if you'd like to model it closer to how a 3D graphics pipeline works, the *bare minimum* you'll need is:

* A vertex structure in 3D space
* A list of vertices to define your square in model space
* A world matrix to rotate your square
* A perspective projection matrix to convert it into 2D (clip space)
* A viewport transformation to adapt from clip space into your window/viewport
* A rasterizer to "paint" the rotated square

Depending on which platform you decide to implement this, many or all of these steps may already exist for you to use.

PS: And by the way, I think it's a really good idea from an educational point of view that you're trying to implement this sort of thing. I struggled for a long time with *understanding* how all of this 3D stuff worked, and the moment all of it really *clicked* was when I finally sat down and implemented my own graphics pipeline from scratch. One year later I did the same thing with raytracing, and maybe one of these days I'll try my hands at radiosity too. Or take one step backwards and create some Wolfenstein 3D-ish raycasting scene just for fun.
> 9 votes

# Answer
David has given a good answer, but for a beginner I think it makes 3D rendering sound too hard. The list given is not the *bare minimum* even though 3D engines usually have all of that. In the old days it wasn't uncommon at all to do realtime 3D graphics without any matrices or thinking about different *spaces*.

Matrices is a good way to represent rotation, but there are others as well. If for example you have xy-coordinates and you want to rotate around y-axis, you can just use trigonometry like:

```
rotatedX = cos(angle) * x;
rotatedY = y;
rotatedZ = sin(angle) * x;

```

Projection matrix is useful for representing different kinds of projections, but a simple division by z is often enough to do perspective projection:

```
// CONSTANT depends on the field of view and screen size.
// zOffset can be used to move the objects away from the screen.
screenX = screenWidth / 2 + CONSTANT * rotatedX / (rotatedZ + zOffset);
screenY = screenHeight / 2 + CONSTANT * rotatedY / (rotatedZ + zOffset);

```

If you don't want to work with 3D hardware and rasterization sounds unfamiliar, you can start by rendering the object as a wireframe. Simply draw lines to connect different projected points.

This should be enough to get a square spinning in 3D space to the screen.
> 1 votes

---
Tags: 3d, graphics
---


title: Depth buffer and render target

text:
# Question
Title: Depth buffer and render target
When I use this RenderTarget:

```
renderTarget = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width,
    GraphicsDevice.Viewport.Height, false, SurfaceFormat.Color, DepthFormat.Depth24);

```

and draw something to it:

```
graphicsDevice.SetRenderTarget(renderTarget);
// some drawing code here
graphicsDevice.SetRenderTarget(null);

```

and then when I want to continue with drawing depth buffer seams to be clean. Why? Is possible to save it for future use?

# Answer
> 1 votes
From the deferred rendering articles/tutorials I read it's a limitation in XNA (likely because the XBox 360 probably discards the depth buffer when you change render targets, hence they apply the limitation to Windows as well). What you need to do is use MRT (Multiple Render Targets) and write/test the depth against another `RenderTarget2D` that is something along the lines of `Single`.

When you have finished 'compositing' your depth buffer write it out to the real depth buffer using a screen quad and associated pixel shader.

The first article in J.Coluna's (quite brilliant) series on LPP describes the problem briefly - and his code should provide a nice reference for working around the issue.

# Answer
> 1 votes
It's automatically saved. RenderTarget2D is derived from Texture2D. So in your code sample, 'renderTarget' is a texture that have the render information saved to it.

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


# Question
Title: What is the name for a single 2D polygon on a UV Mapped texture?
When UV Mapping a polygon/texture, is there name that describes a single polygon on the texture.

Does this name differentiate if from the same geometry once it has been mapped to a face?

Would sometime like "UV Tile" or "UV Face" be clear?

# Answer
> 1 votes
I'd say it's a *"UV-mapped triangle"* or *"UV-mapped quad"*. Or simply a *"polygon with UV coordinates"*. I guess it's also fine to just call it the same as the geometry.. eg. UVs of a triangle, quad or polygon. There are some names that are introduced in UV mapping, such as *"patches"*, *"shells"* or *"islands"*, which are all names for a group of connected UV coordinates though.

A polygon doesn't get a new name once it has been UV mapped, it just gets some additional UV coordinates. So it really isn't a *"UV Tile"*.. generally you just talk about UVs (the "vertices") and "shells" or "islands" (connected UVs). If you select a polygon within UV editing, you just select and modify a bunch of UVs...

---
Tags: textures, vertex
---


title: Box2d and sprites

text:
# Question
Title: Box2d and sprites
I have very little experience with box2d, but basically it seems to me that it is possible to attach to it a sprite (that is, a bounding box enclosing the sprite itself) and let box2d to check for collisions.

Now, suppose that our animation is composed of N sprite (for example, a character walking) and that the sprites are not equal in terms of width and/or height of their minimal bounding box.

How do you do with box2d? Compute an average box to enclose the sprites or change the box width/height at every sprite change? The first method seems to fit well only those situations where the sprites bounding boxes are similar.

If that is not the case, the second way is surely the most precise, but I wonder if that is computationally heavy (I mean, to change the size of a box everytime we change the animation frame).

Any advice/ideas are welcome!

# Answer
It depends on the game. In most cases you'll be fine with just some simple shapes that average the sprite over all animation frames. Something as shown here (image from Ray Wenderlichs/Andreas Loews MonkeyJump tutorial) :

You see that three circle shapes are good enough as average for this sprite (the two small circles left and right are just sensors to see at which side a collision happened).

If your sprites do extrem transformations from one stage of animation to another, or if you really need a high accuracy (think a beat-em-up, or some slow-motion close-up), then you should create separate bodies per frame (or animation phase). Then you add/remove the physics bodies at the appropriate time of your animation.
> 2 votes

# Answer
> If that is not the case, the second way is surely the most precise, but i wonder if that is computationally heavy (i mean, to change the size of a box everytime we change the animation frame).

Boxes in Box.2D are represented as polygons. You can easily alter the size by getting the Fixture of the Body and then the Shape of the Fixture. The PolygonShape has a property that lets you access of the polygon data representing the shape and alter it however you need.

I do this often with ~100 bodies and have had no performance issues so far.

Edit: Bummzack is correct. However, after a bit of Googling about, if you call ResetMassData() and then relocate the box to its current rotation/position both the AABB and Mass data will be recalculated. Probably still faster and more flexible than swapping out new fixtures constantly.

```
Body.ResetMassData();
Body.SetTransform(Body.Position, Body.Rotation);

```

Example manipulation of verts. Remember that they are represented in local space around the position of the body.

```
var poly1 = (PolygonShape)Body.FixtureList[0].Shape;
var poly2 = (PolygonShape)Body.FixtureList[1].Shape;

poly1.Vertices[0] = End + perpNormal - center + normal;
poly1.Vertices[1] = End - perpNormal - center + normal;
poly1.Vertices[2] = Start + perpNormal - center - normal;

poly2.Vertices[0] = Start + perpNormal - center - normal;
poly2.Vertices[1] = Start - perpNormal - center - normal;
poly2.Vertices[2] = End - perpNormal - center + normal;

```
> 0 votes

---
Tags: collision-detection, sprites, box2d
---


title: Ball Physics for Android Game

text:
# Question
Title: Ball Physics for Android Game
I am starting work on a new Android game and I haven't had any experience implementing physics before. I am trying to steer clear of external libraries such as box2d, not just because I think it is overkill for my project, but I also want to code it myself for the experience. I am more just interested in getting 1 ball to bounce around the screen and bounce off of objects in my world. The game is in 2D and I was just looking for some advice on where to start with ball physics? I know I will need gravity, x/y velocities... etc. I know I need to calculate how high the ball needs to bounce based on how fast it hit the object, I also know I will need to calculate the correct angle that the ball needs to bounce at. Just hoping to get some ideas on a good place to start and things I will need to take into account.

# Answer
> 0 votes
As you stated, you need to start with forces like gravity and velocity. Define some constants for each of the forces, for example gravity = 0.1; airResistance = 0.05; etc.

Next step is to set a position on the center of the screen and a velocity vector on the ball, with x as a random number between 1 and 2 and y = 0.

In the update loop for the game update the ball's velocity by adding the gravity and subtracting the airResistance, use Pythagorian Theorem to determine what amount of resistance the ball has on each axis. You can imagine if the ball falls straight down, you need to subract the resistance value from the balls y velocity. If the ball were to fly straight to the left, you need to subtract it from the x velocity etc.

When this works, next step is to determine collision with other objects and the screens borders. Lot's of articles can be found about this. (you'll need to check for collision on the current position + the velocity vector)

When a collision is detected, change the direction of the ball accordingly (assuming there's no elasticity and no force lost on impact) If the point of impact is on the left or right, invert x axis, etc

when no collision is found, set the new position for the ball as old position + velocity vector (both x and y).

These are the very basic steps on how to do this, values need to be modified based on the number of updates / sec and need to be balanced for the right effect.

---
Tags: android, java, physics
---


# Question
Title: How to handle pixel-perfect collision detection with rotation?
Does anyone have any ideas how to go about achieving rotational pixel-perfect collision detection with Bitmaps in Android? Or in general for that matter? I have pixel arrays currently but I don't know how to manipulate them based on an arbitrary number of degrees.

# Answer
I'm not familiar with Android so I don't know what tools you have at your disposal, but I can tell you a way to implement this in general terms. How easy it will be depends on what Android provides for you. You're going to need matrices or at least they'll simplify calculations a lot.

For starters do a bounding box collision check and return immediately if they don't collide in order to avoid further computations. That's logical because if the bounding boxes don't collide it's guaranteed that no pixels will be colliding either.

Afterwards, if a pixel perfect collision check is needed, then the most important point is that you have to perform that check in the *same space*. This can be done by taking each pixel from sprite A, applying a series of transformations in order to get them into sprite B's local space, and then check if it collides with any pixel in that position on sprite B. A collision happens when both pixels checked are opaque.

So, the first thing you need is to construct a world matrix for each of the sprites. There are probably tutorials online teaching you how to create one, but it should basically be a concatenation of a few simpler matrices in the following order:

```
Translation(-Origin) * Scale * Rotation * Translation(Position)

```

The utility of this matrix is that by multiplying a point in local space - and for instance if you get the pixels using a method like `bitmap.getPixelAt(10,20)` then 10,20 is defined in local space - by the corresponding world matrix will move it into world space:

```
LocalA * WorldMatrixA -> World
LocalB * WorldMatrixB -> World

```

And if you *invert* the matrices you can also go in the *opposite direction* i.e. transform points from world space into each of the sprite's local spaces depending on which matrix you used:

```
World * InverseWorldMatrixA -> LocalA
World * InverseWorldMatrixB -> LocalB

```

So in order to move a point from *sprite A's local space into sprite B's local space*, you first transform it using sprite A's world matrix, in order to get it into world space, and then using sprite B's *inverse* world matrix, to get it into sprite B's local space:

```
LocalA * WorldMatrixA -> World * InverseWorldMatrixB -> LocalB

```

After the transformation, you check if the new point falls within sprite B's bounds, and if it does, you check the pixel at that location just like you did for sprite A. So the entire process becomes something like this (in pseudocode and untested):

```
bool PixelCollision(Sprite a, Sprite B)
{
    // Go over each pixel in A
    for(i=0; i<a.Width; ++i)
    {
        for(j=0; j<a.Height; ++j)
        {
            // Check if pixel is solid in sprite A
            bool solidA = a.getPixelAt(i,j).Alpha > 0;

            // Calculate where that pixel lies within sprite B's bounds
            Vector3 positionB = new Vector3(i,j,0) * a.WorldMatrix * b.InverseWorldMatrix;

            // If it's outside bounds skip to the next pixel
            if(positionB.X<0 || positionB.Y<0 ||
               positionB.X>=b.Width || positionB.Y>=b.Height) continue;

            // Check if pixel is solid in sprite B
            bool solidB = b.getPixelAt(positionB.X, positionB.Y).Alpha > 0;

            // If both are solid then report collision
            if(solidA && solidB) return true;
        }
    }
    return false;
}

```
> 11 votes

# Answer
While David Gouveia's answer sounds correct, it is not the best solution from a performance point of view. There are several important optimizations you need to do:

1. sort out and avoid unnecessary checks by checking first with a simple circle collision: to get the center and radius of your sprites in any rotation, get the minima and maxima x and y coordinates of all 4 (already rotated) vertices: then you can construct an circle closing in the sprite by:

center = max\_x-min\_x/2 , max\_y-min\_y/2

radius = max(max\_x-min\_x, max\_y-min\_y)
2. now you should have not too many candidates to check by rasterizing the already transformed (rotated) images basically by using a **simple affine texturemapping algorithm**. Basically you keep track of 4 lines per rasterized sprite: 2 lines going from vertex a to the next vertices of your rotated box (b and c) 2 lines going in "bitmap space" from vertex u1/v1 to the next vertices u2/v2 and u3/v3: Note: I googled this image and it shows a triangle, your boxes are just two triangles. It is vital for this algorithm to draw **horizontal** lines (that's why it is called "*rasterizer*") to avoid "holes" inside the bitmap due to round off errors. By calculating the lines with a **bresenham algorithm**, you need for each pixel only 4 additions and 4 compares (and sometimes two additional adds, depending on the slope) What you do is you write your own polygon texturemapper, however without the costly(and difficult to optimize) 3d correction.
3. you can easily reduce the resolution of the collision bitmaps (for example by factor 2) and save even more time. a collision check on half of the resolution shouild be unnoticeable.
4. If you are using graphics accelleration it could be possible to use some kind of HW-accelerated Buffer check(stencil?) to avoid coding the rasterizer by yourself..

The main problem is: Java is not very fast on accessing bitmap data stored in an 2D-array. I would recommend to store the data in a 1-dimensional array to avoid at least 1 indexOutOfBounds check for each access. Also use power-of-2 dimensions(like 64x64, 128x128, etc. By this you can calculate the offset via bitshifting and not multiplication). You can also optimize the second texture access to perform it only if first one has value != 0 (transparent)

All these problems were solved in software rendering engines, it could be useful to look into sourcecode
> 2 votes

---
Tags: android, java, collision-detection, graphics
---


# Question
Title: Scrolling the camera when the mouse cursor gets to the edge of the screen
I was wondering if you could help me:

In XNA I have a hexagonal map, and the size of the map currently exceeds the size of the window. There is already code in place to move the 'camera' around the map using the directional keys, which is as follows:

```
if (ks.IsKeyDown(Keys.Left))
        {
            Camera.Location.X = MathHelper.Clamp(Camera.Location.X - 8, 0,
                (myMap.MapWidth - squaresAcross) * Tile.TileStepX);
        }

```

But I'd prefer using the mouse, like in good ol' Command and Conquer.

So basically: If mouse coords are within 5 pixels of game window edge, move map appropriately'. Any help would be greatly appreciated!

# Answer
> 4 votes
*You have somewhat answered your own question :) (everything after "so basically"). I don't have XNA here so YMMV with my code. Furthermore - it's (from what I can tell) usually a 1px border.*

# Using Rectangles

What you first need to do is determine the position in terms of your `Viewport`. What we do is create some rectangles and check if the mouse cursor is in each of them. If it is we use the associated `Vector2` to move the camera.

```
private List<Tuple<Rectangle, Vector2>> _rectangles = new List<Tuple<Rectangle, Vector2>>();
private Rectangle _noActionRectangle;
private const int MouseCameraBorder = 5; // Really, this should be 1.

// ...

GraphicsDevice.DeviceReset += GraphicsDevice_Reset;
GraphicsDevice_Reset(GraphicsDevice, EventArgs.Empty);

// ...

void GraphicsDevice_Reset(object sender, EventArgs args)
{
    var vp = GraphicsDevice.Viewport;
    _rectangles.Clear();
    // Top/left
    _rectangles.Add(Tuple.Create(new Rectangle(0, 0, MouseCameraBorder, MouseCameraBorder), new Vector2(-1, -1)));
    // Left, but excluding the top/left and bottom/left.
    _rectangles.Add(Tuple.Create(new Rectangle(0, MouseCameraBorder, vp.Height - MouseCameraBorder * 2, MouseCameraBorder), new Vector2(-1, 0));
    // Add the rest of the 8 rectangles that are
    // - Corners
    // - Sides excluding the corners.
    _noActionRectangle = new Rectangle(MouseCameraBorder, MouseCameraBorder, vp.Height - MouseCameraBorder * 2, vp.Width - MouseCameraBorder * 2);
}

// ...

var ms = Mouse.GetState();
var msPt = new Point(ms.X, ms.Y);
// Make sure we are not wasting team checking each rectangle if the
// mouse is not in any of them.
if (!_noActionRectangle.Contains(msPt))
{
    foreach(var pair in _rectangles)
    {
        if (pair.Item1.Contains(msPt))
        {
           // ... Move your camera based on pair.Item2.
           break;
        }
    }
}

```

# Using Offset

You might want to try this approach and see if it works out better than the rectangle approach. Essentially what you do is make sure the mouse cursor is not inside the `_noActionRectangle` and then calculate how to move the camera based off of how far away from the center of the screen the mouse cursor is.

```
private Vector2 _screenSizeOver2; // Should be Size technically, but we want floats.
private Rectangle _noActionRectangle;
private const int MouseCameraBorder = 5; // Really, this should be 1.

// ...

GraphicsDevice.DeviceReset += GraphicsDevice_Reset;
GraphicsDevice_Reset(GraphicsDevice, EventArgs.Empty);

// ...

void GraphicsDevice_Reset(object sender, EventArgs args)
{
    var vp = GraphicsDevice.Viewport;
    _noActionRectangle = new Rectangle(MouseCameraBorder, MouseCameraBorder, vp.Height - MouseCameraBorder * 2, vp.Width - MouseCameraBorder * 2);
    _screenSizeOver2 = new Vector2(vp.Width / 2, vp.Height / 2);
}

// ...

var ms = Mouse.GetState();
var msV = new Vector2((ms.X - _screenSizeOver2.X) / _screenSizeOver2.X, (ms.Y - _screenSizeOver2.Y) / _screenSizeOver2.Y);
var msPt = new Point(ms.X, ms.Y);
if (!_noActionRectangle.Contains(msPt))
{
   // ... Move camera based on msV - it will lie in the range [-1 ... 1]
}

```

---
Tags: xna, 2d, mouse, rts
---


# Question
Title: How do I perform a slice effect like Fruit Ninja?
I want to do slice effect like in Fruit Ninja. Is there any class in Cocos2D like CCBlade? How can I use the CCBlade in Cocos2D on Android?

# Answer
> 2 votes
CCBlade https://github.com/hiepnd/CCBlade

There is an example provided with the project. Don't know what more you could wish, except for somebody making your game.

---
Tags: android, cocos2d
---


# Question
Title: Help for choosing a cost effective game server for Flash client
I am developing a flash-based game primarily for desktops, to be hosted on facebook platform (like cityville, sims social etc). The gameplay doesn't involve real-time communication between players unlike an mmorpg. Here each player plays in his own world without any knowledge of other online players. I've written almost 95% of the game logic in actionscript on the client side.
I used **Smartfox Server pro** on the server side (mostly used for getting data from the DB) and the entire server code is an extension written in java. I'm using *json* as the protocol for communication.
Although I love smartfox server, as an indie, its tough for me to afford the unlimited users license. Morever its limited just to one machine. So I'm looking for an alternative to smartfox server now.

The reason for choosing smartfox server earlier was to use the **server properties** supported by it.

Server properties on smartfox server take advantage of the socket connection and are essentially server side objects in java which store some data for the player which he can change frequently during the game. And when he logs out of the game, the extension can write out the final state in the DB (I'm using MySQL). This significantly reduces the number of DB UPDATE/INSERT calls made during the game.

I love the way this works since the data is secure as its on the server side and smartfox server is known to be scalable. (although I'm not sure whether this approach is used widely by gaming industry or not, since this is not an mmorpg, I'm putting all player in the lobby).
So my question is whether any of the free and community supported servers like reddwarf, firebase, BlazeDS etc can provide a similar architecture so that I can use server properties without many code changes?

**EDIT :** I am not insisting on the exact same feature (thats asking too much!), but atleast a viable messaging system on the server so that I can send actionscript objects from the client using json/binary so that its fast. OR maybe some completely different way to implement what I need here. Thanks in advance.

# Answer
Have you looked at using Red5 as your server? The default includes Tomcat so you can write servlets or regular java web app code to do anything you need done at that tier. All the rtmp communications that you could want comes with this for free; free as in it costs you nothing, but you have to write what you need at the server level where the sky's the limit.
> 2 votes

---
Tags: java, flash, actionscript-3, server, smartfox
---


# Question
Title: A* : Partial recalculation when one node *changes*
I have implemented an A\* library. Its most interesting feature is that it is "interruptible"; for example, you can stop the calculation loop on a game frame, and resume it later on the following frame.

The library works by creating "Nodes". Each node holds information about a cell in a grid: what is the cost to get there, what is the cell's "parent" (from which it is cheaper to get to the cell) etc. This information is stored until manually released; it is available for other uses if needed.

The "bestNode" is a pointer to one of such nodes. When the search starts, it is the "origin", and it gradually changes until the destination is reached.

Now I'd like to use that information to "partially recalculate" the node information when a node changes; the typical example is a door which opens/closes, allowing new paths/cancelling existing paths. Since I have already calculated the path from the origin to the "changed" node, I'd like to conserve that info, instead of re-calculating everything.

So far my thinking is:

```
function update(location)
  If the modified location is not in a node, return // not affected
  let node = self.nodes[location]
  let parent = node.parent
  delete all nodes that where created after parent
  add parent to the open list
  bestNode = parent
end

```

So I have two problems:

* I don't know how to select the "nodes created after parent". Would a "unique increasing integer", like in a database, be enough?
* This looks kind of complicated and clumsy. Is there a simpler way to do it?

Are there any other "partially-re-calculable" A\* algorithms out there? I could not find anything on the subject.

Regards!

# Answer
> 3 votes
I have found Lifelong Planning, which seems to do pretty much what I wanted - it "reuses" the previous calculations to compute "a difference".

There is a demo applet (java), too. Draw some walls, calculate the paths, then draw some more and calculate them again.

# Answer
> 6 votes
You'll probably get farther with Google with a bit of terminology: the usual jargon for a recalculation of an A\* path is a "replan". In more specific direction, the situation you raise is the primary stated motivation of HPA\*; it's a fairly well proven-out algorithm at this point and is likely to provide solid guidance.

# Answer
> 4 votes
@RichardMarskell-Drackir in the comments has it right imo. Richard is trying to describe a scenario where more than just the subsequent A\* calculations are invalid and you will will either have to completely recalculate the entire path from where you are now, or at a minimum find a way to roll-back the A\* calculation even further than the changing tile. Here's the example Richard was explaining:

You don't want the pathfinding algorithm to walk you right up to the closed door then turn around, you want to turn around right away. There may be shortcuts for certain specific scenarios, but in the general case, you'll want to recalc, or store the entire A\* tree and be able to roll-back all invalid calculations.

---
Tags: algorithm, path-finding, lua
---


# Question
Title: Are shader-based antialiasing methods making traditional multisampling obsolete?
See an analysis of FXAA here, and the page for SMAA here

Now these methods have a drawback which is that they are not capable of improving quality in a physically accurate way, like multisampling does (what I mean by this is that it brings out the sub-pixel details from geometry by super-rasterizing), but they are a terrific method for curtailing visual artifacts which are a result of regular rasterization.

Case in point: I run an Nvidia GTX 260, it came moderately overclocked from the factory, it is a Gigabyte Super Overclock model. I also run a 1920x1200 screen.

It's sometimes difficult to maintain good framerates when I play Battlefield 3, but I've noticed some general improvements in terms of speed recently which has made the game play quite a bit better today than it did back when it was released.

The point is, the performance hit caused by 4xMSAA or even 2xMSAA is very noticeable in this game at my full resolution, because it needs all the power it can get. However, FXAA post processing antialiasing comes at almost no cost! A month or two ago, I found myself running the game in windowed mode most of the time because it achieved better framerates that way. But now I've discovered that disabling MSAA and using FXAA almost completely eliminates edge-artifacts without the performance hit of MSAA.

I find that shader-post-process AA is extremely good at producing smooth edges when lines are near-horizontal or near-vertical, and also with thin objects, like the cables on the telephone pole in the link. On still images, a similar smoothness quality is unobtainable until you crank MSAA to 16x.

However shader-post-process AA does not eliminate temporal aliasing artifacts: Even though edges are smoothed terrifically, they "jump" as they move across pixel boundaries.

The reason why this happens is because the shader-AA has no knowledge of actual geometric coverage data, which is what MSAA and friends are essentially based on. As an edge traverses the pixel boundary, our smooth edge will "jump" the length of a pixel, rather than smoothly blending in and out like we would see with 16xMSAA/CSAA. CSAA is particularly good for this because it rasterizes at a higher resolution than MSAA.

So with all this in mind I don't think that shader-based antialiasing methods are a replacement for traditional methods. However I think they are a really cool way to improve image quality in almost every situation. They have the benefit of not requiring a different render buffer storage format.

I think that, going forward, the best way to apply antialiasing in games would be a combination of coverage sampling AA and post-process AA.

Jeff Atwood claims that FXAA made MSAA/CSAA obsolete overnight. What do you think? What are some other ways to compare and contrast traditional antialiasing with shader-based antialiasing?

# Answer
Generally speaking, yes, postprocess antialiasing like FXAA is making MSAA much less popular.

As you mentioned, the performance hit for MSAA is very high, mainly due to the increased memory bandwidth required for reading/writing render targets. It also, of course, consumes a lot more memory for those render targets - not as big a deal for PC gamers who usually have lots of memory, but a real big deal for consoles. To do MSAA on a console requires you to make big sacrifices in some other aspect of the graphics. MSAA is also tricky to get working right with deferred-shading renderers, which are becoming more common. Meanwhile, FXAA is fast, usually doesn't require any extra memory, and is very easy to bolt on to an existing rendering pipeline. It's no wonder game developers are flocking to it!

Moreover, as screen resolutions get higher, the visual quality benefits of MSAA over FXAA will diminish in many cases. There's an interesting article here about different kinds of visual acuity and when MSAA really makes a difference.

Eventually, of course, we expect to get to screen resolutions so high that no AA is necessary at all. That's quite a few years away. But MSAA will die a long time before postprocessing AA does.
> 4 votes

---
Tags: antialiasing
---


title: Wavefront *.obj loader in C++

text:
# Question
Title: Wavefront *.obj loader in C++
I'm creating a game using OpenGL (via SDL) and C++ (via Visual Studios 2010 Professional). During the game, I will be using 3D character animation. I'd like to use wavefront \*.obj files for all the 3D models (with the exception of terrain). The characters will need to have fluent movements (realistic), with as many as 250-500 frames (for walking, running, sprinting, jumping, crouching, crawling, etc.). I'd like to use either md2 or md3, but the 3D modelling/animation tool I'll be using (Blender 3D 2.57) doesn't support either one. The game will only be running on Windows.

What I need is a small yet powerful \*.obj loader and parser that supports animation. It must be written in C++ and be usable by SDL.

Thanks

**Alright, after looking at all the file formats that Blender can export to...I've decided to go with 3DS because it produces the smallest file format when I export the default cube. Thanks @Daniel For recommending 3DS!**

# Answer
OBJ does not support animation, for more information read this.

For a compliant OBJ loader, lib-obj comes to mind.

If you want to home brew, **and** you can ensure the file only contains triangles; no quads etc, parsing an OBJ is arbitrary (its only text!):

```
        char prefix[10] = {0};
        stream >> prefix;

        switch (prefix[0]) {
            case 'v' : {
                switch (prefix[1]) {
                    case 't' : {} break; // texcoords
                    case 'n' : {} break; // normals
                    default : { // points
                        float x, y, z;
                        stream >> x >> y >> z;
                        // put in a mesh etc
                    }
                }
            } break;
            case 'f' : {
                unsigned short a, b, c;
                stream >> a >> b >> c;

                // etc
            } break;
            default : {} // skip
        }
    }

```

If in doubt, look to the specification.
> 5 votes

# Answer
Just because Blender offers you an exporter for Wavefront doesn't mean, that the whole animation will be exported as well. Wavefront OBJ doesn't know animation!

On the other hand it's perfectly possible to implement a exporter Add On for md2 / md3, and AFAIK those already exist.

That being said, as I understood it, you intend to store the full mesh for each animation frame. This is a very inefficient way to do animation. A better approach would be to just store keyframes and interpolate between those. Or even better: Implement a mesh deformation system that's compatible with Blender's animation system, or implement your own mesh deformation system for both Blender and your program. Animating simple whole object transformations is easy. Mesh deformations in Blender typically happen through the builtin Armature modifier, but it's perfectly possible to implement a own mesh deformation operator as stand in replacement for the Armature modifier.

ATM I'm developing an export/import Blender Add-On that dumps all the currently loaded data into JSON format; either one big file or a single file for each data block. The main idea is to use it with WebGL (i.e. implementing a WebGL engine that allows to load stuff originally created for the Blender Game Engine). Maybe I can interest you in using JSON for storing model and information.
> 1 votes

# Answer
Although the .obj specification doesnt support animations natively, by simply augmenting it with a seperate .anm file you can get brilliant boneless animations.

Have a look at:- http://public.sanguinelabs.co.uk/expose/product.php?id=wastudio

This provides a very easy to use tool to create the animations and also provides an open-source model library (for OpenGL) so you can get the animated models working in your project quickly.

Note: I am the developer of Wavefront Animation Studio and libwavefront so feel free to email me if you have any improvements or bugs to report. The software was developed during my time at university because I found it extremely awkward to create and display animations using the complex tools and libraries currently available.
> 1 votes

# Answer
The answer to what you seek is not \*.obj because it is pretty much like a bitmap for animation (you can export it with Blender but you have to tell blender to export every frame as a single \*.obj file \[NOT EFFICIENT IN ANY ASPECTS\], like a movie and it's frames). What you really seek is Collada. There is a mesh loader called assimp, and it loads like a million mesh formats (I am using it for my new engine). And what you said about \*.3DS is not always true.
> 0 votes

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


# Question
Title: BOX2D Kinematic Platform with parallax layer
I am using a kinematic body for my moving platform on x-axis, so I set the linear velocity to `b2vec2(5,0)`.

When the player jump on the platform, it works like it is suppose to. But the thing is that my platform is on the obstacle layer and I am moving it with the parallax layer.

So if I `setTransform` the kinematic platform to follow the obstacle layer than it's physics will not work and the player will slip-off the platform.

I'm developing for iOS and using cocos2d api. Anyway around this?

# Answer
> 1 votes
I've found a solution. I calculate the layer offset difference then minus it from the velocity and apply it to the setLinearVelocity rather than the setTransform method. Cheers.

---
Tags: physics, cocos2d-iphone, ios, moving-platforms
---


# Question
Title: Help me choosing a 3d modelling software for this project?
I'm making a video where I want to show a few scenarios of a game in 3d:

It has some objects with simple shapes - stairs, walls, barrels. So all I have to do is to model those simple objects and apply the proper textures on the right faces. I have never learned a 3d modelling software so I would like to know, what of them is more suited to this task?

If possible, it would be even better if I could just do it with scripts (python?). For instance, I could make a script that returns the vertex/faces and let the program calculate the model. This would be great as I could get the geometries really fast and then just configure the textures. I'm not really a fan of modelling with the mouse, I always get lost with so many views and stuff.

# Answer
Sketchup is probably the most accessible for people who don't have "real" 3D experience.

Especially so if your shapes are mostly just boxes. It's a couple click/drags.

If you're looking for a format that you'd be easily able to edit or script, you should check out the OBJ format. It's a plain-text format that is dead-simple to understand.
> 4 votes

---
Tags: 3d
---


# Question
Title: Intuitive way to handle dragging outside the Arc Ball?
So I'm writing a game (or toy, rather), which involves manipulating a 3d object with the mouse. I'm trying to get the most intuitive control that I can.

I've implemented the "Arc Ball" mouse control. I'm happy with how it "feels", except for when I drag the mouse outside the range of the virtual ball.

Currently when the ray from camera to mouse-pointer in world-space does not intersect the virtual sphere, I simply find the closest point to it.

This results in something that acts like this example (not my code, just an example I found with the same implementation as me).

Notice the behaviour change when you click and drag away from the cube.

I'm not sure if it makes sense, but I am hoping for some way of allowing the cube to continue to rotate no matter how far away the mouse pointer gets, while still maintaining the useful property of standard Arc Ball that returning the pointer to the starting point will undo all rotation.

Any suggestions?

# Answer
I haven't really thought this through but how about this:

Let the distance from the center of the sphere to the border (in screen coordinates) be X. When the mouse moves away X from the center of the sphere, the sphere should rotate 1/4PI for a correct feeling (eg keeping under the mouse which was under the mouse). Now let Y be the distance from the sphere center to mouse in screen coordinates. The radians the sphere should rotate now is Y/X * 1/4PI and you should rotate over the axis perpendicular to that of the imaginary line between the center of the sphere and the mouse pointer (be sure to map this back to world coordinates this time first).

Be sure to be careful with rotations after rotations, maybe use quaternions if you're not already using them.
> 1 votes

# Answer
When implementing arc-ball rotation myself, I personally found that thinking it from the camera's perspective was must more easy and intuitive for me. Also, most (if not all) 3D programs (CAD, level editors) allow you to rotate the camera around a focus point (in your program, the focus point can be the centre of your object).

Instead of repeating the steps/answer, I will just link to it.
> 1 votes

---
Tags: xna, 3d, user-experience
---


title: Sliding down the slope

text:
# Question
Title: Sliding down the slope
I've just gotten a triangle collision object in using the Separate Axis Theorem, the triangle has a 45 degree slope and resloves collision detection via the projection method. The actual collision detection works fine, but I'm having an issue where the character keeps slipping down the slope when he runs up or goes down it.

These are the number for the characters movement. I know I should be doing something with either the part of the Y velocity or somehow changing the x velocity but not sure what.

The number for the velocity

```
private float accerlation = 0.25f;
 velocity.X = velocity.X - accerlation

private float superaccerlation = 0.3f;
velocity.X = velocity.X - superaccerlation

```

How the collision is being resolved.

```
if (collision == TileCollision.LeftSlope)
{
    Vector2 triDepth = RectangleExtensions.GetIntersectionDepthTriLeft(bounds, tileBounds);

    if (triDepth.X != 0 && triDepth.Y != 0)
    {
        isOnSlope = true;
        Position = new Vector2(Position.X + triDepth.X, Position.Y + triDepth.Y);
    }
    else if (triDepth.X != 0 && triDepth.Y == 0)
        Position = new Vector2(Position.X + triDepth.X, Position.Y);
    else if (triDepth.X == 0 && triDepth.Y != 0)
    {
        headOnRoof = true;
        Position = new Vector2(Position.X, Position.Y + triDepth.Y);
    }

    bounds = BoundingRectangle;

}

```

# Answer
> 2 votes
I'm assuming that this is a platformer game and that your character collision shape is a rectangle.

You didn't give enough information for me to definitively say what the problem is, but I can guess. Your character will look like he's sliding down the slope if you are applying gravity every frame and always project out the shortest intersection distance. Instead, you want to always move him up on the y axis.

I drew a diagram that can explain my thoughts better than words:

---
Tags: xna, physics
---


# Question
Title: Correct texture format for Moai with TexturePacker
We are going to use TexturePacker to create our texture atlases for a Moai-based game. I'm wondering what the correct texture format and image format is to use specifically for Moai. Should I just use png and RGBA4444 or can you use pvr and PVRTC4? PVRTC4 format seems to create a texture that indicates less RAM usage but I'm unsure if we can use this format.

# Answer
> 1 votes
According to this post: http://getmoai.com/forums/post667.html#p667 MOAI supports PVR format.

But in the end it's a matter of quality. PVRTC may be good enough for background images but I would not recommend using it for foreground because the quality is not too good through the heavy lossy compression.

---
Tags: textures, memory-efficiency
---


# Question
Title: CLR Profiler Allocated Bytes and XNA ContentManager
I've been fighting with XNA ContentManager and memory allocations for some weeks because I'm trying to port my game from XNA (Windows) to ExEn / Monotouch (iphone).

The problem is that after playing a few levels, my game exits unexpectedly on a real iPhone device (not simulator).

Profiling memory usage on Windows with CLRProfile, I found some useful stuff but I also found something I dont understand. If I use 2 ContentManagers (1 for shared assets and 1 for level assets), when profiling, "Allocated Bytes" grows and grows after level through level but Memory consumption measured by Windows Task Manager stays constant (down when I unload the content manager and up again when I load content). Obviously, I contentManager.Unload() when level ends. After a few levels my game exits unexpectedly on an iPhone device.

If I use 1 content manager, "CRLProfiler Allocated Bytes" stays constant on Windows and on the iPhone; I can play the game normally and it doesnt exit unexpectedly. I use the same assets level through level.

It seems like in ios (iPhone) when loading and unloading the same assets, it allocates memory and consumes all device memory, so the ios kill it.

Can anybody explain me how this really works?
I've read quite a bit, but I still don't understand what's going on.

# Answer
The garbage collector might work in unpredictable ways. You probably want to do a GC.Collect() at the end of your level loading logic to ensure that all releasable memory is indeed released. I don't know if there are any difference between the GC behavior in the simulator or on the device, but make sure you are making it easy for your ContentManager to be collected by null'ing all references to it and the content itself.

You might want to use the Instruments profiling tool (or something else, CLR Profiler?) while running on the actual device to check the memory allocation / release patterns and see if it's indeed a memory-related issue.

As a rule of thumb, you should avoid allocating memory during gameplay (create all game objects ahead of time or have pools) so that you can avoid accidentally triggering the GC while the game is supposed to be interactive.

Finally, try reducing your problem to a minimum reproducible test case by removing all game logic, display, anything that isn't needed to make the whole thing crash, and make sure that it still crashes. This should either help you find what you did wrong or help you locate any bugs that might exist in MonoTouch / ExEn / any other frameworks you might use.
> 1 votes

---
Tags: xna, ios, monotouch
---


title: Havok SDK and Android, where to begin

text:
# Question
Title: Havok SDK and Android, where to begin
The Havok games SDK is cross platform and supports android according to this link http://www.havok.com/solutions/mobile-game-developers

I want to explore the sdk but don't know from where to begin, didn't find any resources on how to use Havok with Android.

can anybody provide me with links,books, resources on how to start.

thanks

# Answer
> 1 votes
Thanks, I downloaded the free binaries from here software.intel.com/sites/havok/en and found support forum from here software.intel.com/en-us/forums/havok

# Answer
> 1 votes
Afaik you must buy Havok to get it for Android: http://www.havok.com/sales

---
Tags: android, havok
---


title: How can I create gradiented Fog of War?

text:
# Question
Title: How can I create gradiented Fog of War?
I'm creating a top down 2D RTS game for educational purposes. Currently, I'm really just copying Starcraft's design/ideas. I've decided I should probably implement Fog Of War too.

My expectations:

* Areas currently explored (units are there) should be lit up.
* Areas previsouly explored (units *were* there) should be darker but show what things *were* there when your unit was there.
* Areas not explored (areas your units have never been to) should be completely black.
* There should be a gradient change from each type (e.g. explored to previously explored) See picture below.

Just the rough details: How would I do this?

# Answer
You should add more information about how you are implementing the game, but here are a few sugestions:

* Keep a bitmap of the whole map, each time a new area is explored just flip the corresponding bits as they become visible. You can do the same for the revealed area.
* Enemy units are drawn only if they are in the revealed area. You'll need to keep a 'last seen' state for buildings in the FOW area.
* You don't need to update visibility every frame - depending on your maximum unit speed, 5 or 10fps should be quite enough.
* Assuming you are using square tiles, you'll just need 4 masks to get the results you need: one for a 'solid' (blacked out) tile, one 'elbow' and one 'corner' gradient, and one 'straight edge' gradient. You can get all others from these using rotations and different transparencies.

Hope that helps.
> 11 votes

---
Tags: 2d, xna-4.0, rts, fog-of-war
---


# Question
Title: displaying image on modelmesh with transparency
i have a modelmesh that has a image on it. When i draw the modelmesh i get the image but i also get a black bacground. The image is png and transparent and is added in 3ds max(i don't give it coordinates to be drawn, it sits on the modelmesh). How can i make the black background transparent?

Here is my drawing code:

```
 foreach (BasicEffect effect2 in modelMesh)
 {
     effect2.DiffuseColor = Color.White.ToVector3();
     effect2.LightingEnabled = true;
     effect2.AmbientLightColor = new Vector3(1, 1, 1);
     effect2.Projection = camera.projectionMatrix;
     effect2.View = camera.viewMatrix;
     effect2.World = transforms[modelMesh.ParentBone.Index] * gameobject.orientation;
     effect2.Alpha = 1;

  }
  modelMesh.Draw();

```

# Answer
> 1 votes
SharedGraphicsDeviceManager.Current.GraphicsDevice.BlendState = BlendState.AlphaBlend; fixed the problem (XNA 4.0)

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


# Question
Title: Are there any issues with not drawing to all render targets when using MRT?
Lets say I set 2 render targets:

device.SetRenderTargets(color, depth);

And then half my draw code only outputs color and not depth. This works fine on the PC and produces the expected results however I feel like this might be an issue on the Xbox.

Are there any issues I should be aware of when using MRT while only outputing to one render target?

# Answer
First of all, using a color buffer and a depth buffer isn't really MRT. That term is used when you have multiple color buffers and are sending different outputs to each.

But to answer your question, no, there should be no issue. Any render targets that are disabled by the current states will not be written to. You can turn color writes or depth writes on and off whenever you like.

The X360 GPU is really just a slightly-modified version of a certain PC GPU chipset. It's not like it's different in a fundamental enough way that enabling/disabling depth writes behaves differently.
> 2 votes

# Answer
I don't think it'll be an issue on the Xbox as long as you don't accidentally clear the rendertarget before you are done with it. To be on the sure side when only writing to your color rendertarget, make sure to choose a BlendState which disables color writes to your depth rendertarget. You'll even save some bandwith/performance this way.

E.g. create a new BlendState disabling color writes to second rendertarget:

```
protected override void LoadContent()
{
    this._blendState = new Blendstate()
    {
        ColorWriteChannels1 = ColorWriteChannels.None,
    }
}

```

Then set this state before you do your draw calls only outputting to the color rendertarget (and reset afterwards):

```
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.SetRendertargets(color, depth);
    GraphicsDevice.BlendState = BlendState.Opaque; // .. or any other BlendState

    {.. draws to both rendertargets ..}

    GraphicsDevice.BlendState = this._blendState;

    {.. draws only to color rendertarget ..}
}

```
> 0 votes

---
Tags: xna, graphics, rendering, graphics-programming
---


# Question
Title: What features should a 2D graphics library have?
I am making a 2D graphics library in Python designed to make 2D easy and fast. Internally it uses OpenGL. The library does cover a bit more then a graphics library, it also includes windowing and sound (and all necessary features to get working, like texture loading).

I've got a good beginning working with good performance, and I'd like to expand and refine my feature set.

Now I'm wondering, what features should a 2D graphics library have? After some brainstorming I made a little list:

* Fast sprite class for displaying rotated, scaled, colored and translated textures
* Sprite batching
* Drawing geometry: lines, polygons, circles, etc
* Alpha with blending modes on all of the above
* Easy texture loading (from file and memory)
* Texture regions (and texture atlases)
* Blitting texture(regions) into other textures
* Particle systems
* Off-screen rendering surfaces (FBO's?)

But I feel I have only scratched the surface of features. What am I missing?

One thing you must keep in mind that all of this in Python with C extensions. Any work in the library is fast, any work the user must do is relatively much slower. In addition to that Python calls are quite expensive, so the library largely benefits from batching.

(In case anyone cares, the library in question is pygrafix and can be found here: http://github.com/nightcracker/pygrafix)

# Answer
> 2 votes
For a 2d Graphics library, needs naturally vary according to application, but there are some things that I always find are "must haves".

I must be able to draw primitives. I must be able to draw images. I must be able to draw text.

Of course, if the library in question only did these three things, I'd be no better off with it than I am with just using OpenGL directly.

So, regarding primitives:

At the very least, I need pixels, lines, rectangles, ellipses, rounded rectangles, line based polygons, and filled versions of all of these, with the options of different pens and brushes and whatever else. Above all else, this needs to be easy to use. My requirements for easy to use are not stringent.

Regarding images:

I have the graphic formats that I like to use. Generally, this means PNG file, with alpha. If a 2d graphics library doesn't support this, I generally won't be interested. I must also be able to transform my images through color shading, rotating, scaling, flipping, and pretty much all of the other usual expected image manipulation.

What I DONT want is to think about textures. I want to think in terms of images and spritesheets and tilesets.

Regarding text:

I want to be able to draw text to the screen as easily as on other 2d libraries. I don't want to have to make some goofy grayscaled bitmapped font. I don't mind having to run a command line utility to convert a ttf into something else that the lib can use, but I'd prefer to deal with the ttf directly if I could.

Your library looks to be a "3d lib that can also be adapted for 2d use, provided the user is willing to think in 3d terms", which I would take a pass on.

You may wish to look at Slick2D as a model of a 2d lib that I regard as done correctly.

# Answer
> 0 votes
The ability for the user to set a "world window". By this I mean they supply a rectangle in world co-ordinates and you fit this to the viewport (display it to fit the entire window). By using this function, they can zoom and pan as they see fit. OpenGL has calls that you can pass this on to: `glOrtho(r.l, r.r, r.b, r.t, -1, 1);` By the way, the user specifies everything in world co-ordinates from now on.

You could also implement some utility routines to aid in collision detection: Nearness checks using bounding boxes or circles and a more expensive polygon intersection test.

---
Tags: 2d, graphics
---


# Question
Title: How do I avoid Race Conditions in UnrealScript?
I'm trying to create a pseudo turn based battle system in the Unreal Engine (think Final Fantasy style).

I'm trying to avoid the Enemies and the players attacking while another animation is in progress. I thought the most simple solution is to have a flag somewhere that the player controllers check before starting an animation, and set it to a value before they start, and then reset it when they've finished.

However, I could see this leading to race conditions if two controllers (AI or player) try to access the variable at the same time, then both start their animations.

If I was writing this in Java I'd obviously use synchronized methods, but I haven't come across anything like that in UnrealScript. Is there another way to avoid this? Its probably not the end of the world, as its a pretty unlikely occurance, but I'd like to try and avoid it completely if possible.

# Answer
> 5 votes
> obviously use synchronized methods, but I haven't come across anything like that in UnrealScript

Unreal script is only allowed and runs only in the main-thread, so there is no need to add synchronization objects to Unreal Script. In other words, two lines of script code can never access a variable at the same time from different threads, so no worries about race conditions in Unreal Script :)

---
Tags: udk, unreal
---


title: Design patterns for rules systems?

text:
# Question
Title: Design patterns for rules systems?
As a quick fun project, I tried writing a solitaire game. But when getting to writing up the rules systems, I felt *dirty*, because my code felt completely **unstructured and inextensible**, mainly because my game logic was complete spaghetti code.

I've run into this problem before, and always feel awkward when writing this part of my program, so I was wondering, **are there any tried and tested best practices when it comes to defining rules in a game**?

# Answer
I don't think there is a unique solution since a lot of cosiderations come from the particular problem.

You can use the Model View Controller pattern: this moves (confinate) your problem to "how to implement a behaviour on the controller", a beahaviour that always follows the rules.

Unless we are talking about very simple rules, the way you organize them poses a problem of *expressiveness*. You always face the conflicting demands of being simple (structured) and being expressive (write fun rules).

Using the MVC simplifies your job because the model formalize a *state* i.e. the *context* in which the rules are enforced.

Said that, you may find it useful to implement the Controller using the Strategy pattern and/or the State pattern in order to compose a complex behaviour in terms of simpler switchable behaviors. A Chain-of-resposibility pattern can help you to express rules while a State machine should be used carefully because its "state" partially overlaps the model's meaning of "state".

Using the Command pattern within the Controller may be usefull to both reduce Controller resposiblities (the Command know how to deal with the model) and make it easy to add the *undo/redo* functions in the Controller.

At any rate, you should try use the design patterns as guideline: they are useful to avoid to reinvent the wheel, especially the square wheel, but not every problem's solution consists of a bunch of (round) wheels put together.
> 2 votes

# Answer
I'm not sure about being best or even good but I usually use Observer pattern. It worked well enough for me.
> 2 votes

# Answer
Unless you've done the job many times before, you'll always end up with spaghetti code. Actually, at this point, you've only just started: what you have is the rough draft of a preliminary spec. Check out some of the other advice here and do some serious rewriting. And then some more rewriting, and then.... Personally, I'm never sure whether I get my code into really great shape or just get sick of rewriting it, but I do *seem* to get it right eventually.

Tackle the problem from two ends. Try to get the overall design to make sense *and* pick small parts that handle simple chores and make them right. Then try to work your way from both ends towards the middle. And then work from the middle back towards both ends. Then from the top down, then from the bottom up. Then repeat the whole process.

Essentially, what you have is a collection of classes. Consider class A. If class A is built well, its the classes that use it will automatically work better, however good or bad they are. If class A uses classes well, those used classes will do more, however good or bad *they* are. So organize your classes as best you can, then make sure each is the best class it can possibly be.

It is important to get it as right as you can. Bad code will haunt you until the day you throw it out. With software, a bit of extra polishing *always* pays off. (Unless no one ends up using the code....)

To sum up: check out the actual advice given in the other answers, then rewrite your code till you get something you like.
> 1 votes

---
Tags: design-patterns
---