# Question
Title: SRV from UAV on the same texture in directx
I'm programming gpgpu raymarching (volumetric raytracing) in directx11. I succesfully perform compute shader and save raymarched volume data to texture. Then i want to use same texture as SRV in normal graphic pipeline. But it doesnt work, texture is not visible.

Texture is ok, when i save it file it is what i expect. Texture rendering is ok too, when i render another SRV, it is ok. So problem is only in UAV-\>SRV. I also triple checked if pointers are ok. Please help, i'm getting mad about this.

Here is some code:

```
//before dispatch
D3D11_TEXTURE2D_DESC textureDesc;
ZeroMemory( &textureDesc, sizeof( textureDesc ) );
textureDesc.Width = xr;
textureDesc.Height = yr;
textureDesc.MipLevels = 1;
textureDesc.ArraySize = 1;
textureDesc.SampleDesc.Count = 1;
textureDesc.SampleDesc.Quality = 0;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.BindFlags = D3D11_BIND_UNORDERED_ACCESS | D3D11_BIND_SHADER_RESOURCE ;
textureDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
D3D->CreateTexture2D( &textureDesc, NULL, &pTexture );

D3D11_UNORDERED_ACCESS_VIEW_DESC viewDescUAV;
ZeroMemory( &viewDescUAV, sizeof( viewDescUAV ) );
viewDescUAV.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
viewDescUAV.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D;
viewDescUAV.Texture2D.MipSlice = 0;
D3DD->CreateUnorderedAccessView( pTexture, &viewDescUAV, &pTextureUAV );

//the getSRV function after dispatch.
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc ;
ZeroMemory( &srvDesc, sizeof( srvDesc ) );
srvDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = 1;
D3DD->CreateShaderResourceView( pTexture, &srvDesc, &pTextureSRV);

```

# Answer
> 7 votes
I solved this. Problem was in releasing. You can't access compute shader's resources until it is fully unbind and released.

**Edit** you dont have to release it at all. Only "unplug" UAV from from gpu.

```
//code is shortened
//create UAV
D3D->CreateTexture2D( &textureDesc, NULL, &pTexture );
D3DD->CreateUnorderedAccessView( pTexture, &viewDescUAV, &pTextureUAV );

D3DC->dispatch(...);

//pTextureUAV->release(); // You dont have to release (if you want to use UAV again)
outputTexH->SetUnorderedAccessView(NULL); // This is what is important

effpass->Apply(0,D3DC); // unbind compute shader

//create SRV on the texture, use it.

```

---
Tags: c++, directx, directx11
---


# Question
Title: How do I have to take into account the direction in which the camera is facing when creating a first person strafe (left/right) movement
This is the code I am currently using, and it works great, except for the strafe always causes the camera to move along the X axis which is not relative to the direction in which the camera is actually facing. As you can see currently only the x location is updated: \[delta * -1, 0, 0\]

How should I take into account the direction in which the camera is facing (I have the camera's target x,y,z) when creating a first person strafe (left/right) movement?

```
    case 'a':
        var eyeOriginal = g_eye;
        var targetOriginal = g_target;
        var viewEye = g_math.subVector(g_eye, g_target);
        var viewTarget = g_math.subVector(g_target, g_eye);
        viewEye = g_math.addVector([delta * -1, 0, 0], viewEye);
        viewTarget = g_math.addVector([delta * -1, 0, 0], viewTarget);
        g_eye = g_math.addVector(viewEye, targetOriginal);
        g_target = g_math.addVector(viewTarget, eyeOriginal);
        break;
    case 'd':
        var eyeOriginal = g_eye;
        var targetOriginal = g_target;
        var viewEye = g_math.subVector(g_eye, g_target);
        var viewTarget = g_math.subVector(g_target, g_eye);
        viewEye = g_math.addVector([delta, 0, 0], viewEye);
        viewTarget = g_math.addVector([delta, 0, 0], viewTarget);
        g_eye = g_math.addVector(viewEye, targetOriginal);
        g_target = g_math.addVector(viewTarget, eyeOriginal);
        break;

```

# Answer
> 6 votes
### Code quality first and foremost

That's a lot of duplicated code you've got going on there. If you've got duplicated code, you need to do it differently - duplicated code is dangerous (you'll change one side but forget to change the other and get logic errors).

* If you've got duplicated code down both ends of a conditional, take it out of the conditional.
* If you still need to only execute it conditionally (e.g. when the key is a or d) wrap it all in its own conditional.
* Consider helper methods.

### Now the answer

What you need is to get the Camera's rotation matrix: the exact direction it's pointing.

If the classes you're working with can return that from the camera itself, great! If it can't, you can calculate it based on the camera position and target - see here for one way to do that.

Once you have the camera's rotation matrix, you can just set up the movement vector then rotate it to point in the camera's direction using its rotation matrix.

The advantage of this approach is you can instantiate one general movement matrix, throw in all the vertical, horizontal and forward movement for your character in that update, do all the calculations you'd like on all of it then you do one rotation to face the camera and make that movement happen all at once.

I have no idea which language or framework you're using so I'm going to be using some C# and XNA here.

```
var keys = Keyboard.GetState();

if (MovementKeysPressed())
{
    var eyeOriginal = g_eye;
    var targetOriginal = g_target;
    var viewEye = g_math.subVector(g_eye, g_target);
    var viewTarget = g_math.subVector(g_target, g_eye);

    // The important camera rotation stuff happens here

    // Determine camera rotation. I am assuming that:
    // g_eye is the camera's location,
    // g_target is where it's looking,
    // and they are both Vector3s
    var up = [0, g_up[1]*-1, 0];
    var cameraRotationMatrix4 = g_math.matrix4.lookAt(g_eye, g_target, up);

    // The rotation component of a 4D transformation matrix is always
    // the upper-left 3x3
    var cameraRotation = g_math.getUpper3x3(cameraRotationMatrix4);

    // Right now we're only doing *direction* of movement - working with 1s only.
    // Speed comes after rotation.
    var xMovement = 0;
    if (keys.A.Down) xMovement -= 1;
    if (keys.D.Down) xMovement += 1;
    var movementVector = [xMovement, 0, 0];
    // Note that holding both A and D is possible and gets you nowhere.

    // Sets the vector's length to 1. You'll understand why this is important
    // after we introduce speed.
    var movementVector = g_math.normalize(movementVector);

    // rotate movement to face camera.
    var realMovementVector = g_math.rowMajor.mulVectorMatrix(movementVector, cameraRotation);

    // Now for speed.
    // We earlier normalized movementVector to give it a magnitude (length) of 1.
    // After we rotated it, it still only had magnitude of 1.
    // Any movement would always create only 1 unit of movement in any direction.
    // Let's say you want your character to move faster than that though!
    // What if you want your character to move at 4.2 units per update?
    // By multiplying it by a scalar (aka integer), we multiplied its magnitude,
    // which is now (1 x 4.2) = 4.2. It will now move 4.2 units either left or right
    // of the camera (unless the player has both 'a' and 'd' held down).
    var speed = 4.2;
    var speedThisStep = delta * speed;
    realMovementVector = g_math.mulVectorScalar(realMovementVector, speedThisStep);

    viewEye = g_math.addVector(realMovementVector, viewEye);
    viewTarget = g_math.addVector(realMovementVector, viewTarget);

    // End important camera stuff

    g_eye = g_math.addVector(viewEye, targetOriginal);
    g_target = g_math.addVector(viewTarget, eyeOriginal);
}

MovementKeysPressed = function() {
    // current state of the keyboard, stores for each key
    // whether it's pressed or not
    var keys = Keyboard.GetState();
    return (keys.A.State == KeyState.Down || keys.D.State == KeyState.Down);
}

```

Changes:

* Complete refactor
* Did camera-rotatey things in the code.
* Changed the first argument in the last two occurrences of `viewEye` and `viewTarget`

# Answer
> 1 votes
If you have the forward vector and the vector for straight "up", you can take the cross product to get a vector pointing sideways for strafing.

---
Tags: 3d, camera, first-person-shooter, matrix
---


# Question
Title: Morph a sphere to a cube and a cube to a sphere with GLSL
I'm getting started with GLSL with quartz composer. I have a patch with a particle system in which each particle is mapped into a sphere with a blend value. With `blend=0` particles are in random positions, `blend=1` particles are in the sphere. The code is here:

```
vec3 sphere(vec2 domain)
{
    vec3 range;
    range.x = radius * cos(domain.y) * sin(domain.x);
    range.y = radius * sin(domain.y) * sin(domain.x);
    range.z = radius * cos(domain.x);
    return range;
}

// in main:

vec2 p0 = gl_Vertex.xy * twopi;
vec3 normal = sphere(p0);;
vec3 r0 = radius * normal;
vec3 vertex = r0;

normal = normal * blend + gl_Normal * (1.0 - blend);
vertex = vertex * blend + gl_Vertex.xyz * (1.0 - blend);

```

I'd like the particle to be on a cube if `blend=0`

I've tried to find but I can't figure out some parametric equation for the cube. Maybe it is not the right way?

# Answer
**edit: source shader code tested, updated and works...**

**there is also video...**

Once you use a 3D coord instead 2D to sample cube, it is possible (but not parametric :)).

First theory:

Use normalize(GL\_Vertex - cubeOrigin) as sampling vector.

You have to know to which face of cube vertex belongs. It is the biggest componnent in sampling vector.

Once you have face, you can specify face normal. Than compute angle between face normal and sampling vector. Use Law of sines to get distance of point in space from cube origin(in middle). Multiply this distance with normal and you got it :)

```
// this code sucks for shader ... it would be slow it is written to be clear not optimal.

uniform int timer;

//return face's ID based on sampling vector
int face(vec3 coord)
{
    if((abs(coord.x) > abs(coord.y)) && (abs(coord.x) > abs(coord.z)))
    {
      if (coord.x > 0)
        return 0;
      else
        return 1;
    }
    if( abs(coord.y) > abs(coord.z))
    {
      if (coord.y > 0)
        return 2;
      else
        return 3;
    }
    if (coord.z > 0)
      return 4;
    return 5;
}

vec3 cube(vec3 position,vec3 cubeOrigin)
{
    int CUBE_SIZE = 2;
    vec3 coord = normalize(position - cubeOrigin);
    int face = face(coord);
    vec3 faceNormal = vec3(0);
    switch (face)
    {
      case 0: faceNormal = vec3(1,0,0); break;
      case 1: faceNormal = vec3(-1,0,0); break;
      case 2: faceNormal = vec3(0,1,0); break;
      case 3: faceNormal = vec3(0,-1,0); break;
      case 4: faceNormal = vec3(0,0,1); break;
      case 5: faceNormal = vec3(0,0,-1); break;
    }

    float gamma = acos (dot(faceNormal,coord));
    float alfa = 3.14 - 1.57 - gamma; //there is no PI or HALF_PI in glsl you have to define it on your own.
    //this is little hard stuff. You want to know length from origin to place on cube. It is simple triangle and can be solved by law of sines.
    //It should be multiplied with sin(HALF_PI) but it is 1.
    float posFactor =  (CUBE_SIZE/2.0)/sin(alfa) ;

    return (cubeOrigin + coord * posFactor);
}

void main(void)
{
    vec3 transformed = cube(gl_Vertex.xyz,vec3(0.0,0.0,0.0));
    vec4 cubetrans = vec4 (transformed,1.0);
    gl_Position     = mix(gl_ModelViewProjectionMatrix * cubetrans,gl_ModelViewProjectionMatrix * gl_Vertex,timer/200.0);

    gl_FrontColor = gl_Color;
}

```
> 11 votes

---
Tags: glsl, geometry
---


# Question
Title: Will we see a trend of stereoscopic 3D games coming up in the near future?
I've noticed that the trend of movies is diving into the world of movies with 3-dimensional camera.For me it provoked a thought as if it was the same feeling people got when they saw a colour movie for the first time, like in the transition from black and white to colour it is a whole new experience. For the first time we are experiencing the Z(depth) factor and I really mean when I said "experiencing".

So my question is or maybe if not a question, but Is there a possibility of a genre of 3d camera games upcoming?

# Answer
Short term, yes but for two different reasons.

1) The Nintendo 3DS is coming out soon with its set of 3D games. That platform has glasses-free hardware built in, and I'm sure the majority of those games are going to take advantage of it in some fashion (it may even be a cert requirement for the platform, I don't know).

2) At least in the living room space, the console makers (Sony specifically) are asking their teams to include 3D features in their games so they have something they can use to push 3D TVs. The hardware isn't there yet to make the investment worth it from an independent developer point of view, but people like Sony can use it as an excuse to improve their sales across the entirety of their product lineup.
> 5 votes

# Answer
3D with shutter glasses first appeared on the PC almost a decade ago. 3D cinemas (using polarised glasses) have been around for even longer, although primiarly at theme parks.

It didn't take off then, and little has changed since then, really.

Nobody wants to wear 3D glasses for their daily living room TV viewing, and it's not a whole lot more appealing for regular gaming.

But even if you don't mind the glasses, there's another perhaps more serious problem. On current platforms, stereoscopic 3D often offers a significantly worse experience than 'flat 3D', as rendering the scene for each eye usually results in a halving of the framerate.

I recently looked at Gran Turismo 5 on a 3D TV, it was not impressive. The framerate was all over the place, ruining the 3D effect. Switch off 3D mode and you've got a much nicer game, running at a lovely smooth 60fps.

I'm sure there'll be a lot more games released with 3D support in the near future, simply becaust the hardware support is now there. But it's likely to be more as a 'tick the box' extra feature, rather than a fundamental part of the game, and at the price of a severe drop in framerate and/or image quality.

The 3DS, on the other hand, is likely to be a big success. (Although Nintendo's only big hardware release failure was their last attempt at 3D, the Virtual Boy...). But I wouldn't be surprised if most gamers turn off the 3D effect after the novelty factor quickly wears off.
> 2 votes

# Answer
I certainly hope so. The current crop of glasses-bound 3D displays is too awkward for filmed entertainment, especially if you wish to watch it in company. I will not re-iterate the arguments here, but suffice to say I saw an ad yesterday that said "now with free second pair of 3D glasses".

However, this is not necessarily a problem for games. Gaming is an immersive activity, meaning that when you game that's the main focus of your attention, more-so than watching a film. Having to wear special glasses is less of a burden. Since the scene is especially rendered for your situation, a bit of basic head-tracking could solve the single biggest problem with current-gen 3D, the horrible parallax you see when you move your head even a little bit.

To summarize, I surely hope we get some good 3D games in the near future, because the current crop of 3D displays are worthless for all other endeavours.
> 1 votes

# Answer
Considering how little work is generally required to add 3D support to a game and that most earlier solutions for PCs had simple driver shims that added this on-the-fly for many games without even rewriting them, yes certainly - now that 3D movies have (re)started mainstream interest in the concept...
> 0 votes

---
Tags: game-industry
---


# Question
Title: Has an open console any chance to give more strength to the indie game world?
I have heard about the GPX, but i don't really think the embedded market is mature enough in terms of performance, but what about the home console market ?

I'm not talking about last-generation graphics, because that would be economically impossible, but what about an hardware as fast as a playstation 2/Xbox 1/Gamecube ?

For games, the trick would be to ask some editors to recompile their best sellers for the new machine: those games being from the PSX age or even older console generations, I think this would have a very low cost job and they could still make some good profit, but I need to know if this is doable technically, considering the architecture which can be quite exotic.

Do you think it would be a viable project to talk about to investors ?

# Answer
> 9 votes
A truly "open console" is an oxymoron. What consoles bring to the table, for developers and users, is a standardized platform - a fixed set of well-understood hardware and software. For developers this means less time testing and less worksforme bug reports. For users this means guaranteed compatibility and a base level of stability and quality.

What both parties give up to the platform owner for these benefits is control. For developers, they agree to be bound by approved APIs, and give up some revenue from the product. For users, they agree to only install licensed and supported software.

One could talk about "open consoles" in the 70s and 80s, when the difference in price and power between a "gaming computer" and a "real computer" was enormous. But today, it's not meaningful. *What defines a console platform is the lack of openness*, in exchange for those benefits. Right now we even have platforms running the gamut of tradeoffs - PC on one end, Wii/PS3/Xbox 360 retail on the other. On the more open platforms, like the Android, we can see the compatibility and user support problems of the PC emerging.

But the value of each platform in that continuum is based on how much or how little control it takes away from you in exchange for simplicity of development/use - and with so many platforms, consumers and developers finally have the ability to vote with their code and dollars as to how much openness they want. Just don't be too surprised if, for the mass market, it's less open than PC enthusiasts are used to.

There is another, wholly useless, way to think about "open consoles", and that's in terms of hardware fetishism. (And it's what I see from a lot of people interested in the GP2X/Pandora/etc., as well as PS3 and DS homebrew.) Playing around with novel low-level hardware is fun. But it's really a secondary characteristic of what defines a console, driven by the desire to drive down component costs and size and power consumption, and to increase platform lock-in, and unfettered by the need for Win32-on-x86 compatibility. If this is why you want to do "console development", you're probably better off getting an Arduino or something.

I really don't mean to disparage low-level programming. I personally enjoy it, *as a software developer*. But if that's what you mean by "open console", you're really romanticizing what consoles are, and ignoring the reality of why they're still around after two decades of high-spec low-cost general-purpose personal computing devices.

# Answer
> 4 votes
I strongly suspect that there's simply no market for it. (Except for a small number of geeks/developers that would be attracted to any new and open hardware)

There's plenty of devices out there that can play games very well, many of which are open, or 'open enough' for indies. We can already develop for a wide variety of computers, phones, and tablets.

Whilst consoles are much more limited, we do already have Xbox Indie Games (XNA), and there's active homebrew scenes for some of the older consoles such as the Dreamcast (and I wouldn't be surprised if we see a thriving PS3 homebrew scene soon?)

I suspect that in the future, we'll see a mainstream 'box under the TV', maybe a future iteration of something like Apple TV, that's not a traditional console, but is good at playing casual/less demanding games, and has an app store which is reasonably open to indie devlopers.

# Answer
> 1 votes
The home console market is more open to indie developers than at probably any other time in it's history.

You have downloadable games on PSN/XBLA for sub $2m budgets, and the XNA channel offering distribution for basically $100. On the PC side you have Facebook/Flash which is a platform offering distribution to millions of potential users with minimal cost, not to mention countless flash/unity web portals.

In the mobile space Android, WinPho7 and iOS offer options that are again at bargain entry price points compared to previous mobile options.

Why would you want/need a custom piece of hardware?

---
Tags: open-source, project-management, game-industry, platform
---


# Question
Title: Procedural terrains in 3D: what has been done ? Are there common algo and/or theories about it?
Besides programming, modeling an environment takes a great deal of time.

I don't know about the work time involved, for example, in a WoW dungeon level, or other beautiful city-like, future environment, jungles, fantasy, etc, but this kind of work is made from scratch by artists.

What are the techniques involved in the TorchLight level randomizer, and does other titles have similarities with this ? Is there a family name for such techniques ?

# Answer
Roguelikes have been doing this kind of thing since they were invented, and they are the "seed" Torchlight (and Diablo) got their ideas from.

I don't know about Torchlight's specifically, but in general, what you are looking for is called "Procedural Level Generation".

Fuel procedurally generates a zone so bast that it would not fit on the DVD the game comes in. I particularly enjoyed reading Shamus Young's series on it.

Another interesting example of procedurally generated content is Introversion's not-yet-release game, called Subversion. Have a look at Part 12 on that page; it's specially juicy.

Speaking about procedurally generated cities, there's also some middleware around - check out http://www.procedural.com/.

For more games/middleware, check out the Procedural Generation Wikipedia page and the Procedural Generation Wiki.
> 8 votes

# Answer
(Cited Links in pastebin link: http://pastebin.com/PpJknMuT )

Well you could say that there are 2 different kinds. It depends what you want. For example if we take a recent GTA game, 100's of artists were used to make the city and to personalise it. Procedural generation could be used here, but it would be used as an artists tool rather than something running on the game engine as we don't particularly want a different city layout with each game.

So my undergraduate dissertation was on procedural city generation with city zoning: \[1\]

This tool is used by the artist to create a city whilst allowing control over different aspects if they require it. The city generation is similar to L-systems as seen by Pascal Mueller's work: \[2\] The city zoning works as an image map taking probabilities of zones (commercial, residential, industrial) from the pixel rgb data. It would be possible to automate the generation if you wanted to, but to make cities look believable the algorithm would have to be far more complex using population AI mechanics rather than L-System and noise algorithms.

On the fly generation can be seen in \[3\] or I guess the simplest example would be helicopter: \[4\]

Something similar to Torchlight would be Infinity: Quest for Earth \[5\]

In Infinity, the galaxy and everything within it is generated with a seed value that then creates all the other variables used to generate everything contained in the galaxy (planets, suns etc) The link talks about how this works in greater detail.
> 2 votes

# Answer
Minecraft uses 2D Perlin noise to generate outdoor terrain. It can have practically infinite levels (you'd die of old age before you got to the edge) that are generated as players explore. It (probably) also uses 3D Perlin noise to generate underground caves.
> 1 votes

# Answer
> What are the techniques involved in the TorchLight level randomizer.

They will just be random numbers that get put into there level algorithms.

> and does other titles have similarities with this ?

Wikipedia.

Although debatable Left 4 Dead used similar techniques in there AI Director.

> Is there a family name for such techniques ?

Fractals, Recursions, L-systems and plain old algorithms. Each combined with random numbers.
> -1 votes

---
Tags: procedural-generation, level-design, ogre, random
---


# Question
Title: Where to start, to develop an online Backgammon game?
I would like to develop a backgammon game to play against other players online, as a way of learning more Javascript/jQuery and a little game development. I'm a web developer and most of my experience is in PHP. I have minimal Javascript experience and no game development experience. Where should I start? Are there any particular books, tutorials, libraries, or frameworks that would help give me a jumpstart? As a beginner, am I better of using the DOM or Canvas?

# Answer
I think it depends on how you're planning to render your graphics. Do you want to include animations? A playing board with a pseudo-3d-view?

A top-down view is probably easiest and could be done using DOM and/or Canvas. Since DOM is supported in all major Browsers and jQuery offers a nice toolset (including animations) for DOM manipulation, I'd probably pick DOM over Canvas.

Since this is a multiplayer game, you'll have to think about where to put the game logic. The best approach (which also prevents cheating) would be to keep all the game-logic on the server-side (programmed in PHP) and only have rendering logic and user-input in the clients.

I don't know about any PHP framework that has a focus on game-development. I'd probably pick a multi-purpose framework like Zend, Cake, Sapphire or Symfony. This will let you focus on the implementation of the game-logic while it will already provide tools for data-persistence or handling of AJAX-request (which you'll probably use for communication).
> 2 votes

# Answer
Since your goal is to experiment with Javascript, I suggest you to take a look on Node.js for the server side. It's well suited for what you're trying to do because you can build a realtime server through websocket quite easily and stay DRY. Your backgammon logic will be wrote only one time and shared both client and server side (for anti-cheating / game rules validation)

Search for chess games build on these technology.
> 5 votes

# Answer
With the caveats that I have no direct experience with them and their web site login/logout is a bit wonky, I've heard good things about gamesbyemail.com's developer program. They provide a downloadable tutorial for building games within their framework.
> 1 votes

---
Tags: web, javascript, html5, html-canvas
---


# Question
Title: How should I show shared resources during a Shared Resource game in the Galaxy Editor?
One of my favorite ways to play the original StarCraft was in a "Team" game. In this game type, multiple players on the same "team" would *share* control, resources, supply, and even the same starting location. It was like playing as 1 player, only 2 humans were controlling it. It was a lot of fun.

I want to do something very similar in StarCraft 2, but I need to create a custom map in the Galaxy Editor to do it.

I found the editor can quite easily emulate this behavior. There is a Trigger action "Set Alliance for Player Group" to "...treat each other as **Ally With Shared Vision, Control, And Spending**." To use this, I create units for only 1 of the players, and then set all players to be allied with each other in this way. All the other players get no units and no resources. This makes it so 1 player is the actual owner of all the units and everyone else is tagging along with full control.

This nearly works! The problem is that if I am not the actual owning player, I can't actually *see* how many minerals/gas/supply the team has. This makes it pretty difficult to build stuff.

What would be the best way to display to the other players how many Minerals/Gas/Supply the team has?

# Answer
Meanwhile, I figured it out! As @Wikwocket says, custom Dialogs are the way to go; however, here's a very detailed explanation of precisely how I did it.

First off, for convenience I made a new **Record** in the Trigger Editor I called ResourceDialogUI.

I also had to make a variable of type "**\- Record / ResourceDialogUI**," which I cleverly also called ResourceDialogUI.

I then painstakingly recreated the positions and sizes of the ingame Resources UI to make a UI that looks almost, but not quite, entirely like the defaults. Also I turned off the defaults. I hope these numbers are useful to someone else too.

*Edit: dialogSizeX might need to be a little bigger and dialogRightBuffer correspondingly larger to account for supply sizes in the triple digits; otherwise you get ... truncation.*

Then it's just a matter of updating the numbers at appropriate times using **ResourceDialogUI.MineralsText** etc. and the "Player Property" getter function to get the values. To update, I simply used a Trigger that fires every .5 seconds, and it works *pretty* well. It's not as nice as the default text, which "rolls" around to the real numbers, but I'm sure I could polish that.

Also of note: Supply is "SuppliesUsed / SuppliesMade." That took me a couple tries. I was *not* able to get the color to update to red when you need more supplies; the trigger to set the text color on the fly didn't seem to actually do anything.

My map lets you join other teams on the fly, so I also added in a Trigger to change the icons to appropriate race-specific icons. Using a local variable "race" which is a "Game Link -\> Race," here's what does that:
> 4 votes

# Answer
I would think you could add a panel near the upper-right of the screen showing your team's resources/supply. A lot of custom maps have little info panels all over the screen so I'm sure this is possible. The only trick would be getting it to show just your team's stats, not those of both teams.

You may want to ask this at gamedev.stackexchange.com as well; custom map building is kind of a game development topic, and policy questions like "how should I show X to the player" are also within their scope.
> 2 votes

---
Tags: starcraft-2
---


title: Xaudio2 XAPO Effects

text:
# Question
Title: Xaudio2 XAPO Effects
I've been working with XAudio2. After looking at the samples, example code, and sparse documentation available from Microsoft and the MSDN, I've found that there aren't any easy-to-find resources on creating and using XAPO effects, nor any XAPO effects produced by third parties that I can download and/or buy.

What it looks like is that if I create an app that uses XAPO effects, I'll have to create them all myself because there's no community of existing applications like there is with technologies like Apple's AU or Steinberg's VST. Is this true, or are there others using XAudio2 and XAPO and I just haven't found them?

Is there a place to ask programmer-support-related questions about XAudio2 and related technologies (or is this the best destination)? The best I've found so far are the XNA forums, which are game-specific and sparsely populated in the audio area.

# Answer
XAPO is a rather new technology and as such not widely supported (yet). So, yes, you have to create most of your effects yourself, however it shouldn’t be too hard to port/convert the older DirectSound SFX’ (I forgot the name of that technology and if it even was related to DirectSound…).

The AppBuh DirectX \> Audio/XACT forum and the DirectX mailing list seems to be the places to ask questions about XAudio2, even though both are rather low frequency but will get you “access” to the devs of it :)
> 1 votes

---
Tags: xna, audio
---


title: UDK or Blender?

text:
# Question
Title: UDK or Blender?
I am new to UDK and Blender but I've some prior game development experience on XNA. Now I want to know should I start using Blender gaming engine which is open source and gives lot of freedom to programmer or UDK which is awesome tool to create 3D games but it is very specific and bounds you to use Unreal script. Which one should I start?

# Answer
> 5 votes
Blender Game Engine is very unproven. I've seen very few games released using it, and all of those that I have played felt a bit dodgy (subjective term, sorry). UDK, on the other hand, is totally proven; there are a bunch of games, especially student games out there, that use it. They have varying degrees of success (generally, FPSes are the easiest sort of games to make in the engine), but there's gonna be more resources and mentors out there.

Does that mean you can't trailblaze and make a great game in Blender? Of course you can. Its just a higher-risk choice.

An alternative if you like Blender and want free coding in multiple languages is Unity. Unity will work seamlessly with Blender models, and it's much more proven than the Blender Game Engine.

# Answer
> 4 votes
Either is fine, but Blender has some very interesting advantages:

1. It contains both the modeling tool and the game engine. You don't need another tool for creating the models. Use the same tool for both.
2. The game engine uses a tile-based system. When you start with the game engine, you can use a tile-based drag-and-drop system to get your game working. You can get a pretty sophisticated game working (drive a vehicle around - shoot bad guys, take damage, scorekeeping) without writing a single line of traditional code.
3. When you're ready for 'real' programming, Python is built in. Python is becoming a very popular language for game development because it's pretty sensible. It's already built into Blender (much of the blender UI is built with it.)
4. True multiplatform. A game you've built with the game engine can be exported to an executable in the local OS.

The down side is the documentation, which basically stinks. I've got a series of videos (actually, it's one of my classes) which goes through blender and the game engine pretty thoroughly. Check it out at http://synapse.cs.iupui.edu/Mediasite/Catalog/Front.aspx?cid=5d511316-3092-446e-9a69-79d35c41b62d

The blender stuff starts at lecture 17, and the game engine stuff begins at lecture 27.

# Answer
> 2 votes
I would say Cube 2.

You know, you limited yourself too much, there are plenty of good options out there, Unity is cool, UDK, Source SDK (if you don't want to buy a source game, get Alien Swarm), Torque 3D is popular (although in my opinion it suck...), and so on...

Also there are some scenegraph stuff if you are willing to learn C++, like Horde3D (really great, REALLY great...), Ogre3D (really bloated... but good, and popular), Irrlicht (lighter than Ogre3D, more flexible than Horde3D, but the age and clutter shows...), and so on...

Your two options are limited in my opinion. I would say to you use Cube 2, it has a good scripting language (the original author of the engine is a professional langauge designer, that designed Far Cry 1 language, among other stuff), and it is open source too if you want to hack it to do more custom stuff.

# Answer
> 1 votes
If you do want to check out Blender then these links may help:

Blenderartists finished games forum: http://blenderartists.org/forum/forumdisplay.php?f=39 Blenderartists game resources forum: http://blenderartists.org/forum/forumdisplay.php?f=36

Beginners thread: http://blenderartists.org/forum/showthread.php?t=196825

Tutorial list thread: http://blenderartists.org/forum/showthread.php?t=11430

Project Apricot open game: http://www.yofrankie.org/

Personally I would wait for the next upgrade to the game engine in blender. Work seems to have been done integrating the BGE with Ogre: http://blenderartists.org/forum/showthread.php?t=155310&page=29

As stated by others Unity is nice to use, and although Blender has python scripting I am unsure how stable the scripting api is for the BGE whilst Unity can use javascript which is very easy to pickup.

BGE = Blender game engine

# Answer
> 0 votes
Blender is not game engine by it's purposes. But it consists of some game engine modules. I think Blender is better for creating Cg stuff;) So if for me I'll choose UDK;)

# Answer
> 0 votes
UDK is far ahead of the others.

* best support and forums
* ready to play out of the box for FPS's
* excellent graphics and physics built in
* fairly easy to learn
* free (kind of)

---
Tags: blender, udk
---


title: blender: 3D model from guide images

text:
# Question
Title: blender: 3D model from guide images
In a effort to learn the blender interface, which is confusing to say the least, I've chosen to model a model from referrence pictures easily found on the web.

Problem is that I can't ( and won't ) get perfect "right", "front" and "top" pictures. Blender only allows you to see the background pictures when in ortographic mode and only from right|front|top, which doesn't help me.

How to I proceed to model from non-perfect guide images?

# Answer
My first (successful) Blender modeling-from-reference-images experience came from the fantastically useful Blender Noob-to-Pro wiki. The fox modeling exercise not only supplies the images for you, but gave me some ideas about how I could combine household items and my phone's camera to produce my own reference images - since I'm not patient enough right now to learn how to sketch my own...

Honestly, going through most of that wiki got me to the point where I was able to make sense of almost all of the other tutorials I could find Googling.
> 6 votes

# Answer
You can also get left, back, bottom views. Try holding shift when using the keypad to activate those views. I would also suggest editing the images in photoshop or something similar first.

The blender noob to pro wiki is a bit out of date. Its not using the most recent Blender version (2.55) and as the interface is completely different, this could be confusing.

Try going to http://www.blenderatists.org/forum or irc freenode #blender for help
> 2 votes

---
Tags: models, blender
---


# Question
Title: Do you fill all your game data in huge excel tables? Are there any better method?
I really want to know how many game designers prefer to work with a huge table for all items, another table for all skills, and even another table for all mobs in a MMORPG. And these tables may grow to several hundred MBs with thousand records, but most records only use a few fields in a table.
I know some game designer works in this way. Are there any better method?

# Answer
> 4 votes
I didn't want to answer here, but when i saw another answer/comments i changed mind. SQL is not very good solution of this. SQL defines tables and inserts lots of data into that tables. This is not that case. When creating/testing game design you are mostly want to check if the huge system is balanced. That means lots of tables which affect each other. Nothing good for SQL actualy - or it is, but not easy to handle, bacause you have to do programming which is not necessary. And game designer doesn't have to know it.

As game programmers/developers we can disdain excel and its usage for anything, but it is pretty good tool for this case, especialy when game designer can use it well and the document is well created.

I cant recommend any other tool, but i can say that i know professional game designers who use excel too. So i assume it is common tool.

# Answer
> 3 votes
I agree with most answerers that sometimes spreadsheets can make decent dev tools, especially for designers.

If you are interested in taking this approach further, the Resolver One spreadsheet program uses python for scripting, making it easy to set up a spreadsheet for designers that both does complex modelling and exporting to a game-friendly data format. I find it much easier to work with than Excel's VBScript.

# Answer
> 2 votes
Excel is an excellent solution.I had been wondering how this should be done. But thinking about it, Excel is while a very popular tool and quite adequate for this duty, I would not recommend this practice. Additionally, actual database, as @notabene suggests, brings a **lot** of extra overhead that you really don't need. I see a couple of options, one of which is akin to using Excel:

* Open Office Calc: free. There is also a MySql connector download (open source I believe) for Calc.
* serialized data: either XML or binary (encrypted)

...either way, free and you have complete control.

I personally would be inclined to go with binary serialized *and encrypted* data. Two reasons:

* game data cannot be easily tampered with
* I can work with datatables rather than Xml serialization of datasets, i.e. **I** have the option.

Is there a need for a dedicated, true game-oriented *data library*? Maybe...unless someone knows of such a library already in existence.

To the point of the OP's question, look at each *page* *csv file* as a single data table - akin to a table in a database. Each page file should contain related data:

* Skills, or
* Gear, or
* NPC stats

This helps you keep a high level of organization which will be very important as data content grows, game content expands, etc.

**Edit**
After actually attempting to use .ODS (OpenOffice Calc file) and connecting from an application, it is actually *not* possible as initial posts on OO site implied. I could not find anything specifically showing *teh codez* on implementation.

Also, using Excel files might be *okay* while developing a game so data can be tweaked without overhead from a database. However, and this is important, if you plan on doing this, you must have MS Office installed so you can reference Microsoft Excel Interop COM. This may be beneficial at first, but I wouldn't want to remove or change a bunch of code to get an application ready for Alpha, Beta, or RC. A very simplified library would take more effort than I could see being useful.

I am going to use .CSV files for early stage data storage. There are some drawbacks, but overall I feel this is a much better option. Everything is contained within my libraries. .Net has very useful classes for reading these text files. Also, as .CSV files, the data is easily manipulated; and, for later stages of development, all I need to do is have my data files serialized to XML, then later to serialized encrypted binary.

# Answer
> 1 votes
So long as the nature of your data permits it to be stored in a spreadsheet without jumping through too many hoops it makes a very good format, especially for development work. In the end you may want to store it in other formats for use but the spreadsheet gives you a very powerful editor which can be *VERY* nice if you decide to change how you handle something!

If you're using Excel go get a copy of ASAP utilities--it makes the spreadsheet into an even better editor.

# Answer
> -2 votes
Well, for me, I thing speartesheet programs can't handle such stuff correctly and effectively. RDB was design, actually, to handle huge data and tables. Modern RDB were designed to handle the 'Huge' kind of things and they are doing it very good.

The point is, to get the best output of the RDB you need to design your database in the correct way. If your data schema was poor, or did not cover all the data of your project, you will end with a very bad results, performance, and output.

The idea of RDB is to break down huge table into smaller ones so that you can improve performance and readability. If you have a very huge table (attributes wise or even records wise) or a lot of repartitions, and you don't use most of them, that means your design of the DB has some errors.

In your question Huang F. Lei, if I were asked to design a MMORPG database, I will not add all the skills in one table and all mobs in one table. I will divide the skills according to their classes and usage into multi tables. Each skill type will have its own table or even tables. For mobs, I will either divide them according to their types, or according to their location in different worlds. And so on.

This way I can shrink the table sizes, make it easier for me to track the data, and improve the DB performance.

In Excel, on the other hand, all the data will be 'crumbed' in one place. and to find one piece of data is almost impassable, epically when you have a repeated data. In addition, as the data grow in size, the opening time of the file will increase.

At the end, Excel - in my opinion - is a very poor way to handle huge related data.

---
Tags: game-design, tools, mmo, data
---


# Question
Title: 2D Ragdoll - should it collide with itself?
I'm working on a ragdoll fighting game as a hobby project, but I have one dilemma. I am not sure if my ragdoll should collide with itself or not, i.e. if ragdoll's body parts should collide.

2D world is somewhat different than 3D, because there are several layers of stuff implied (for example in Super Mario you jump through a platform above you while going up).

The setup I'm currently most satisfied with is when only the parts which are joined by a joint don't collide, so head doesn't collide with neck, neck with chest, chest with upper arm etc, but the head can collide with chest, arms, legs.

I've tried every different way, but I'm not content with either. Which way would recommend me to go?

# Answer
It depends on the style of game and the "perspective" you're going for, really. For the sake of argument I'm assuming your game is a pure side view instead of top down or faked perspective (think castle crashers or final fight).

Generally I would think you wouldn't want anything to collide. In a pure 2d game you aren't really going to be able to pull off what you might need self collision for anyway, like the body landing on it's side, or legs getting twisted up. Now you could do that with a 3G game played in 2d, but I'm guessing that's not the point.
> 2 votes

# Answer
I'm not an expert when it comes to ragdolls but when I think "2D fighting game" I imagine seeing the fighters from the side.

So colliding legs won't work or the poor guys/gals won't even be able to walk. Also the arms shouldn't collide with the torso (because of the side-view). The limbs should collide with the head though, so that if a player has raised his arms in defense and gets hit, the arms will hit the head.

It probably helps to think in layers. The arms are on another layer than the legs or the torso and therefore don't collide. You wouldn't want the arms to be affected by a kick.

I'd probably setup the collision group as follows:

* Head collides with everything.
* Arms collide with head.
* Legs collide with torso and head

It's probably best to reduce the amount of possible collisions within a ragdoll to a minimum and just work with joint constraints. And of course playerA collides with playerB.
> 1 votes

# Answer
Again - the perspective, PoV, matters. But I imagine a fighting game just like Tekken or Street Fighter.

In that case - there probably should be some layers, from front to the back.

Front layer would (for example) have right arm of the fighting figure, as well as the whole right leg. Assuming he is facing an opponent to the right of him on the screen. Middle layer would be head and torso, and finally the layer furthest from the camera would contain the rest.

The layers would not collide with each other - otherwise the figure would not be able to walk.

---

But this makes me think - there is no point for collision detection at this point. Player would most likely be in a standard boxing pose, which means that the wrist should not collide with the shoulder - it would be hard to make an arm bend otherwise.

This can be fixed by splitting both the wrist and the shoulder into two sub-parts, which would not collide at the elbow joint. It would also enable stuff like breaking arms possible, but this is quite a lot of work.

For the legs - the same, because they wouldn't bend normally otherwise.

---

The final answer IMO is ***no***, but IF you want to invest some more time into stuff like fractures and realism, yes.
> 0 votes

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


# Question
Title: How to load a mesh from the .X-format in DirectX10 via SlimDX?
As of DirectX10, the usual functions to load a mesh in the .X-format are marked as deprecated and they are DX9 functions anyway. How can I load a mesh from the .X-format into an `ID3DX10Mesh` object using the SlimDX wrapper?

# Answer
There's a "SimpleModel10" sample in the samples distribution for SlimDX -- it is essentially the same code as in the ScapeCode post. In fact, it was written by the same developer.
> 1 votes

---
Tags: c#, 3d-meshes, directx, directx10, slimdx
---


# Question
Title: How to separate production and test assets during development?
this is like a complement for Assets Management, database or versioning system?.

I am wondering about how to separate development, specially programmers assets from production assets?

For example, if we keep all the assets on the same repository, how do you keep with programmers assets and final game assets? Do you keep a separate directory for each of those, allowing duplicates? Or do you use some fancy scheme for striping out the "development" and "test" assets from final build?

# Answer
> 5 votes
At my last job we prefaced everything that was development-only with \_, and the support for that convention ran into the lowest levels of our filesystem handling code in the game, like directory listing and our file opening wrappers. Test and development-only assets were just checked into the same RCS repository as the real game data.

So for example,

```
# This is always loaded
data/texture_library/titlescreen.tex
data/spells/magicmissile.spell

# These are only loaded in development mode.
data/texture_library/_foo.tex
data/spells/_testmissile.spell
data/spells/_testing/fireball.spell

```

It's a very simple convention, but was easy to use with other tools (grep, one-off Perl scripts, etc.), and straightforward for everyone on the project to understand.

# Answer
> 2 votes
We tend to keep all of our test assets in a 'test' folder which get stripped out when making final releases of our games. These folders can be broken down by person (which is what we do) or perhaps asset type, or both. Once benefit that we've gotten is that we can use perforce exclusionary mappings to allow people to remove folders (inside of 'test') that they don't want to look at.

To do this method right though, does requires some planning and adherence to the scheme on the part of the development team. This type (or any type) of organization can be hard as you scale up the number of members on your team. I guess the advice here is that no matter what scheme you pick, make sure that your team members follow it, otherwise, it will break down in ways that can be pretty irritating. For example, the scheme that involves prefacing files with an underscore sounds workable. But in practice, it also seems easy for someone to forget this convention (either way) and then you wind up with missing or extra assets (the latter typically being less of a problem). Again, these problems can happen with any scheme, so it's worthwhile to have it documented and drilled into your team's collective head.

# Answer
> 1 votes
If i understand well. In my team we use SVN. If you didn't know, you can also create branches in SVN. So it is simple. We create branch for every release we do. Then we have releases untouched and marked in same system we are using.

# Answer
> 1 votes
I like to take an approach where content is organized into 'packages' with the content root, and packages can be scheduled into the production build (in order) via some kind of manifest.

The simplest implementation of this technique is a flat-file one, where you have an asset directory which subdirectories for each package. Each package subdirectory contains assets, possibly in a fixed tree form (such as all the models in a 'model' folder).

The manifest simply contains an ordered list of packages to apply to a build -- packages applied later override those applied earlier. The manifest for dev builds includes the packages for developer-only stuff, and the manifest for live builds doesn't.

Obviously you can scale this out to an arbitrary complexity, supporting things like efficient fallbacks for missing resources if you forget to schedule in a package, or emitting warnings, et cetera. The system lends itself well a local 'override' directory, too, allowing for quick asset iteration.

This approach is orthogonal to the SCM package used, so you don't necessarily need a branch per package or anything like that.

---
Tags: assets, testing, management
---


title: What is the "MSN Game API"?

text:
# Question
Title: What is the "MSN Game API"?
The other day I herd this "MSN Game API" mentioned, but I can not find any information about it anywhere. This particular API seems to be for browser based games (Such as Flash, and ActiveX embedded games).

What exactly is this API for? And is that its correct name? is it to do with the MSN Zone? Where can I find more information about it, and maybe even some documentation on the actual API.

# Answer
The API in question is, I believe, the MSN Games GDK for developing games for the MSN Games portal (or Live Messenger). The SDK itself is not readily available to the public; I believe you need to contact developer support to get it. Check out this page at the MS Casual Games portal.
> 2 votes

---
Tags: microsoft
---


# Question
Title: OpenGL ES Basic Fragment Shader help with transparency
I have just spent my first half hour playing with the shader language.

I have modified the basic program I have which renders the texture, to allow me to colour the texture.

```
varying vec2 texCoord;
uniform sampler2D texSampler;

/* Given the texture coordinates, our pixel shader grabs the corresponding
 * color from the texture.
 */
void main() {
  //gl_FragColor = texture2D(texSampler, texCoord);
    gl_FragColor = vec4(0,1,0,1)*vec4(texture2D(texSampler,texCoord).xyz,1);
}

```

I have noticed how this affects my transparent textures, and I believe I am loosing the alpha channel which would explain why previously transparent area's appear totally black.

If I use the following line instead, I am shown the transparent area's

```
gl_FragColor = vec4(0,1,0,1)*vec4(texture2D(texSampler,texCoord).aaa,1);

```

How can I retain the transparency after this modification to the colour?

I have seen various things about a .w property, and also luminous, but my tweaks with those and the .aaa property are not working XD

# Answer
You seem to be throwing away the alpha channel each time you try and play with multiplying the colour part of the texture. You should be able to get to it through either "a" or "w" and then copy it through unchanged.

```
gl_FragColor = vec4(0,1,0,1)*vec4(texture2D(texSampler,texCoord).xyz,texture2D(texSampler,texCoord).w);

```

(While I'm guessing this should work, it's been a while since I've played with shader stuff)
> 2 votes

---
Tags: opengl, shaders
---


# Question
Title: Common way of animating 'motion' for walk cycle animations
I've just posted this at the Blender artists' forums before realising I would probably get a better response from a more game development-specific audience, so apologies for cross-posting! It's for the right reasons :)

I'm a programmer trying to animate a character walking for a game project, using Ogre. I've made a very simple walk cycle in Blender and exported it to Ogre, and it plays just fine. By fine, I mean it works, but there's terrible foot sliding. This is because I just animated the walk in-place (at the origin) in Blender, and of course I don't know what "speed of walk" that corresponds to, so when I move the character in-game the motion doesn't necessarily match up with the movement of the feet in the animation.

So my question is: what's the normal approach for this kind of thing? At work we use Maya, and the animators either animate a special 'moveTrans' node that represents the "position" of the character (or have the exporter generate it for them from the movement of the root node), then the game can read this to know how fast the animation moves the character. So in the Maya file, the character will walk forward for one cycle and this extra node will follow along with them by their feet. I've not seen anything like this in open-source land, and there's certainly no provision for that in the Ogre Exporter script. What do you chaps normally do for this?

# Answer
There are two ways of doing it: root motion or "in code".

With root motion you have basically exactly what you're suggesting with the "moveTrans" node. You use the motion of that object to determine how quickly to play back the walk cycles. You might be able to do a reverse lookup of sorts to figure out that if you want to be at position X what frame you need to be at. But the real advantage of root motion is that to get truly realistic animations you need to account for the fact that movement isn't a true linear path. Real people move at a variable speed over time, or maybe they're shuffling left and right a bit, or whatever.

Mixamo did a good example with root motion control using Unity. There's a video of it here: http://vimeo.com/12052874

Now root motion does have its drawbacks. It can get tricky with things like trying to get the "walk" animation to work on stairs (ideally you'd have a separate stair/ladder climbing anim and do all the movement for that in the animation as well). I'm also not really sure how IK really plays into it, if at all.

Now doing it "in code" is a lot easier from the programming side of things. What I suggest doing is first making sure all your units are consistent. For example, 1 unit in Maya and your game is 1 meter. Then you get your artists to animate a character walking (complete with forward movement). Use that to figure out the speed of the animation, and export the animation without the forward velocity. Use that to figure out how fast to play back the animation. So if the walk animation at 1x speed is 5 m/s, and you want to have the player run at 7 m/s, you simply play back at 7/5 = 1.4x speed. If your model is scaled up or down multiply the animation playback rate by the inverse of the scale. A half height dude will have to walk twice as fast to move the same rate as a 1x scale guy.
> 10 votes

---
Tags: animation
---


# Question
Title: What is "Rapid" in reference to the MSN Games GDK?
I have herd a little talk about the MSN Games GDK lately, and what wondering what **Rapid** was.

It sounds like some sort of testing environment, is this true? How can I get access to it? Or find out more about it?

# Answer
From some old (2006/2007) presentation on MSN Games...

RAPID!

* Integration Test Tool
* Allows developers to test that the MSN API is correctly implemented
* It does not:
    + Verify client requirements
    + Doesn't test the game play

Links to the main site is here MSN Games and the developer resources are here

To get access to the developer libs you'll need to submit a concept, have it approved and then take it from there. (I've not actually done any of this so can't advise you on the process itself).
> 3 votes

---
Tags: microsoft
---


title: OpenGL ES Shader help (Blending)

text:
# Question
Title: OpenGL ES Shader help (Blending)
Earlier I required assistance getting to grips with how to retain the alpha channel of a transparent texture in my colourised texture shader program.

Whilst playing with that first version of my program (before obtaining the solution to my first requirement), I managed to enable transparency for the whole texture (effectively blending via GLSL), and I quite liked this, and I would now like to know if and how it is possible to retain this blending effect, on top of the existing output without affecting the original alpha channel - as I don't know how to input this transparency via the parameter that is already being provided with the textures alpha channel.

A basic example of the blending program I am referring to (minus any other functionality) is as follows...

```
varying vec2 texCoord;
uniform sampler2D texSampler;

void main() {
    gl_FragColor = vec4(texture2D(texSampler,texCoord).xyz,0.5);
}

```

Where 0.5 is the transparency (blending effect) of the whole texture.

This is the current version of my program, which provides the ability to colour a texture according the colour parameter passed to the program, and retains the alpha channel of the original texture.

```
varying vec2 texCoord;
uniform sampler2D texSampler;
uniform vec3 colour;

void main() {
    gl_FragColor = vec4(colour,1)
    * vec4(texture2D(texSampler,texCoord).xyz,texture2D(texSampler,texCoord).w);
}

```

I need to know if it is possible to apply transparency on top this program, without affecting the original alpha channel which I have already preserved.

I hope this makes enough sense, I am sure it is possible, and if so I should imagine it is rather simple, but this has me stumped. Any help much appreachiated.

Cheers, Chris

# Answer
> 2 votes
Are you just trying to scale the value of the alpha coming out of the texture? If so you can just supply a floating point value between 0 and 1 as a scaling value in the part "vec4(colour,1)" instead of the 1.

---
Tags: shaders, opengl-es, transparency, blending
---


# Question
Title: Typical Method Of Building Puzzle Levels
I am designing a puzzle game for the iphone and was wondering as most puzzle games consist of the player progressing through multiple levels. You see for example Angry Birds has over 100 levels.

Once the basis of the game is made, how do developers typically go about building their levels?

Do they generally build them from scratch each one more or less, or work of their own template or have some other method which they use to tailor these levels?

I imagine building so many levels is a long process, certainly if building each one individually. Do they do this, or have a method which speeds it up once they have their basis?

# Answer
For the Pirate Poppers puzzle mode, I generated the levels randomly based on some parameters related to difficulty.

Difficulty is always difficult to measure objectively, but in this case there were some variables that were good indicators (chain length, number of different colors, nesting level of the combos) so I was able to generate pretty good puzzles quickly, with a sensible difficulty progression.

I did manually test every one of them afterwards to make sure they were winnable (some of them weren't, right after generation, due to other variables not included in the generator, such as chain position and path shape), tweaked some of them and re-generated others that were too difficult.

The first levels were hand made, though, to make sure they were simple enough and worked as a tutorial of sorts.

In summary, you can batch-generate tons of levels and manually pick and tweak the subset you finally include in the game.
> 6 votes

---
Tags: iphone, level-design, cocos2d-iphone, levels, puzzle
---


# Question
Title: IDE & Debugging of Official SDK for wii and ps3?
I remember hearing that wii and the ds uses CodeWarrior as their IDE. I know xbox uses visual studios but i have no idea what ps3 uses.

What IDE do ps3 developers use and how do they debug? How do wii programmers debug? I always heard they use GDB but is that built into CodeWarrior or is that a separate application?

# Answer
> 2 votes
One can use the Visual Studio IDE for PS3 development -- the PS3 relevant bits are, of course, just command-line tools (GCC ports) that can be plugged in to makefiles that VS can understand, after all.

There's also a toolchain called ProDG, by SN Systems that is used for PS3 development.

GDB, as an aside, is its own, command-line program. Some IDEs (such as Xcode on the Mac) have a GUI that wraps it. So it's not "built in" to CodeWarrior or any other IDE, per se, but ships with some as GUI layers some times communicate with it.

---
Tags: tools, ide
---


# Question
Title: Outsourcing Artwork: Hourly or Per-Project?
I've hired people to produce art and graphics before, but only ever at a per-job rate and that has worked out well.

This question is for both artists and the people who hire them:

As a buyer, are there any situations or types of projects you've experienced where it worked out better billed at an hourly rate?

For artists, do you have a preference for one over the other and if so, why?

# Answer
> 6 votes
It depends on what kind of results your looking for, I'd say.

I have clients with whom I've worked out this per-hour approach: My client have a list of tasks that they keep filled. I take out time and work on the tasks with the highest priority. We agree on beforehand how many hours, roughly, I should work every week. This means, for them, the cost is pretty constant, but the results are varying. Usually we also agree I can deviate and work on smaller impulsive tasks, ie follow my "spur of the moment"-creativity. Then once a week we meet up and discuss my work. (That regular meeting is important.)

The benefit of this is I can work whenever I want. This may sound sloppy, but what happends is you end up working when you have ideas and a feel inspired. If you want "innovate" creative results, I think a setup similar to this is almost required.

The down-side is there can be weeks where nothing significant happends. If results are needed on a certain date, I don't think this works that well. It also requires you have a healthy business relationship and can trust eachother. I wouldn't do this from day 1. I would say it also requires that the creator is passionate about the project.

Then I have clients with "normal" projects where the desired results are more or less known and there's a set time frame. There's also usually a known budget. Here I think the only viably approach is agreeing on a set price for a given amount of results of a certain quality. The benefit is the chance of getting those results at the given time is much higher, and that means the client can plan the project. The down-side is you seem to slip into this "daily-grind" mode, as a creator. You run more on auto-pilot and mostly stick to methods you already know. Since you know what you need to deliver, you deliver that, and that's it. Then of course, that also means you usually get more done in less time.

I have to say I like both approaches. They compliment eachother and mixing them up keeps me evolving new skills as well as improving my already existing ones. My clients seem to like both as well: One delivers out-of-the-leftfield ideas and the other gets things done.

I'm not sure I quite answered your question. But at least I think these two methods are related to being paid per-hour vs. per-project, somehow, I hope.

---
Tags: graphics, art, outsourcing
---


# Question
Title: Factors to consider when building an algorithm for gun recoil
What would be a good algorithm for calculating the recoil of a shooting guns cross-hairs?

What I've got now, is something like this:

1. Define min/max recoil based on weapon size
2. Generate random number of "delta" movement
3. Apply random value to X, Y, or both of cross-hairs (only "up" on the Y axis)
4. Multiply new delta based on time from the previous shot (more recoil for full-auto)

What I'm worried about is that this feels rather predicable, what other factors should one take into account when building recoil? While I'd like it to be somewhat predictable, I'd also like to keep players on their toes. I'm thinking about increasing the min/max recoil values by a large amount (relatively) and adding a weighting, so large recoils will be more rare -- it seems like a lot of effort to go into something I felt would be simple.

Maybe this is just something that needs to be fine-tuned with additional playtesting, and more playtesters? I think that it's important to note, that the recoil will be a large part of the game, and is a key factor in the game being fun/challenging or not.

# Answer
> 6 votes
Guns tend to recoil vertically far more than they recoil to the left or right (at least the few I've fired -- pistols and a shotgun -- have done so to the best of my recollection). I have a feeling the random variance in X would just feel unusual.

I would start with an implementation that kicks the gun/view upwards only, probably based on the power of the gun. When fired, a cooldown timer starts. If the gun is fired again while the cooldown timer is still counting down, the vertical kick is applied again, with intensity proportional to how much time is left on the timer. After a certain threshold it might be appropriate to add X axis variance to indicate that the player is really losing control of the (probably automatic) weapon. I've never fired such a thing so I don't know what that is supposed to feel like, but I imagine "chaotic" would fit nicely. The cooldown should probably scale a bit -- but nonlinearly -- as you continue to fire and the intensity of the kicks should probably be similarly damped or smoothed. Pure linear measures might feel too harsh.

Whatever you do, it sounds like your initial plans called for a fair bit of randomization and I don't think that would be appropriate -- a small bit, certainly, but sudden large recoils amidst smaller ones seem like they'd be unusual.

# Answer
> 3 votes
I'd be tempted to try to approximate real physics here. It isn't something you're going to do several times per frame so the cost of the calc probably won't factor much.

The impulse force of the powder explosion acting along a vector opposite the barrel direction with opposing force vectors where the hands/shoulder are all combine into a linear & angular momentums for the gun.

You vary the mass of the gun, shooter, & the hand/arm strength, along with varying amounts of ammo powers for different recoils. A gun's recoil for a particular person doesn't vary much unless different cartridges are used or the shooter gets fatigued.

---
Tags: game-design, algorithm, playtesting
---


# Question
Title: How to calculate new direction after sprite collision
The scenario as you can see in the picture. A ball will be hitting a surface and I want to fairly correctly get the new angle after the collision..

I expect to know the X,Y coordinates of the lines breaking points (The picture below would has 6 lines)

Secondly, if the ball would have a rotation - Is there a standard way of compensate for a "screewed" ball?

# Answer
What you need to calculate is the reflection vector;

if **v** is the velocity of your ball and **n** is the normal vector of the surface the ball is bouncing from then the the velocty of the ball after the bounce (assuming perfectly elastic collision etc) will be;

**v**-2(**v**•n)**n**

in 2d this will be;

newvelocity\_x=v\_x-2(v\_x.n\_x+v\_y.n\_y)n\_x

newvelocity\_y=v\_y-2(v\_x.n\_x+v\_y.n\_y)n\_y
> 13 votes

---
Tags: mathematics, collision-detection
---


title: Help with Strategy-game AI

text:
# Question
Title: Help with Strategy-game AI
I am developing a strategy-game AI (think: Final Fantasy Tactics), and I am having trouble coming up for the design of the AI. My main problem is determining which is the optimal thing for it to do.

**First let me describe the priority of what action I would like the AI to take:**

1. Kill nearest player unit
2. Fulfill primary directive (kill all player units, kill target unit, survive for x turns)
3. Heal ally unit / cast buffer

**Now the AI can do the following in its turn:**

* Move -\> {Attack / Ability / Item} (either attack or ability or item)
* {Attack / Ability / Item} -\> Move
* Move closer (if targets not in range)
* {Attack / Ability / Item} (if move not available)

**Notes**

Abilities have various ranges / effects / costs / effects. Each ai unit has maybe 5-10 abilities to choose from. The AI will prioritize killing over safety unless its directive is to survive for x turns. It also doesn't care about ability cost much. While a player may want to save a big spell for later, the AI will most likely use it asap.

Movement is on a (hex) grid

num of player units: 3-6

num of ai units: 3-7 or more. Probably max 10.

AI and player take turns controlling ONE unit, instead of all at the same time.

Platform is Android (if program doesnt respond after some time, there will be a popup saying to Force Quit or Wait - which looks really bad!).

**Now comes the questions:**

* The best ability to use would obviously be the one that hits the most targets for the most damage. But since each ability has different ranges, I won't know if they are in range without exploring each possible place I can move to.
* One solution would be to go through each possible places to move to, determine the optimal attack at that location - which gives me a list of optimal moves for each location. Then choose *the* optimal out of the list and execute it. But this will take a lot of CPU time. Is there a better solution?
* My **current idea** is to move as close as possible towards the closest, largest group of people, and determine the optimal attack/ability from there. I think this would be a lot less work for the CPU and still allow for wide-range attacks. Its sub-optimal but the AI will still seem 'smart'.

**Other notes/questions:**

* Am I over-thinking/over-complicating it? Better solution? **I am open to all sorts of suggestions**
* I have taken a look at the spell-casting question, but it doesn't take into account the movement - so perhaps use that algo for each possible move location? The top answer mentioned it wasn't great for area-of-effect and group fights - so maybe requires more tweaking?
* **Please**, if you mention a graph/tree, let me know *basically* how to use it. E.g. Node means ability, level corresponds to damage, then search for the deepest node.

# Answer
There are a lot of applications that you could use for this kind of AI. Personally, one of the most obvious techniques you could make use of is a position evaluation function. Killzone made use of this technique and it's described in the following paper:

http://www.cgf-ai.com/docs/straatman\_remco\_killzone\_ai.pdf

Actually, you could probably utilise a lot of that paper since it describes world representation, line of sight data, lookup tables, etc, and you've basically got a graph already with your hex grid (you just need to add neighbouring nodes, which in this case would be the neighbouring hexagons to a single hexagon).

Another thing to look into (that's pretty impressive at the moment, but slightly more advanced) is planners. I haven't read up much on Hierarchical Task Networks, I'll leave that to you. One planner that might help is GOAP (Goal Oriented Action Planning)

This link has lots of information regarding GOAP: http://web.media.mit.edu/~jorkin/goap.html

Something that I just thought of with regards to your "Survive for X number of turns" goal is the use of an influence map. An influence map is just a very simple representation for your world where each node (hexagon) has a single value associated with it (called the influence).

The influence can be calculated in a number of ways, but an example for your case could be to have the players generate +10 influence on the hexagon they are placed on and +1 influence on the hexagon that is designated as the maximum range of the player.

So for example, if you have a group of players clustered together, the influence around them would be relatively high. This could be construed by the AI as a threat to its life and moves away from the points of highest influence.

These are just a few techniques that you could use, but there are loads others. If you want something simple, use something like hierarchical FSMs (pretty much FSMs with each state containing another FSM with a higher level of detail). If you want something complex but functional and practical use GOAP and influence maps. It doesn't really matter to be honest because the **MAIN POINT** is to make the AI fun, and to do that you need to implement some sort of "artificial stupidity". No one will want to play an AI that's infinitely smarter than they are, regardless of how much effort you put into it. I'm not saying this to sound harsh, I'm saying this because it's important that the AI make mistakes cos their human counterparts sure do!

Good luck! :)
> 8 votes

# Answer
Over the years I've written 3 game AIs, all of which played a respectable game.

Two of the cases had limited options per turn and so I explored all possibilities and evaluated the resulting positions--I altered the depth I searched based on the difficulty and it didn't take very many layers to make a quite respectable opponent. I could get a couple of layers down and still have a response back in a second or two and that was on some pretty ancient processors. (All of these were before Windows was on the scene.) The quality of the position analysis is *VERY* important when using this approach.

The third case did not permit such an analysis as the number of possible moves per turn could easily exceed the particles in the universe. It was a situation sort of like Risk--territory with a number of armies on it but you could make any number of moves per turn, the key factor being moves took time. A province next door generally took 1 turn, one on the other side of the map could take 9.

I used a totally different approach here. I decided the percent of the forces to be allocated to defense and allocated those based on the value of the territory and the estimated enemy threat (While you could see what forces your opponent moved you could not see where they were going--it assumed the human would be concentrating it's forces somewhere and figured it was much more likely to be where they could all arrive at once rather than piecemeal.) Anything not needed for defense became available for offense. I looked at each possible objective and computed what it would take to have a good chance of taking it quickly (a protracted battle would destroy basically all it's production) and generated a set of attack orders for it. The value of the order was the value of the province, the cost was the number of army/turns committed to the attack. Pick the highest value and execute the orders, repeat until the available forces couldn't take anything. The execution time was trivial.

I hope I gave you some ideas here.
> 5 votes

# Answer
Your note about quitting/waiting suggests to me you're doing all the processing work on the main thread of the application. You could, assuming there is sufficient thread support in the Android's SDK (which I assume there must be), offload the "thinking" portion of your AI to a worker thread while the main thread pops up an in-game "AI is considering..." UI but otherwise renders normally.

Of course there are good reasons not to want to do that, such as not wanting the AI to take so long anyhow because the player will get bored.

As for your actual question, while your "current idea" is workable, it's very simple. It's a good starting point, though. It's a system where the AI is purely result-focused -- trying to maximum one value (damage). Other options include a target-focused approach, where you pick a target from the opposing team (randomly, one with the most HP, some combination thereof, et cetera), and move to that target, trying to damage it.

One thing you might want to consider is giving each ability a 'power' or 'effectiveness' stat that is hidden from the player and is used only internally by your AI. You determine the values of this stat yourself, based on your own knowledge of the abilities as the game's programmer.

Your AI would then select their highest rated ability and try to use that, if they can't for whatever reason, pick the next, et cetera. If built appropriately general enough, you could start to tie these two systems together, so that once you establish a target you have heuristics for the best kinds of attacks on that target (for example, weight an attack that does MP damage as more effective if the target has high MP).
> 4 votes

---
Tags: android, ai
---


# Question
Title: Basic tutorial/introduction for 3d matrices, idealy in c++, without openGl or directX
I am wondering if there is a simple tutorial that covers the basics of how to initialize rotation, translation and projection matrices, and how to multiply them, and how to get the screen coordinates afterwards for a 3d point.

Idealy, the tutorial comes with compilable code and is not dependent on any 3rd party library.

Searching the internet, I found lots of tutorials, so this is not the problem. Yet, it seemed all of these either covered openGl or directX, or they were theoretical in nature.

# Answer
> 2 votes
I have found that the D3D SDK documentation does have a reasonably good, and relatively API-agnostic overview of the transformation pipeline. The thing to remember is that while references may show you how to set matrices with API-specific alls, nothing about the form or values in those matrices is API-specific -- it's all just math under the hood, and you can make it do whatever you need it to.

In addition to the two links David Lively provided, there's an MIT Opencourseware graphics course here. You can also find a fair number of references -- of perhaps unknown quality -- by searching for "computer graphics pipeline" and omitting specific references to APIs.

However, for the deepest forays into the theoretical graphics pipeline fundamentals, I would submit that books are still the best way to go. I am particularly fond of "Fundamentals of Computer Graphics, 3rd Ed," and "The Geometry Toolbox" (the latter is primarily a discussion of the linear algebra behind the graphics and not so much the graphics itself, though).

# Answer
> 3 votes
One of my very, very favoritest things:

Matrices can be your friends

And another one that just came up but looks nice, Matrices ARE your friends.

Get the math down, and the framework you're using (OpenGL, DirectX/XNA, or whatever) will start to make more sense.

# Answer
> 1 votes
This is not a actual answer to your question. But something like learning exercise i suggest for you, if you want to learn about 3D graphics matrices.

Make you own super simple CPU based 3D rendering library. For start you should use something like canvas which enables to draw polygones (triangles). I sugests SDL. For algebra maybe armadillo, but it is little overkill. You can be fine with some simple matrix4x4 and vector2/3/4 class (or write own).

Then go to opengl documentation and code these function:

```
gl_begin //(support only triangles)
gl_color //color will help you to determine which triangle is which one
gl_vertex
gl_end

glViewport

glMatrixMode // it is not neccesery to have matrix stack for you, so you can use some easier approach
glLoadIdentity
glOrtho
glFrustum
gluPerspective

glTranslate
glRotate
glScale
// and that could be enough for easy render library.

```

And read as much theory before. David Lively suggested nice articles. I don't say to make it in the same way that opengl does. It can be simplier for super simple library you are going to create, but opengl has very smart archicture, so consider keeping your path with it.

It is possible that i forgoten to include some crucial function, let me know in comments please.

---
Tags: mathematics, matrix
---


# Question
Title: [JOGL] My program is too slow, how can I profile with Eclipse?
My simple opengl program is really toooo slow and not fluid. I'm rendering 30 sphere with simple illumination and simple materials. The only complex computing stuff I do is a collision detection between ray-mouse and spheres (that works ok and i do it only in mouseMoved) I'm not using any threads, just an animator to move spheres.

How can I profile my jogl project?

Or maybe (most probable...) I have some opengl instructions that I don't understand and make render particular accurate (or back face rendering that I don't need or whatever I don't know exactly I'm just entering the opengl world)

# Answer
> 2 votes
What do you mean by "too slow", as in it dropped from 5000 frames per second to 500, or it went from 100 to 2 (do note that frame rate is a logarithmic time scale).

For profiling, there are several java profilers, and some of them have plugins for eclipse. A quick google turns up several potential solutions.

As far as OpenGL goes, a couple of things: are you using matrices, or manually transforming the vertices? Do you use VBOs or Display Lists, or are you submitting each sphere using immediate mode instructions? How many triangles in each sphere?

# Answer
> 1 votes
There are several Java profilers you can evaluate. That will only tell you so much, though -- basically what's going on CPU-side. If that's where your performance bottleneck is, great, but if not you may need to resort to tools like gDebugger to do analysis on your OpenGL call stream.

---
Tags: java, profiler, jogl
---


# Question
Title: Ray Intersecting Plane Formula in C++/DirectX
I'm developing a picking system that will use rays that intersect volumes and I'm having trouble with ray intersection versus a plane. I was able to figure out spheres fairly easily, but planes are giving me trouble. I've tried to understand various sources and get hung up on some of the variables used within their explanations.

Here is a snippet of my code:

```
   bool Picking()
 {
  D3DXVECTOR3 vec;
  D3DXVECTOR3 vRayDir;
  D3DXVECTOR3 vRayOrig;
  D3DXVECTOR3 vROO, vROD; // vect ray obj orig, vec ray obj dir
  D3DXMATRIX m;
  D3DXMATRIX mInverse;
  D3DXMATRIX worldMat;

                // Obtain project matrix
  D3DXMATRIX pMatProj =   CDirectXRenderer::GetInstance()->Director()->Proj();
                // Obtain mouse position
  D3DXVECTOR3 pos = CGUIManager::GetInstance()->GUIObjectList.front().pos;

                // Get window width & height
  float w = CDirectXRenderer::GetInstance()->GetWidth();
  float h = CDirectXRenderer::GetInstance()->GetHeight();

                // Transform vector from screen to 3D space
  vec.x =  (((2.0f * pos.x) / w) - 1.0f) / pMatProj._11;
  vec.y = -(((2.0f * pos.y) / h) - 1.0f) / pMatProj._22;
  vec.z = 1.0f;

                // Create a view inverse matrix
  D3DXMatrixInverse(&m, NULL, &CDirectXRenderer::GetInstance()->Director()->View());

                // Determine our ray's direction
  vRayDir.x = vec.x * m._11 + vec.y * m._21 + vec.z * m._31;
  vRayDir.y = vec.x * m._12 + vec.y * m._22 + vec.z * m._32;
  vRayDir.z = vec.x * m._13 + vec.y * m._23 + vec.z * m._33;

                // Determine our ray's origin
  vRayOrig.x = m._41;
  vRayOrig.y = m._42;
  vRayOrig.z = m._43;

  D3DXMatrixIdentity(&worldMat);
  //worldMat = aliveActors[0]->GetTrans();
  D3DXMatrixInverse(&mInverse, NULL, &worldMat);

  D3DXVec3TransformCoord(&vROO, &vRayOrig, &mInverse);
  D3DXVec3TransformNormal(&vROD, &vRayDir, &mInverse);
  D3DXVec3Normalize(&vROD, &vROD);

```

When using this code I'm able to detect a ray intersection via a sphere, but I have questions when determining an intersection via a plane. First off should I be using my vRayOrig & vRayDir variables for the plane intersection tests or should I be using the new vectors that are created for use in object space?

When looking at a site like this for example: http://www.tar.hu/gamealgorithms/ch22lev1sec2.html

I'm curious as to what D is in the equation AX + BY + CZ + D = 0 and how does it factor in to determining a plane intersection?

Any help will be appreciated, thanks.

# Answer
For your first question, about vRayOrig & vRayDir, you should use what you need to use -- certainly the plane and the ray must be defined in the same space, or the results you get out of the intersection test will be meaningless. So you need to either define or transform the plane into the same space as the ray, or the other way around.

For the second question, that's the implicit equation of a plane. D itself is just some constant for the plane; when the plane is normalized, it can be interpreted as "the distance to the origin" (A, B and C can be interpreted as the X, Y, Z components of the plane's normal), but you need to be careful with that.

Look at it like this. A plane can be defined by some normal vector N, and a point P. All points in the plane will be perpendicular to the normal vector, which is to say the vector from P to any point T will be (T - P) and will be perpendicular to N. The dot product of two perpendicular vectors is zero. Thus:

```
                          N dot (T - P) = 0
Nx(Tx - Px) + Ny(Ty - Py) + Nz(Tz - Pz) = 0    (dot product)
NxTx - NxPx + NyTy - NyPy + NzTz - NzPz = 0    (distribute)
NxTx + NyTy + NzTz - NxPx - NyPy - NzPz = 0    (collect and group)

```

In case it's not clear, "Nx" is the X component of N, et cetera. Now that we've got that expansion, remember that (A,B,C) are often the names of the plane's normal's components, so we can rename:

```
ATx + BTy + CTz - APx - BPy - CPz = 0    (collect and group)

```

That should look a little more familiar. If we call the whole second half of the equation D, we end up with `ATx + BTy + CTz + D = 0` or in general `Ax + By + Cz + D = 0` -- so D, is in fact (-APx - BPy - CPz) where P is the point that defines the plane.

This is useful for ray intersection because it will be zero for any (x,y,z) on the plane -- and the point that the ray passes through the plane *will* be on the plane. That's the computation that the page you linked to is demonstrating. For any point (x,y,z) that *isn't* on the plane, the evaluation of (Ax + By + Cz + D) will be nonzero.
> 5 votes

---
Tags: c++, 3d, mathematics, linear-algebra
---


# Question
Title: Does swf provide better compress rate than zlib for png image?
Somebody told me that when a png image is stored in swf, it's separated to several layer, hence the alpha channel can be compressed better. Is it true? Or, once png image is imported into a swf, it's format is changed, e.g converted into bitmap data, and than compressed by swf's compress algorithm. That's, it is not in png format anymore.
I don't know how swf packing its resource, please tell me if you know.

# Answer
> 3 votes
If you add a PNG image in the Flash IDE, you can choose JPEG compression for it. The interesting part about this is, that it will preserve alpha transparency.

So what internally happens is exactly as you describe. The alpha channel and the color information get separated and compressed individually. AFAIK the alpha will always be JPEG compressed whereas I'm not so sure about the image. I suspect that there is some analyzing going on and the algorithm then chooses either PNG or JPEG compression for the color data.

This only applies for the Flash IDE though (eg. Flash CS 5, Flash CS 4, etc.). In Flex, images aren't treated that way. However there's a tool that can do that with any existing SWF. It's called "reducer" and can be found here: http://blog.joa-ebert.com/2009/08/08/reducer/

Actually I encountered some weird behavior using Flex Builder a while back, where I compressed PNG game-assets using ImageOptim but the resulting SWF didn't decrease in filesize like I would have expected. This lead to this question on stackoverflow which isn't answered till today :)

---
Tags: flash, image, swf, compression
---


# Question
Title: How to detect which edges of a rectange touch when they collide in iOS
I'm creating a basic "game" in iOS 4.1. The premise is simple, there is a green rectangle ("disk") that moves/bounces around the screen, and red rectangle ("bump") that is stationary. The user can move the red "bump" by touching another coordinate on the screen, but that's irrelevant to this question.

Each rectangle is a UIImageView (I will replace them with some kind of image/icon once I get the mechanics down). I've gotten as far as detecting when the rectangles collide, and I'm able to reverse the direction of the green "disk" on the Y axis if they do. This works well when the green "disk" approaches the red "bump" from top or bottom, it bounces off in the other direction. But when it approaches from the side, the bounce is incorrect; I need to reverse the X direction instead.

Here's the timer I setup:

```
- (void)viewDidLoad {
    xSpeed =  3;
    ySpeed = -3;
    gameTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(mainGameLoop:) userInfo:nil repeats:YES];
    [super viewDidLoad];
}

```

Here's the main game loop:

```
- (void) mainGameLoop:(NSTimer *)theTimer {
    disk.center = CGPointMake(disk.center.x + xSpeed, disk.center.y + ySpeed);

    // make sure the disk does not travel off the edges of the screen
    // magic number values based on size of disk's frame
    // startAnimating causes the image to "pulse"
    if (disk.center.x < 55 || disk.center.x > 265) {
        xSpeed = xSpeed * -1;
        [disk startAnimating];
    }
    if (disk.center.y < 55 || disk.center.y > 360) {
        ySpeed = ySpeed * -1;
        [disk startAnimating];
    }

    // check to see if the disk collides with the bump
    if (CGRectIntersectsRect(disk.frame, bump.frame)) {
        NSLog(@"Collision detected...");
        if (! [disk isAnimating]) {
            ySpeed = ySpeed * -1;
            [disk startAnimating];
        }
    }
}

```

So my question is: how can I detect whether I need to flip the X speed or the Y speed? ie: how can I calculate which edge of the bump was collided with?

# Answer
> 4 votes
Since you're using rectangles and it sounds like you're also confining yourself to eight directional movement, you can probably get away with computing a vector from the ball's center to the bumper's, and examining that; it will tell you about their relative positions. If the magnitude of the Y component is greater the ball is hitting the top or bottom, if the X component is greater the ball is hitting the left or right, and if they are equal it's hitting exactly on the corner (maybe reverse both directions in that case?).

A more robust solution would probably involve the separating axis theorem and use of penetration vectors to gauge response and real reflection vectors to compute the change in velocity. I don't know how robust a solution you need though.

# Answer
> 1 votes
You can't simply do that with CGRectIntersectsRect. That's only a method that say if a collision is detected or not.

So you have to "split" your rect into more "pieces" and call CGRectIntersectsRect for each piece (or do that by hand without CGRectIntersectsRect). I.e.

```
CGRect Up = CGRectMake(bump.frame.origin.x, bump.frame.origin.y, bump.frame.size.width, bump.frame.size.height/4);
CGRect Down = CGRectMake(bump.frame.origin.x, bump.frame.origin.y + (bump.frame.size.height/4)*3, bump.frame.size.width, bump.frame.size.height/4);

CGRect Left = CGRectMake(bump.frame.origin.x, bump.frame.origin.y + bump.frame.size.height/4, bump.frame.size.width/4, bump.frame.size.height/2);
CGRect Right = CGRectMake(bump.frame.origin.x+(bump.frame.size.width/4)*3, bump.frame.origin.y + bump.frame.size.height/4, bump.frame.size.width/4, bump.frame.size.height/2);

```

Then you can check where your frame first collide (but be carefull: that example is only edge detection - the center isn't detected at all).

```
if (CGRectIntersectsRect(disk.frame, Up) || CGRectIntersectsRect(disk.frame, Down)) {
  NSLog(@"Collision detected...");
  if (! [disk isAnimating]) {
    ySpeed = ySpeed * -1;
    [disk startAnimating];
  }
}
if (CGRectIntersectsRect(disk.frame, Left) || CGRectIntersectsRect(disk.frame, Right)) {
  NSLog(@"Collision detected...");
  if (! [disk isAnimating]) {
    xSpeed = xSpeed * -1;
    [disk startAnimating];
  }
}

```

I couldn't test this code, so please be carefull - it's only to give you an general idea about this...

# Answer
> 1 votes
As long as you're just checking circle vs. rectangle collisions it should be sufficient to do the following:

Whenever you detect a collision, check the center of your circle against the 6 outer sides of the rectangle, as in the following image:

If the circle is in *bottom* or *top*, flip the Y-speed. If in *left* or *right* flip the X-speed. If the circle is located in one of the edges, you'll probably want to flip both. Please note that this will only work reliably when the traveled distance of the circle doesn't exceed the circle diameter (this is per update). If your circle is moving faster, you'll be better off with continuous collision detection.

This approach should be really fast and easy to implement. For a more robust collision detection that can also handle arbitrary convex polygons, check out the separation axis theorem (as also stated by Josh Petrie).

---
Tags: iphone, collision-detection
---