# Question
Title: Explain this line segment intersection code
I've been reading this article on pathfinding over polygon meshes using line-of-sight, and in the article are several code snippets. One of them, the one I'm trying to understand, is a simple function that determines whether two line segments intersect.

Here is that function from the article (in C#, though that isn't important to me):

```
public static bool LineSegmentsCross(Vector2 a, Vector2 b, Vector2 c, Vector2 d)
{
    float denominator = ((b.X - a.X) * (d.Y - c.Y)) - ((b.Y - a.Y) * (d.X - c.X));

    if (denominator == 0)
    {
        return false;
    }

    float numerator1 = ((a.Y - c.Y) * (d.X - c.X)) - ((a.X - c.X) * (d.Y - c.Y));

    float numerator2 = ((a.Y - c.Y) * (b.X - a.X)) - ((a.X - c.X) * (b.Y - a.Y));

    if (numerator1 == 0 || numerator2 == 0)
    {
        return false;
    }

    float r = numerator1 / denominator;
    float s = numerator2 / denominator;

    return (r > 0 && r < 1) && (s > 0 && s < 1);
}

```

Without any explanation, I assume that the function accepts two line segments, a-b and c-d. I know the first part checks whether the two lines are parallel, in which case they don't intersect. After that, I'm not sure. I suspect the next bit checks whether the two segments are out of range of each other? The code talks about numerators and denominators, so maybe it's dealing with slope comparisons?

In any case, I'd like to understand the math used here for determining line intersections. I know there's an algorithm that this code is following, but I don't know what it is. How does the formula used in the first part determine that the lines are parallel? I know it works, but why does it work? And what does the function do after that? Why?

I'd much rather understand how the code works, and then write my own code from that knowledge, than just blindly copy someone else's code.

# Answer
First, the value called `denominator` is something that you might call the "two-dimensional cross product" of the vectors `b - a` and `d - c`. You can see that it corresponds to what would be the z-component of the cross product if these were 3D vectors. The "2D cross product", like the 3D one, represents the (signed) area of the parallelogram spanned by the two vectors. If the two vectors are parallel or antiparallel, the parallelogram squashes down to nothing and its area is zero.

The two numerators are another pair of 2D cross products. In particular, `numerator1` is the cross of the vectors `d - c` and `a - c`, that is a vector *along* one line with a vector pointing from that line toward the other line. So this calculates a parallelogram that spans between the two lines.

At this point it's helpful to sit down and draw a few diagrams, but the key thing to realize is that when the two line segments are *barely* touching—i.e. when they touch only at an endpoint—the parallelogram spanned by `d - c` and `a - c` is either squashed down to nothing, or it's equal to the previous parallelogram (the one calculated in `denominator`). In other words, in these barely-touching cases, `numerator1` is either zero or equal to `denominator`.

It's not too hard to convince yourself, then, that intermediate cases where the line segments intersect somewhere in the middle result in parallelogram areas somewhere between 0 and `denominator`, or in other words, `numerator1 / denominator` should be between 0 and 1.

Then `numerator2` is calculated the same way, but just swapping segments. It's necessary to check both directions because there are cases where the line segments don't intersect, but one of the two numerator parallelograms is stretched long and thin, so its area gets small and this would be detected as a false intersection if we didn't check both cases.
> 6 votes

---
Tags: mathematics, geometry, intersection
---


# Question
Title: Entity Component Architecture - initialization between multiple components
I'm starting work on an game set in an isometric world, and I'm having a bit of trouble understanding how to implement certain aspects of the entity component system idea.

Here are the Components and Systems I have so far:

WorldData (only one ever used, contains map and cell sizes) Camera (currently also only one ever used, though that could change I guess) WorldPosition (just contains X and Y values, in world space) Renderable (contains the image to draw, screen position values + offset, and a depth) Floor (contains the type of flooring and a walk speed)

Now If I create an entity with WorldPosition, Floor and Renderable components, where do I put the logic to enforce certain rules. For example, if Floor.FloorType is set to 'Grass', I want the image in the Renderable component to be set to 'floor-grass.png'. Should this go in something called 'FloorSystem', which checks every entity that has a Floor and Renderable component and updates them? And if so, do I need some sort of 'dirty' flag on Floor to say when it has changed, so that FloorSystem knows to update it and is not updating every floor tile in every frame? Or do I instead create a 'Dirty' component which I attach to that entity when it changes?

Any guidance would be much appreciated! I love the general elegance of this architecture and I think it will work well in my game once I get a better handle on it.

# Answer
> Now If I create an entity with WorldPosition, Floor and Renderable components, where do I put the logic to enforce certain rules. For example, if Floor.FloorType is set to 'Grass', I want the image in the Renderable component to be set to 'floor-grass.png'.

In a data file. There's no reason to say that you can't have a tile with `FloorType=Grass` but with `Image=brick.png`. Maybe you want it for some secret area the player has to use sound or some other property of the ground type mismatching the visuals to figure out. Or maybe you just want to have a wide visual palette and 20 different grass tiles that are all grass but look different.

You really don't want to couple `Floor` and `Renderable`. They are entirely separate things.

There's no good reason to encode policy into code. It's data. Leave it in data. You might make a map editor tool that does some extra checking to protect designers from common mistakes, but avoid enforcing design rules in the code itself.

> And if so, do I need some sort of 'dirty' flag on Floor to say when it has changed, so that FloorSystem knows to update it and is not updating every floor tile in every frame? Or do I instead create a 'Dirty' component which I attach to that entity when it changes?

No. In the first case you still have to iterate over all tiles to check a dirty flag, and the second is an abuse of components. You can easily enough just make a dirty list that you append objects to if they need an update, but you certainly don't need it in this case.
> 1 votes

---
Tags: entity-system
---


# Question
Title: How can I provide a mechanism for users to increase the gameplay speed?
I am developing a tower-defense game and I want to permit user to change game engine speed ,for example rotation speed of towers,rockets speed ,enemies moving speed ,counters and etc proportionally. Is it any way to increase/decrease speed of game engine or any other way similar to it?

# Answer
> 5 votes
You don't speed up the engine, you speed up your units and their actions. For example, when you update an enemy, you usually do something like `enemyDirection * enemySpeed * timePassed` to get their new position. Now, if you want to double or halve the speed of gameplay, you just add this in as a factor: `enemyDirection * enemySpeed * timePassed * gameplaySpeedFactor`. That's roughly the principle behind it.

---
Tags: cocos2d, cocos2d-x
---


# Question
Title: Does game development have its own types of modeling?
In general computer science there are modeling "languages" (read: standardized diagramming techniques) such as UML ,, in databases there are things like ERD, in business there are other types such as BPMN,. Is there anything like these that are Game Design specific?

# Answer
There's no industry standard, but most high-profile studios do create a game design document.

Game development, after all, encompasses quite a number of fields, so there will often be a combination of storyboarding, UML for the programming side, a script for dialogue, and so on.

That being said, the number one "modelling language" I've encountered: flow charts.

But that's hardly specific to game design!
> 16 votes

# Answer
One of the actual models that I know about in game design is the MDA framework. This is the closest thing to your question that I can think of, as MDA gives you a reference to think and talk in (thus a language). And you can visualize it in a diagram if necessary.

A proper definition is given in this paper by Hunicke et al, and I'll give a short description below.

## The MDA framework

In MDA **mechanics** are the things that you define in a game as a designer. An example of a mechanic could be - *"A timer starting at 60 and counting down by one every second. If it reaches zero the game is over."*

A **dynamic** describes the actual behaviour of a mechanic. Or in other words: the influence of a mechanic on your game. The timer mechanic would add a *time pressure* dynamic to your game.

The **aesthetics** of a game describe the overal feel and types of play in a game. The 8 basic aesthetics are:

1. Sensation (pleasure of the senses)
2. Fantasy (make believe)
3. Narrative (drama)
4. Challenge (obstacles to overcome)
5. Fellowship (social interaction)
6. Discovery (uncharted territory)
7. Expression (self-discovery)
8. Submission (pastime)

The aesthetic generated by a timer is challenge, because the time pressure is an obstacle. Note that you can add any new (sub-)aesthetics if necessary.

---

MDA allows you to reason about your game design both bottom-up and top-down. If there's some aesthetic in your game that you feel is not represented strongly enough, you can add more mechanics to support it. You could also model your game in a diagram using MDA by connecting the mechanics that support specific dynamics, and so on.

I learned about it in a game design course, but you can probably find some further reading on the web too. I hope this is what you were looking for, good luck!
> 7 votes

---
Tags: game-design, design-patterns, documentation, design-document
---


title: XNA 4.0 - Car game dashboard lights

text:
# Question
Title: XNA 4.0 - Car game dashboard lights
I'm making a car game and doing the dashboard part. I'm trying to do the dashboard lights, i've did this changing the dashboard texture, overwriting the texture with the light image over it, example:

```
Texture2D dashboardTexture;
Texture2D parkingBrakeLightTexture;
Model carModel;

//when the light needs to turn on:

PutTextureOverDashboardTexture(parkingBrakeLightTexture);

//on Draw method I change the texture of dashboard mesh:

effect.Texture = dashboardTexture;
effect...

```

This is alright, but the lights will suffer influence from the external light if I EnableDefaultLighting() in the effect, then the dashboard lights will almost don't appear depending on what direction the car is, and of course that should not happen. So how can I make the lights of dashboard appear? I need to use another alternative? Or can I still utilize this method?

# Answer
From what I understand from your question: You don't want your model/dashboard to have so much shadow on it from certain angles.

Here is a picture of a textured model with just the default lighting enabled: The dark side:

Well if you want to make it look like there is lighting coming from the model you can add Emmisive Light. Change you EnableDefaultLighting code to look like this:

```
        effect.EnableDefaultLighting();
        effect.EmissiveColor = Color.FromNonPremultiplied(200, 200, 200, 255).ToVector3();

```

Here are the results: The dark side:

Just for interest. This is what EnableDefaultLighting does:

```
        LightingEnabled = true;
        // Key light.
        light0.Direction = new Vector3(-0.5265408f, -0.5735765f, -0.6275069f);
        light0.DiffuseColor = new Vector3(1, 0.9607844f, 0.8078432f);
        light0.SpecularColor = new Vector3(1, 0.9607844f, 0.8078432f);
        light0.Enabled = true;

        // Fill light.
        light1.Direction = new Vector3(0.7198464f, 0.3420201f, 0.6040227f);
        light1.DiffuseColor = new Vector3(0.9647059f, 0.7607844f, 0.4078432f);
        light1.SpecularColor = Vector3.Zero;
        light1.Enabled = true;

        // Back light.
        light2.Direction = new Vector3(0.4545195f, -0.7660444f, 0.4545195f);
        light2.DiffuseColor = new Vector3(0.3231373f, 0.3607844f, 0.3937255f);
        light2.SpecularColor = new Vector3(0.3231373f, 0.3607844f, 0.3937255f);
        light2.Enabled = true;

        // Ambient light.
        AmbientLightColor = new Vector3(0.05333332f, 0.09882354f, 0.1819608f);

```

EnableDefaultLighting just sets up the Directional Lights and Ambient Light which we can already access. That is why we can make additional modifications to the lighting after we call EnableDefaultLighting as I did with the emissive lighting.
> 2 votes

---
Tags: xna, textures, car
---


# Question
Title: How do I get the DirectX project templates to appear in Visual Studio?
I have DirectX11 on Windows 7, and I also have VS13 Express for Desktop. In some tutorials I have seen that there's an option on VS13 for new project on DirectX, but doesn't appear in my VS13. Is it because I have the for Desktop version instead of the for Windows one? Or do I need to install some DirectX developmentkit first? Thanks.

# Answer
The "DirectX" project templates are for Windows Store Apps / Windows Phone Apps. So I assume it has to do with the version of VS Express you are using (Desktop).

However, you don't need anything special to write traditional desktop apps. You just need to create a Win32 Application and include the DX11 headers in your code
> 8 votes

# Answer
There are no "DirectX" project templates for Win32 desktop applications. You just create a Win32 application and then use Direct3D 11.

If you'd like a Direct3D 11 tutorial for Win32 desktop, I have one on MSDN Code Gallery.

**UPDATE** Alternatively, you can install this extension if you move to the VS 2013 Community edition (or VS 2013 Pro+) Direct3D Win32 Game Visual Studio template which is also on GitHub
> 5 votes

---
Tags: directx11, visual-studio
---


# Question
Title: Usage of render states in Direct3D 11.x?
I know there are four different render states. They are

```
Blend State
Depth Stencil State
Rasterizer State
Sampler State

```

One of my Direct3D reference books say that Direct3D is a state machine. But how, where do we use these in game development?

# Answer
> 1 votes
This is quite broad.

* Blend state is used by the Output merger and you can configure it however you want to blend together outputs from a pixel shader and the render target or backbuffer.
* Depth stencil state is used if you have a depth stencil view bound to your rendertarget or backbuffer. You can configure it if you want depth or stencil test functionality.
* Rasterizer state describes the rasterizer fuctionality which occurs between primitive outputting shaders and pixel shaders and decides which pixels will be executed the pixels shader on.
* Sampler state is a texture sampler state which holds information how to sample a given texture resource.

You can usually create these by

```
ID3D11DeviceContext::CreateXYZState(state_description,state_pointer);

```

where XYZ is your 'Sampler', 'Rasterizer', etc., state\_description is a D3D11\_SAMPLER\_DESC (or rasterizer, etc.) structure object's address which you fill in with the desired parameters. state\_pointer is the address of your state which you want to create.
You can use these states by enabling them before a draw call by calling the relevant method of the device context such as *ID3D11DeviceContext::RSSetState(rasterizerstate);* for example.

There is much more to this topic, you should try them out one by one to understand it completely.

# Answer
> 0 votes
Direct3D 11 is a 'state machine' in the same way as all modern graphic APIs. The full state is much more complicated than these four objects. Here's a list of basic Direct3D 11 state (ignoring optional stuff like Geometry Shader, Stream Out, Tessellation Domain/Hull Shaders, DirectCompute Shaders/Resources, and Queries):

**Input Assembler**

* Input layout
* 1 or more vertex buffers
* 0 or 1 index buffer
* index buffer format (16-bit or 32-bit)
* primitive topology setting

**Vertex Shader**

* Vertex shader program
* up to 16 constant buffers
* up to 128 textures (shader resource view + texture resource)
* up to 16 samplers (*ID3D11SamplerState*)

**Rasterizer**

* rasterizer state (*ID3D11RasterizerState*)
* up to 16 viewports
* up to 16 scissor rectangles

**Pixel Shader**

* Pixel shader program
* up to 16 constant buffers
* up to 128 textures (shader resource view + texture resource)
* up to 16 samplers (*ID3D11SamplerState*)

**Output Merger**

* blend state (*ID3D11BlendState*)
* depth/stencil state (*ID3D11DepthStencilState*)
* up to 8 render targets (render target resource view + texture resource)

So to draw anything, you have to set all this state before you call Draw or DrawIndexed.

---
Tags: directx11
---


title: Java Game: Fullscreen images

text:
# Question
Title: Java Game: Fullscreen images
Hi I am making a football stratedgy game and I have it the game working. I was playing prison architect and minecraft in fullscreen and noticed there was no windows it was covering the whole screen. So I looked up how to do this and I got

```
 frame.setSize(Toolkit.getDefaultToolkit().getScreenSize());
    frame.setUndecorated(true);

    frame.setVisible(true);

```

and this works its just that all the images are (I don't know how to put this) the same size as when the game was in 600 * 500 window and I was wondering if there was a way to have them in the right place according to the size of the screen, so for example if the computer screen is 1000 * 1000 pixels the image whould be 100 pixels from the left of the screen but if someone played it on a 500 * 500 pixel screen it would be 50 pixels form the left of the screen. Keep in mind that they way I draw my images are

```
ImageIcon i2 = new ImageIcon("res/BackGrounds/titlescreen.png");
    img = i2.getImage();
g.drawImage(img, 10, 10, null);

```

I tried doing it this way:

```
    ImageIcon i2 = new ImageIcon("res/BackGrounds/titlescreen.png");
    img = i2.getImage();
    g.drawImage(img, 100, 10,Toolkit.getDefaultToolkit().getScreenSize().width / 5 -100,Toolkit.getDefaultToolkit().getScreenSize().height / 5 - 100, null);

```

but I when I tested it on a different computer whith a different sized screen the images where more squashed together because the screen is smaller and I had set the toolkit to be

Toolkit.getDefaultToolkit().getScreenSize().width / 5 -100

Pleas if u can help me, help me cause I really need help. THX in advance

# Answer
> 3 votes
The easiest way to achieve this is to draw your game to an image buffer first, instead of directly to the window. Then you draw that image scaled up according to the resolution of your window. This way you don't have to worry about scaling and positioning the indiviual elements of your display.

However, it might be advisable to only scale to the nearest integer multiple of your buffer size in order to avoid interpolation artifacts.

Look into java.awt.Canvas and buffer strategies for hardware-accelerated off-screen buffers.

Besides that, you might be interested in fullscreen exlusive mode as an alternative to windows without decoration: http://docs.oracle.com/javase/tutorial/extra/fullscreen/

---
Tags: java
---


# Question
Title: How can I make a power-up spawn system semi-random?
Basically I'm working on a similar game to achtung die kurve (http://curvefever.com). I'm almost done with the game, however I'm not completely fine with the way power up spawning works. As for now, I have setup a timer loop runs the spawn code block every 1 second. I have setup so each spawning period for each power up (total of 11 powers) is between 19.25 - 1.925 seconds. However this is fine, but it's to random I would say. For example it can be times were no power-ups spawn at all and there can be times were 5 power-ups spawn at the same time. I have made alot of games and this problem comes up every time.

# Answer
Why not simply spawn a random powerup every `N` seconds, where you specify some range to randomly pick in for `N` (eg. 3-10).

The power-ups will spawn out of synch. I'm not sure if you mean multiplayer-synch; if that's the case, you need to make sure your clients all use the same seed for the random number generator. That will fix your problem.
> 0 votes

# Answer
You can make the randomness depend on how long time it was since you last spawned a power-up.

For example: Assume you want a power-up roughly every m second, with "spread" s (seconds). Here, s should be less than m.

When (m-s)+j seconds have passed *since last spawned power-up*, you spawn a new power-up with probability (j-1)/(2s) (or probability 1 if s=0).

This model has the following properties:

* The average time between power-ups is exactly m seconds.
* Larger s gives a higher variance in waiting time between power-ups.
> 0 votes

---
Tags: random, spawning, powerup
---


# Question
Title: Do you need a license for US military badges, awards, decorations?
We would like to use in our game names and images of real US military badges, awards and decoration.

http://en.wikipedia.org/wiki/Awards\_and\_decorations\_of\_the\_United\_States\_military http://en.wikipedia.org/wiki/Badges\_of\_the\_United\_States\_Navy

I would like to know, if they are copyrighted or protected in any other way, or are they considered to be in public domain.

Regards and thanks Piotr

# Answer
As far as I know, you don't need a license. But, to be on the safe side...

you can actually call the army (as I understand it they assist with other branches as well) and ask questions like these, for free! They can also assist with other things, like where insignia are supposed to go, how they're arranged, uniform standards, etc.

Department of the Army's Office of the Chief of Public Affairs

```
U.S. Army Office of the Chief of Public Affairs, Western Region
10880 Wilshire Boulevard, Suite 1250
Los Angeles, California 90024
Phone: (310) 235-7621
Fax: (310) 235-6075

```
> 1 votes

---
Tags: licensing
---


# Question
Title: How do you create a game overlay that makes the underlying graphics inactive?
I've created a simple game, and I drew a large rectangle in photoshop with faded edges that I want to use to overlay the game until the user presses "Begin" (on the overlay). The problem I'm currently having is that the stage under the overlay is still responsive (i.e. I can click on the items under the overlay before I press "Begin"). Here's essentially what I'm doing:

```
 @Override
public void render(float delta) {
    Gdx.gl10.glClearColor(51f/255f, 51f/255f, 255f/255f, 1f);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

    stage.draw();

    overlay.setColor(0,0,0,150f/255f);
    batch.begin();
    batch.setColor(overlay.getColor());
    batch.draw(overlay, 0, 0);
    batch.end();
}

```

Is there a way to inactive the stage's input listener until the "Begin" button on the overlay is pressed? Is this how an overlay type feature over games is typically achieved?

Thank you!

# Answer
This logic goes in your update function rather than your render function. The easiest way to prevent this is with an if statement surrounding your stage interaction code.

```
If (overlay not active)
    Stage.handleinput()
Else
    Overlay.handleinput()
Endif

```
> 3 votes

---
Tags: opengl, java, libgdx, user-experience
---


# Question
Title: Is a Gaussian blur a fairly accurate representation of soft shadow edges?
I'm not sure if real life soft shadows (from close,large light sources) have a Gaussian or linear falloff, or something else.

I'm working on something where I can create the shadows by manipulating some kind of pre-rendered gradient texture so I am not having to rely on frame buffers and traditional shadowing techniques. I'm planning on baking the gradient into one channel of my mesh's texture and then manipulating the values based on how much shadow covers each quad. This is possible because I just have quads lined up like a zigzag where each peak can cast a shadow onto the next adjacent quad.

So a linear falloff would be easiest (just need to subtract some value from a linear gradient) but I have a hard time telling what actually looks realistic. Is there a simple math formula that could be applied to a linear gradient to pull out a Gaussian approximation?

# Answer
Real-life soft shadows have a shape that depends on the shape of the light source as it appears from the point of view of the shadowed surface. This is because penumbras occur due to partial occlusion of the light source from the shadowed surface's point of view. The shape of the shadow is therefore something like the shape of the occluder convolved with the shape of the light source.

For example, the sun appears to us as a disc, so soft shadows due to the sun are effectively convolved with a disk filter. The resulting falloff is, in many cases, similar in appearance to that of a Gaussian, which may explain why Gaussians are popular for shadow filtering.

Gaussian falloff is also very similar in appearance to the smoothstep function, which is pretty inexpensive to evaluate and could be a good choice for your shader.

The dependence of shadow shape on light source shape is most dramatically demonstrated during a solar eclipse. This photo by Flickr user Cantavestrella, for instance, was taken during a partial eclipse a few years ago. The eclipse resulted in a crescent of visible sun surrounding the moon, and as a result, the shadows of a tree show a crescent shape where the leaves of the tree happen to form a pinhole.
> 34 votes

---
Tags: shaders, shadows, lighting
---


title: Setting up images for frame animation

text:
# Question
Title: Setting up images for frame animation
I am learning the basics of iPhone frame animation. I have code that loops through 15 images to do an animation:

```
- (void)viewDidLoad
{
    [super viewDidLoad];
    UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(40, 40, 95, 70)];
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    for(int i = 1; i <=15; i++){
        UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"someImage_%02d", i]];
        [arr addObject:img];
    }
    iv.animationImages = arr;
    iv.animationDuration = 1.0 / 2;

    [self.view addSubview:iv];
    [iv startAnimating];
}

```

I want to load images of Link from a picture I found on the internet. How can I take this image (available as a png) and load the unique parts of the image? I have heard of people putting multiple images into a single PNG to improve performance. How do I extract the individual images into an array for use in code like the above?

Please keep in mind this is my first time doing frame animation. I realize this code can likely be improved. I'm trying to keep things simple.

# Answer
> 1 votes
Well I finally got it done and learned a few things in the process but teaching you how to use a bunch of Blender features is beyond the scope of this question so I'll just give you the results.

First, here is the .zip archive that contains all 405 animation components in the form of .png with alpha transparency. I removed the purple color-key since all modern hardware supports transparency. http://www.filedropper.com/toprow

I tried to retain the old school blockiness in case that's what you are going for but for some reason I could not coax Blender into doing this so the edges are soft.

Second, here is a video file that shows all the animations one after the other. I tested the video with Windows Media player with a stock build of Win7 that has no updates and it worked fine. http://www.filedropper.com/linkvideoxvid0000-0405 Use the following settings to have media player run the video at 16x16 pixels.

And here is the first frame so you can see what you have.

Also, here is the blender project in case you would like to figure out what I did here. If the other animation sheets have the exact same dimensions then you can just swap the images and press Animation in the Render tab.(Hopefully that's the case or you'll have some easy but very repetitive math to deal with) http://www.pasteall.org/blend/30072

---
Tags: animation, iphone
---


# Question
Title: game server/client user input/event handling
I'm currently getting my feet wet in the realm of networking, so I set a goal to make a simple client/server game using SFML for both graphics and networking. In my head it seemed easy at first, but the more I got into it the more questions arised. I didn't want to make a post before I hadn't done any research, but now, having read many blog posts and articles, there's nothing to lose.

The game I'm working on is a trivial PONG game: server waits for 2 players, when they are connected, clients send server paddle's X position only if mouse is moved. Server reads in the X pos. and sends each client opponent's position.

The problematic part is opponent's behaviour on the client side. When playing both clients + server on my computer, using 100% CPU speed server side, the opponent moves smooth, but having CPU running as fast as it can is nonsense! If I reduce update speed the movement becomes weird so to say.

1. Might there be anything to do with client-side prediction (I read about it too, but didn't quite grasp how it would be implemented)?
2. Since there are frequent position changes, should the server's update speed be as high as possible?
3. I'm using TCP, which I understand is "reliable" = no lost packets. For such fast-paced game like PONG, which protocol is more suitable.

Now, I do not fully understand the magic behind it all, very very thrilled about network programming. I've never been more excited during programming as I am dealing with networking.

Thank you for your attention!

# Answer
CPU 100% is most like a loop running, maybe to check if mouse has moved? You have to realize, that if you don't restrict message sending with time passed, you might send thousands of packets per second, when moving mouse.

1: Client-side prediction is movement you do, before server says it's ok to move. So, Client pressed move button and instead of waiting for new coordinates from server or somekind of move command to come from server, the client predicts that, pressing forward, moves you forward and thus, when server finally send the commands/coords, client should be in right position allready. This tries to eliminate lag perception.

So, Client side prediction is easy to add. You have to run same movement logic on server and client. You have to note, that when server eventually send the new coordinates, you have already send new movement stuff from client and also predicted new movement. So if you just take and set coordinates from server to client object, you snap back to previous position. You can prevent snap back by recording where you were after predicting movement and then check if client is on right track when server message comes and if not, snap it.

2: 30 updates per second should be enough ( 1000ms / 30 == every ~33ms). You can play around with this number to get some feeling. Anything between 20-50 can work.

3: TCP is fine for this kind of learning project and it can work even in larger projects. TCP does not guarantee that there is no packet loss ( packet lost between server-client), but if packets get lost, TCP can recover from it, but it can cause heavy lag. UDP however is little bit harder to use, because server can never know, if packets arrived or not.

Anyways, i would say that you should definitely limit sending the packets, limit your update loop running time and have fun. Also consider what you should be sending, you can send mouse movement event or direct mouse coordinates. Best would be events, so that client does not decide anything, it just tells server what buttons were pressed or what actions were requested. When server update loop runs, server could send new coordinates to every client.
> 2 votes

---
Tags: networking, input, server, client
---


# Question
Title: Is it more efficient to use an A* algorithm or a line system drawn in pathfinding in C#?
I was recently introduced to the A\* algorithm when I asked a friend about making AI/NPC's in video games move to certain points and it sounded very interesting. I am building an FPS and it has AI that must be able to move to certain points, so the A\* algorithm sounds very appealing to me.

However, as I went through the Half-Life 2: Episode 1 Developer Commentary, I found another solution that the workers at Valve have been using: a line system. I couldn't find a screenshot and alas, I couldn't find the developer node to show the system. :(

Basically, there's a whole system drawn on the level map for AI to move along. If there happens to be an enemy that shows up in a certain section that might not be on the AI's line of sight, then the AI can break out of the line and attack said enemy.

I'm building the game in C# (XNA) and I wanted to know if it would be better to use the algorithm, the line system or even both to achieve pathfinding?

# Answer
> 4 votes
I think what Valve does is using a **Navigation Mesh** (source) together with a **Visibility Graph**. The navigation mesh covers all of the walkable space in (usually) convex regions. A\* or Dijkstra's is used to plan paths between regions, while local movement techniques are used for moving agents inside regions. (This is very easy since regions are convex you can reach any place inside a region by following a straight line towards it).

The Visibility Graph models line-of-sight information, and is an alternative subdivision of the walkable space (from where in one region one can see someone in another region). The data from the Visibility Graph can be used to give the agent goals. Like: "find line of sight on an opponent" or "stay out of sight".

Navigation, especially in 3D environments, is a complex problem. Actually I'm writing my thesis on this very subject, comparing all these kinds of techniques.

Here are some links that you can use for ideas:

---
Tags: xna, c#, algorithm, path-finding
---


# Question
Title: How do I implement "prewarming" in particle engines?
How is prewarming in particle engines made?

I have a particle engine and need to support this, which is a feature I have already seen in Unity.

Is it done at compilation, like informations stored somewhere? or pre-processed at launch? or is there a way to simulate a particle system when it is created?

Considering it is time based, I don't see how I could for example simulate 15 seconds of life for a particle system without actually using 15 seconds

# Answer
I ended up with a simple idea that worked surprisingly good, so here it is:

In my particle engine, I generate `n` particles per gameloop tick, and running at 60 FPS we have, for an elapsed time `t` in seconds, `n * 60 * t` particles generated.

This could vary if your game isn't fluid and frames drop, but we assume it runs correctly.

Now what happens is that the prewarn function is launched once the particle emitter starts, and emits this number of particles. Then we have to simulate where they are, because they should have been all generated at different dates, when in truth they haven't.

All of this is done with a simple for loop (example in `JavaScript`):

```
particles.prewarm = function () {
    // FPS = 60, this.rate = number of particles per gameloop tick, this.life = life of a particle in seconds
    var particlesCount = (FPS * this.rate) * this.life; // Gets the number of particles to emit
    var timeUnit = this.life / particlesCount; // This is the amount of time between two particles for the duration of our simulation

    for (var i = 0; i < particlesCount; i++) {
        var p = this.emit(); // Emit a random particle

        // Here, we set the "birth" date of each particle at their simulated point in time
        p.birth = time.time - this.life + timeUnit * i;
        p.update (time.time - p.birth); // Here I call my particle's update with a special deltaTime which corresponds to the duration of the simulation for this particle
    }
}

```
> 2 votes

---
Tags: particles
---


# Question
Title: Animation Texture spread out when animation on 3dsMax
I have a 3d model of a human biped, i did the skeleton and attached it to my 3d model with a skin modifier. But when i move his arms a part of the trunk is comming too . Is it possible to fix this ?

# Answer
> 1 votes
Yes. Ensure that none of the vertices in the trunk are included in the bones controlling the arms. Check out the skin modifier documentation and how to either modify the envelopes you're using, or manually selected the vertices controlled by the underlying bone.

---
Tags: textures, 3dsmax, skeletal-animation
---


title: Scoring system (3 Variables)

text:
# Question
Title: Scoring system (3 Variables)
I'm writing a mobile game where the player has

1. a limited number of clicks to direct their avatar to the bottom of the map
2. into a bronze, silver, or gold basket
3. land on his/her feet, head, or side.

I'd like to take each of these into consideration when determining the score.

On level 231, the lowest possible clicks to get into the bronze is 2, silver is 4, and gold is 7, with a limit of 10 clicks.

So let's say the score is calculated like so:

* Basket: 1 point for bronze, 2 for silver, and 3 for gold.
* Landing: 3 for feet, 2 for head, and 1 for side.

That means the possible outcomes are:

* Bronze: 1, 2, 3, or 4
* Silver: 2, 3, 4, or 5
* Gold: 3, 4, 5, or 6

Now that's all good because I can make a 1 star 3, a 2 star 4, and a 3 star 5 or 6.

But now, the remaining clicks come into play: I originally wanted them to multiply the score. 2x for 1 click left, 3x for 2, and so on. That means getting a fast bronze is better than getting the harder-to-reach gold. Raising the base scores to 1, 2.5, and 6.25, respectively, messed up the other levels.

Does anybody has a solution I could try? I don't care if the points go into the hundred thousands. I want to reward players more for gold, with other elements to keep them interested and feeling accomplished after player a level.

Thanks!

# Answer
> 1 votes
If you use the baskets as multipliers, ie

* Gold: 4x
* Silver: 2x
* Bronze: 1x

No matter how you score the everything else, the biggest reward will always be for gold.

With your current landing score taken into account, the breakdown is thus:

```
      Gold    Silver  Bronze
Feet  12      6       3
Head  8       4       2
Side  4       2       1

```

Then, multiply the number of clicks *divided* by the maximum (or par) clicks, then multiply that by 1000 and drop everything after the decimal point.

```
basket * landing * (clicks/max) * 1000 = score

```

This is where spreadsheets come in handy.

# Answer
> 0 votes
Instead of operating off the minimum clicks to calculate a multiplier, you could have a par number of clicks for each basket. If the player gets in the basket under the par you can use that difference as your multiplier. For example, if it is 2 clicks minimum to get the bronze and 7 to get to gold, the par for each basket respectively could be set at 5 and 10. If the player get the bronze in 4 clicks it is a 2x multiplier. If they get the gold in 9 clicks it is a 2x multiplier. If they get the bronze in 3 clicks they would get a 3x multiplier, likewise, if they get the gold 8 clicks.

---
Tags: game-design, leaderboards, scoring
---


# Question
Title: How can I create a body with a hole in the middle?
I want to create a shape that looks like the black contour in this picture:

The shape must be empty in the middle(white surface). The white surface must not be part of the shape, just the black contour should be a shape.

How can I create such a shape?

I already tried it with the BayazitDecomposer, but it's not working. The BayazitDecomposer makes a shape of the entire picture(white surface+black contour).

**UPDATE:**

It's not working. I tried it with TriangulationAlgorithm.Delauny but it doesn't create the hole. You can see the result in this debug view picture:

My code:

```
List<Vertices> list = new List<Vertices>();
Vector2 _origin;
float _scale;

HoleSprite = Content.Load<Texture2D>("hole");
uint[] data = new uint[HoleSprite.Width * HoleSprite.Height];
HoleSprite.GetData(data);
Vertices textureVertices = PolygonTools.CreatePolygon(data, HoleSprite.Width, false);
Vector2 centroid = -textureVertices.GetCentroid();
textureVertices.Translate(ref centroid);
_origin = -centroid;
textureVertices = SimplifyTools.ReduceByDistance(textureVertices, 4f);
list = Triangulate.ConvexPartition(textureVertices, TriangulationAlgorithm.Delauny);
_scale = 1f;

//scale the vertices from graphics space to sim space
Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(1)) * _scale;
foreach (Vertices vertices in list)
{
  vertices.Scale(ref vertScale);
}

Body Contour = BodyFactory.CreateCompoundPolygon(world, list, 1.0f, BodyType.Dynamic);
Contour.BodyType = BodyType.Dynamic;

```

# Answer
> 1 votes
It looks like you need to try the Delaunay decomposer:

https://farseerphysics.codeplex.com/discussions/462917

https://farseerphysics.codeplex.com/SourceControl/latest#SourceFiles/Common/Decomposition/CDTDecomposer.cs

```
/// <summary>
/// 2D constrained Delaunay triangulation algorithm.
/// Based on the paper "Sweep-line algorithm for constrained Delaunay triangulation" by V. Domiter and and B. Zalik
///
/// Properties:
/// - Creates triangles with a large interior angle.
/// - Supports holes
/// - Generate a lot of garbage due to incapsulation of the Poly2Tri library.
/// - Running time is O(n^2), n = number of vertices.
/// - Does not care about winding order.
///
/// Source: http://code.google.com/p/poly2tri/
/// </summary>
internal static class CDTDecomposer
{...}

```

---
Tags: c#, farseer-physics-engine
---


title: 2D Outline shader in GLSL

text:
# Question
Title: 2D Outline shader in GLSL
I have a simple prototype with 2D worms-like destructible terrain. I use a trivial shader to discard pixels based on a mask.

```
varying vec2 v_texCoords;
uniform sampler2D u_texture;
uniform sampler2D u_mask;

void main()
{
    vec4 colour = texture2D(u_texture, v_texCoords);
    vec4 mask = texture2D(u_mask, v_texCoords);

    if (mask.a > 0)
        discard;
    else {
        gl_FragColor = colour;
    }
}

```

What would be a good and simple way to add few pixels thick black outlines to the terrain to make the carved parts look better?

I've researched something about edge detection algorithms, but my hunch says that such a fullblown thing would be kind of an overkill for this task?

I'm not after quality or high performance, but simplicity.

Thanks for any ideas.

# Answer
You should generate a distance field instead of a simple mask. In each pixel in the empty area, instead of storing 0 you store the distance to the closest pixel containing terrain. So you can return a black pixel if the value is for example between 0 and 0.1.

There are multiple algorithms to compute distance fields, so I let you find one that would suit your needs. You can find some implementations from the Wikipedia article I linked.
> 3 votes

# Answer
Here is a shader that does an outline in the simplest way that I know of. It just uses the dot product of the normal and light to cutoff colors based on the normal angle. Really, I suppose the view direction should be used instead of the light position but this gives control over the direction of the edge highlighting if you want that. There are 3 color gradients but you can take out the middle one so that you only have black(or dark brown) and the color output of your shader. You would just have to replace the line of code that I added a comment to with your '***colour***' variable.

If you want the transistion between light and dark to be anti-aliased then you may want to look for some examples on how to use the GLSL SmoothStep function.

Here's what it looks like using the code I posted

And the code.

```
//lightPosition = 6.6

```

//===========================================================================

```
uniform       vec4    light_POSITION_01;
uniform       mat4    mvpMatrix;
uniform       mat4    modelView;
uniform       mat4    lightMatrix;

attribute     vec4    position;
attribute     vec3    normal;
attribute     vec2    texture;

varying       vec3    normalPass;
varying       vec2    varTexcoord;

void main()
{

    normalPass             = (modelView *  vec4(normal, 1.0)).xyz; //there is no non-uniform scaling so modelView should be fine

    varTexcoord            = texture;

    gl_Position            = mvpMatrix * position;

}

```

//===========================================================================

```
uniform   sampler2D  Texture1;

uniform   vec4       light_POSITION_01;

varying   vec2       varTexcoord;
varying   vec3       normalPass;

          float      NdotL1;

 void main()
 {

    NdotL1                    =  dot(normalize(normalPass), light_POSITION_01.xyz);

    if(NdotL1 > 0.5)
    {
          gl_FragColor        =  vec4(1.0); //REPLACE THIS LINE WITH THE COLOR OUTPUT OF YOUR SHADER
    }
    else if(NdotL1 > 0.2)
    {
          gl_FragColor        =  vec4(0.43*.7, 0.4*.7, 0.31*.7, 1.0);
    }
    else
    {
          gl_FragColor        =   vec4(0.43*.3, 0.4*.3, 0.31*.3, 1.0);
    }

 }

```

I copied the code snippet from page 3 of a .pdf document that I found when I was searching for something that fits your description. Here's is the link. (The description I've added here makes it possible to find the .pdf again somewhere else using a search engine if this link goes down. And it's good to give credit where credit is due)

http://www.cs.rpi.edu/~cutler/classes/advancedgraphics/S12/final\_projects/hutchins\_kim.pdf

Location: Rensselaer Polytechnic Institute Computer Science dept.

Authors: Adam Hutchins and Sean Kim

Title: Advanced Real-Time Cel Shading Techniques in OpenGL
> 2 votes

---
Tags: opengl, glsl
---


# Question
Title: Is it acceptable to mix simple physics logic with gameplay logic?
In my 2D game I have a `PhysicsEngine` class. It currently does two things:

1. Called every frame to apply global forces on all entities (e.g. gravity).
2. Called by the `CollisionDetector` to do the physics part of collision response.

Currently, (almost) all physics-related logic goes through this class (including single-line things like `entity.applyImpulse(..)`).

My question is, from an OO design perspective: is it okay for an entity to do simple physics logic by itself, or should all physics logic (even simple things) go through classes dedicated to it?

For example: in my game, when spotting a collision the `CollisionDetector` notifies both entities to take care of gameplay related logic, and the `PhysicsEngine` to take care of physics related logic. Looks like this:

```
// on collision between entityA and entityB
entityA.handleCollision(entityB); // take care of gameplay
entityB.handleCollision(entityA); // take care of gameplay
physicsEngine.handleCollision(entityA, entityB); // take care of physics

```

But what if, for example when a `Missile` hits something I want to apply an impulse on the hit object? (In addition to the physics that always happens on collisions, in `PhysicsEngine`).

This is easy to do by simply adding about 3 lines of code to the `handleCollision()` method in `Missile`:

```
public void handleCollision(Entity entity) {
    Vector impulse = entity.getPosition().subtract(this.position);
    impulse.scaleBy(5);
    entity.applyImpulse(impulse);
    explode();
}

```

However, this would be putting physics logic in a 'gameplay' class. Should the `Missile` delegate to the `PhysicsEngine` in some way? Or is it okay that it would contain physics logic?

Another example I encountered in my game, is that when an entity 'fires' a `Missile`, I want to apply an impulse on the entity to push it backwards. Again, this can be done easily by adding 2-3 lines to the `fire()` method in the `Entity` subclass, but I'm not sure it's okay design-wise to mix gameplay and physics logic.

So, is it acceptable to have simple physics logic mixed with the gameplay logic? Or should I always separate the two?

How is this done in 'serious' games?

# Answer
It's not at all uncommon to see games where some game objects have non-standard physical behavior that have to be managed by a particular controller (e.g. a character controller).

These typically use the physics engine to the extant possible (from applying custom impulses all the way down to only using the collision detection of the engine) but otherwise side-step the engine's usual integration and kinematics in order to precisely control the behavior of the object.
> 2 votes

# Answer
Yep, this is fine for small programs. *Game play has to exist in some environment*, it's not this abstract notion that contemplates its own navel all day long, and in your case you've defined that environment as a physics simulation.

In a trading game the game play code must know about markets and values, and so on.

I would create helpers and intermediaries that stand between your game play code and the raw physics calls, if not only to isolate boilerplate and make the game code easier to read.
> 1 votes

---
Tags: architecture, oop
---


# Question
Title: Bad pixels on shader when loading cached binary programs
I have been trying to cache binary shader programs in my game and load them accordingly using "glGetProgramBinaryOES" and "glProgramBinaryOES" respectively.

I was successfully able to cache and load the programs but there is one problem that can be seen in some of the shaders. The problem is that SOME pixels of the object that uses that shader appear black / white and keep flickering.

These are heavy shaders and I cannot skip their caching. Any help ?

Edit:

1. I compile and store the shaders on the device itself. So device/GPU dependency is taken care of.
2. I recompile the shaders on any new OS DLC, so software update is taken care of.

The white spots in the image below show the glitch that i am encountering.

# Answer
> 2 votes
It is possible that your issue may be due to the lack of use of the *invariant* qualifier in your shaders. Quote from the book *OpenGL ES 2.0 Programming Guide*:

> There is a keyword introduced in the OpenGL ES Shading Language `invariant` that can be applied to any varying output of a vertex shader... The issue is that shaders are compiled and the compiler might perform optimizations that cause instructions to be reordered. This reordering means that equivalent calculations between two shaders are not guaranteed to produce exactly identical results. This can be an issue in particular for multipass shader effects where the same object is being drawn on top of itself using alpha blending. If the precision of the values used to compute the output position are not exactly identical, then artifacts can exist due to the precision differences.

So I'd recommend that you check your use of `invariant` and add it to `gl_Position` and others if not already doing this.

You can make `gl_Position` invariant with:

```
invariant gl_Position;

```

And any other user declared variable:

```
varying vec2 texCoord;
invariant texCoord;

```

Or you can even enable it globally with

```
#pragma STDGL invariant(all)

```

Though this last way may not be widely supported.

# Answer
> 1 votes
Have you verified that all variables used are initialed before using them? Using a variable that you have not yet assigned values to can cause flickering. For instance, if you have a variable that is created like this:

```
vec4 secondaryColor;
vec4 color = vec4(0.1, 0.1, 0.1, 1.0);
void main()
{
    color += secondaryColor; // and then try to use it like this
    ...
}

```

The variable ***secondaryColor*** will only contain garbage data unless you give it some value before adding it to ***color***. This is the first thing I look for when I see something like this happen.

Duplicate geometry could cause flickering because of z-fighting.

If the camera clipping is spread out too far:

```
near = 0.001
far  = 10000000.00

```

this is also likely to cause z-fighting.

So far as pre-compiled shaders go, I have no experience with them. As far as I understand it, they prevent you from taking advantage of optimized driver updates since they were compiled with older drivers. That is something I read in an older nVidia document. It recommended that we don't use them unless there is a very good reason for doing so.

Then there are some other theoretical problems. You might not be able to take advantage of bug fixes.

I also imagine these shaders compiled for one GPU could have problems if you run them on GPUs made by a different manufacturer... Unless I misunderstand what you are doing with this.

---
Tags: opengl, shaders, glsl, opengl-es2, fragment-shader
---


title: SDL Surface clipping mask

text:
# Question
Title: SDL Surface clipping mask
I am creating a GUI for my game, so I use some buttons like  . So you can see it is only text surrounded by a rectangle. But I currently use a huge png image with all the buttons I need arranged as I want it, it is really inefficient, so how can I upload a single smaller image of the rectangle, a sample of the gradient I want and use SDL\_tff to create a surface. Say: I copy the rectangle and the text in an SDL\_Surface, it should have two colors (black and white), now make white pixel transparent and black pixels to be replaced with the gradient to create the buttons and place them using SDL\_Rects.

# Answer
You can start with your gradient texture and render your texture to a surface where you want your button to be. You can manually apply the gradient by only copying over the pixels from the gradient map onto the destination where the destination pixels have alpha (or multiply the two).

Note, when using GL/DX, you can use the stencil buffer (http://en.wikipedia.org/wiki/Stencil\_buffer) to apply a mask to a render target and then render your gradient over the screen:
Create a new render target to a texture, render the font onto the stencil buffer (usually through an intermediate texture), draw the gradient on the render target, apply.
> 1 votes

---
Tags: sdl, gui, c
---


# Question
Title: How can I play an RTSP video stream in Unity3D?
I want to play an RTSP video stream on a `Texture2D`. The stream is coming from an IP camera and is encoded with *H.264*, *MJPEG* or *MPEG4*.

I know about VLC's libraries, ffmpeg, direct show, media foundation and such, but how do I connect them to Mono develop?

# Answer
> 2 votes
Well this is not a minor task. Basically you need to build a streaming server that supports RTP and also RTSP if you want playback options, or use an existing streaming solution; ffmpeg has one, but unfortunately it doesn't work on Windows. If you plan to use ffmpeg you also need to make Unity connect with native code dynamic libraries which I am not sure if all versions support it.

Building a streaming server needs a lot of work, but it is not really hard. You need to start by understand RTP which is used for data transfer and RTSP which is used for negotiation and playback options.

You can read the packets via sockets, sniffing, or if the camera SDK gives you the packets. Once you get the packets, often given as a blob of `char*` and a `length` buffer, you need to start by segmenting the packet into UDP, RTP/RTSP and RTP payload. Once you extract the RTP payload you can pass it into an ffmpeg decoder which will return a decoded image usually encoded as RGBA once you get there you need to march your image data into Unity's managed code and pass it to a texture.

Well if that sounds too much work, there is an open source library that do that for you, it's called live555 note that I don't know much about it but it can get the job done.

# Answer
> 1 votes
There is also net7mma.

It has a c# rtsp client and server and also has implementations of rtp and rtcp.

There are sdp classes and stream classes for dealing with certain types of packetization and depacketization.

The library also works in mono and has no external dependencies.

---
Tags: c#, unity, graphics, video
---


# Question
Title: Why is anti aliasing not being applied to my 2D objects in Unity?
I am drawing 2D objects in Unity. Some of these objects are drawn using the standard sprite method that is built into Unity. Others are computed as distance functions in a shader.

In both cases I can't get Unity to apply anti aliasing despite the setting being set.

Is there an extra step that I am missing that is required to get anti aliasing to work properly?

Would it be better to implement my own form of AA in a shader?

# Answer
Multisampling AA (MSAA) is only capable of multisampling the geometry edges. If you want your sprites to be anti aliased, you should use a post process AA, like FXAA for example.
You can also use bilinear filtering to smooth out the texture itself (it seems that you are using point/nearest filtering).
Having multiple mip-maps for your textures can also reduce aliasing if your texture is minificated (for example if it is in the distance). Use trilinear filtering if you have mipmaps, it will blend your mipmaps seamlessly.
> 4 votes

---
Tags: unity, sprites, antialiasing
---


title: Is video compositing feasible?

text:
# Question
Title: Is video compositing feasible?
I've been considering the idea of a game client that acted as a video compositor, only drawing, by itself, the terrain, the characters... deferring other graphic elements to separate processes. For instance, a health bar would be drawn by a separate process with its own address space and graphics context. Even if the mentioned bar could be drawn from another thread of the main process, or perhaps even from the renderer thread, this model would increase security (*I believe it is already done in Chromium*), ease development and the introduction of trivial and more complex addons, as well as make the whole game client, with all of its brethren, more balanced across threads/cores.

Please, note that the heavy rendering (i.e. terrain, characters,...) would be drawn from a thread of the main process on the entire window, so it wouldn't have to be composited. The compositor thread would then draw the contents of clients' graphics buffers on top of what the renderer thread drew, in their respective position.

Also, note that this is only a personal project, and that I have never developed a game. My target is Linux with Mesa. As for the IPC part, I had thought about Wayland.

---

### Question(s)

* Would compositing, and having multiple graphics contexts, degrade performance seriously?
* Is this already done in any game client?

P.S.: I think *World of Warcraft* also uses addons, although I think they're in Lua and parsed from the main thread, so no compositing happens there.

# Answer
> 1 votes
A context in OpenGL represents an individual drawing surfaces, such as a viewport in an application. It is impossible to use multiple context to draw to the same surface. If you would like separate system, such as a terrain renderer and a GUI to draw overlapping each other you will need to use the same context.

Separating work into multiple threads has no benefit from a security context, and to be honest the only security context in games is related to online play which is often solved by letting the server make authoritative decisions. You can separate game code into threads, but this is a very complex process which needs to be synchronized each frame (as the GPU can only handle on request at a time). A novice or even moderately experienced game engine programmer will probably end up with a slower game engine and not a faster game engine when using multi-threading so I would advice against it. However, for a good reference see this article

What you might be looking for, and what you should do, is separating functionality and data from other functionality and data. In games we often use the entity-component paradigm for this. See this list of articles and the answer to this question for more information. (It helped me a lot).

Note that if you're not too experienced in game development I advice to use a very simple forward-rendering technique where you just let each system do its job in turn. Be pragmatic!

# Answer
> 1 votes
Games using Chromium Embedded Framework or Awesomium do something like these. The Chromium code runs all "renderers" in sandboxed separate processes and then composites the final view in the "host" process.

This isn't quite down to the level of having each element in a separate thread, but it does illustrate that compositing from separate threads can be done in real-time for games. One render thread vs many render threads shouldn't adversely affect performance much.

That said, I feel this is a fool's errand outside of the use case of using an existing tool like Chromium. Developing this kind of IPC system, sandboxing it properly, and making it all run efficient is *hard*. It also have very questionable utility. I contest that it'll make development easier; what's far more likely is that adding trivial changes is going to constantly require lots of reworking to the IPC layer, bug fixes, and complicated architectural changes.

There's also not likely going to be a lot gained from the "better parallelism." There's a point at which parallelism actually helps. The rendering of a health bar is not it. You want to render as much of your UI in a single call to the GPU as possible and parallelize the GPU hardware. Splitting up simple things into processes adds a ton of overhead at the CPU level and then negates your ability to parallelize the GPU well.

Modularizing your code and making good use of parallelism on the CPU *where it's beneficial* is achieved in far better ways than what you're proposing.

---
Tags: c++, software-engineering, plugin
---


# Question
Title: Texture2DArray in Directx11 with different formats
I'm trying to create a texture2DArray from multiple of images, each of which has different formats, and I got the following error from the DirectX11 debug layer.

```
D3D11 ERROR: ID3D11DeviceContext::CopySubresourceRegion: Cannot invoke CopySubresourceRegion when the Formats of each Resource are not the same or at least castable to each other, unless one format is compressed

```

I want to ask you there is any way of creating a texture2d array in Directx 11 with different format?

# Answer
No can do; the format and array size are both members of the D3D11\_TEXTURE2D\_DESC structure, so an ID3D11Texture2D will always have the same format for any value of array size.

Depending on how you *use* the texture, you could create different shader resource views specifying subranges of the full array, provided the SRV format is compatible with the texture format. Generally that means you'd use a TYPELESS format for your texture and a typed format for your SRV; e.g a textere with DXGI\_FORMAT\_R32G32B32\_TYPELESS could use any R32G32B32 typed format (\_FLOAT, \_UINT, \_SINT).
> 3 votes

# Answer
As noted already, you cannot create a TextureArray with different formats or sizes. They all must have the same for both.

That said, the binding limit for simultaneous textures with Direct3D 11 and Feature Level 10.0 is 128, so you could just bind up to 128 individual SRVs in a single pass. TextureArrays already require Feature Level 10.0, and Feature Level 9.x can only bind up to 8 textures at a time.
> 0 votes

---
Tags: textures, directx11
---


title: Tiles touching all of same color check

text:
# Question
Title: Tiles touching all of same color check
I'm currently having a problem that has stopped my productivity for quite a while. I need to check if all tiles of a color is touching each other for each color like this:
I have all my code for moving the tiles around and switching levels, but i can't seem to work out a proper algorithm that checks if the level is complete(see image above).

The base of my code is the Tile\[\] that holds information about all these tiles.

The Tile class looks like this:

```
public class Tile {
int x = 0;
int y = 0;
int type = 0;
boolean checked = false;

//SETTERS AND GETTERS FOR ALL VALUES
public void setX(int v){
    x = v;
}
public int getX(){
    return x;
}
public void setY(int v){
    y = v;
}
public int getY(){
    return y;
}
public void setType(int v){
    type = v;
}
public int getType(){
    return type;
}
public void setChecked(boolean v){
    checked = v;
}
public boolean getChecked(){
    return checked;
}
}

```

The "type" is the color of the tile.
Should mention that the Tile\[\]'s length is 25 and that each tile has got a X & Y from 0-4.
I need something that can return me a boolean\[\] finishedColors so i can check if it's done.

All kinds of help is surely welcome!

# Answer
Essentially a series of flood fills - one for each cell in the grid, but skipping over any you've already visited, and dropping out early if you find a cell not connected to a group you've already flood-filled/gathered but of the same type as that group.

Written blind, so please excuse any code typos or holes; highlight them in a comment and I will amend. Also assuming a 2D array storing tiles, `width` and `height` variables detailing dimensions. With this algorithm, you don't need a Tile class at all - just a 2D array of ints would do just fine.

```
int IndexFromXY(int x, int y)
{
    return (y * width) + x;
}

void GatherConnectedTilesOfType(int type, int x, int y, List<int> visitedTiles)
{
    if ((x < 0) || (x >= width)) { return; } //Trivial succeed when out of bounds
    if ((y < 0) || (y >= height)) { return; }

    int index = IndexFromXY(x,y);
    if (visitedTiles.Contains(index))
    {
        //We've already checked this tile, assume that if we're still iterating, it succeeded last time
        return;
    }

    if (tiles[x][y].Type == type)
    {
        visitedTiles.Add(index);

        //Check adjacent tiles
        GatherConnectedTilesOfType(type, x+1, y, visitedTiles);
        GatherConnectedTilesOfType(type, x, y+1, visitedTiles);
        GatherConnectedTilesOfType(type, x-1, y, visitedTiles);
        GatherConnectedTilesOfType(type, x, y-1, visitedTiles);
    }
    else
    {
        //Don't proceed to adjacent tiles, this one doesn't match
    }
}

boolean IsComplete()
{
    Map<int, List<int>> connectedTiles = new HashMap<int, List<int>>();
    for (int x = 0; x < width; ++x)
    {
        for (int y = 0; y < height; ++y)
        {
            int type = tiles[x][y].Type;
            if (connectedTiles.containsKey(type))
            {
                //We've already found at least one contiguous segment of this type,
                // so if this tile isn't in that segment, the type has more than
                // one segment of that type
                int index = IndexFromXY(x,y);

                List<int> connectedTilesOfThisType = connectedTiles.get(type);
                if (!connectedTilesOfThisType.contains(index))
                {
                    return false; //More than one contiguous segment with this type
                }
                else
                {
                    //Continue on - we've already covered this cell in a Gather
                }
            }
            else
            {
                List<int> connectedTilesOfThisType = new ArrayList<int>();
                GatherConnectedTilesOfType(type, x, y, connectedTilesOfThisType);

                connectedTiles.put(type, connectedTilesOfThisType);
            }
        }
    }
    //If we get this far, we only found cells which were contiguous with cells of the same colour (and connectedTiles details the various sets)
    return true;
}

```
> 3 votes

---
Tags: java, 2d, android, tiles
---


# Question
Title: More than 8 lights without deferred shading / lighting
I want to know if there is any technique (efficient) to use more than 8 lights in a scene made with OpenGL and GLSL. Without making use of deferred shading / lighting.

I have not implementadon these techniques for their limitations and not being able to use transparency or antialiasing.

If there is a good alternative, describe it with an example.

I use OpenGL 2.0.

Thank you.

# Answer
> 2 votes
the limitation you're finding is somewhat related to the history of OpenGL. Prior to OpenGL 3, a fixed-function pipeline was employed. This roughly means than OpenGL would execute the exact same processing on all vertices. The only way you could modify the output was by changing the input arguments of the pipeline (vertex positions, colors, light properties, ... ). This means the OpenGL API contained a lot of functions to change these input parameters. In specific, to set the properties of lights, the OpenGL provides 8 different lights to change the properties of.

In modern OpenGL, the fixed-function pipeline was replaced by the programmable pipeline. This roughly means that you can program the pipeline to perform any kind of processing of the vertices. You can use widely different processing for different textures/materials you're trying to emulate. These programs are programmed as "shaders". The "negative" side of this, is that no functionality is provided for you. You start of with an empty pipeline and need to write it from scratch. The minimum you need is atleast a vertex shader and a fragment shader. The advantage is, that you can program the pipeline to your liking. You could for example pass an array of 20 lights (rather than the default of 8 lights in fixed-function pipeline OpenGL). So, a solution would be to switch to a more modern version of OpenGL.

However! In most cases you won't need more than 8 lights. Lighting is fairly complex to calculate. If you want excellent looking lights, you'll likely use per-pixel lighting (phong shading) in the vertex shader. For every additional light, you need additional calculations per pixel. The more lights, the more processing time, meaning you'll notice slowdown.

The solution is clever disabling of lights. In modern games, only a few light are active at a time. Lights are disabled and re-enabled based on camera position, occlusion and more. Consider for example point lights. The intensity of the light reflecting of your objects lowers the further away the light is. This is called distance attenuation. At a certain distance, you will not notice the influence of the light anymore. It is thus safe to disable the light, freeing up a lot of processing time (calculations are done for every single fragment!) without visual impact. Another solution is to approximate multiple light sources by a single source. For example, consider having a swarm of 100 fireflies swooping across your game map. You can safely approximate these 100 light sources by a single source in the center of the swarm. The summed contribution of the 100 individual lights will be almost indistinguishable from a single-source approximation.

In summary: if you really want more than 8 lights, take a look at modern OpenGL (OpenGL 3+) and write your shaders to accomodate this. However, more than 8 lights are almost never required. Consider enabling and disabling lights (eg. enable only the 8 closest lights to the player/camera in every frame). Try to approximate multiple close lights sources by single sources.

As you already know about GLSL, you might find modern OpenGL very interesting. While it's more difficult to write the entire shader pipeline from scratch, you'll be happy once you're fluent in it as it offers you a lot of power in graphics processing!

---
Tags: opengl, glsl
---


# Question
Title: which quarter of a triangle the point is in
I've got a world made out of squares. The square are devided in four triangles like this: The corners have their heights stored in a 2D array and the center height is the average of the corners. To calculate the players Y-coordinate I have to know in which triangle he is standing on. How can you calculate in which quarter the player is by the X and Y coordinates?

EDIT:

My algorithm:

```
bool h1 = false, h2 = false;

if(posZ < posX - posZ) //something weird going on here
{
    h1 = true;
}
if(posX < posZ - posX) // and here
{
    h2 = true;
}
if(h1 && h2)
{
    triangle = 0;
}
if(h1 && !h2)
{
    triangle = 1;
}
if(!h1 && !h2)
{
    triangle = 2;
}
if(!h1 && h2)
{
    triangle = 3;
}

```

This algorithm tries to find in which triangle you are. There is something wrong in that math.

# Answer
We can find out which corner the player is in by checking whether their position is above or below the two diagonals through the square.

Let's assume for a moment that the center of your square was at the coordinate position `(0,0)`, and let's start with the diagonal that goes from the lower left to the upper right. When would a point be exactly on this line? Obviously when its `x` and `y` coordinates are the same.

Therefore, if `x < y`, the point is above the diagonal, and if `y < x`, it is below the diagonal.

*(Important: these tests assume the x-axis to point right and the y-axis to point up, like in maths, not like in standard 2D graphics.)*

With a similar reasoning we can check the other diagonal, the one from the upper left to the lower right. A point is *on* that line if `-x == y`.

Therefore if `-x < y`, the point is above the diagonal, and if `y < -x`, it is below the diagonal.

But what if the diagonal's center point is not at `(0, 0)`? Well, then we just translate the player's position so that we can fall back to the above case. In order to move the square so that its center ends up at `(0, 0)` we have to translate it by the reverse vector from that point to its center. And we will have to move the player's position by the same amount, of course.

Together, we get the following algorithm.

```
tx = px - cx              // translate the player's position
ty = py - cy              // by negative vector to square's center

if tx < ty then           // above diagonal #1
    if -tx < ty then      // + above diagonal #2
        // top corner
    else                  // + below diagonal #2
        // left corner
    fi
else                      // below diagonal #1
    if -tx < ty then      // + above diagonal #2
        // right corner
    else                  // + below diagonal #2
        // bottom corner
    fi
fi

```

Note, however, that you should make sure that the player's position is inside the square in the first place. That's something the above algorithm doesn't check.

As an exercise, what does the algorithm do when the player's position is exactly *on* one of the two diagonals? :-)
> 2 votes

# Answer
Do you know for sure that the player's position is actually inside the square? If so, the following might work for you.

If you translate the player position (p\_x, p\_y) so that the center of the square (c\_x, c\_y) would end up in your coordinate system's origin, and then rotate it by 45 degrees around the origin, you can simply check the four corner by less-than/greater-than zero tests:

```
  testX  |  testY  | Corner
============================
   < 0   |   < 0   |   #1
   < 0   |   > 0   |   #2
   > 0   |   < 0   |   #3
   > 0   |   > 0   |   #4

```

You have to handle the `=` case, too, of course, which ever way you like.

Here is how you get from the player's position p to the test coordinates which you can use in the above table:
> 0 votes

---
Tags: geometry, c
---


# Question
Title: Reducing APK File Size by using JPG instead of PNG for game background images
I've just finished my (openGL ES 2.0 Android) game and it's almost ready for Alpha-testing.

When I export the application to an APK File, the file is taking up 16MB and I would like to reduce this as much as I can.

Here are some points about what the project contains and what I've tried to reduce the size already:

* 222kb of Ogg Vorbis files used for Sound Effects
* 1 x MP3 file at 5.59MB (128kbps Bitrate)
* 4 x sets of PNG files used for textures (XHDPI, HDPI, MDPI & LDPI - I'm not using XXHDPI)
* Just over 1MB of code

What I've tried thus far to get where I am:

* I've optimised the PNG files using Optiping
* I've applied ProGuard to my code before exporting, this didn't really help by much as 99% of my app is resources.

So my question is, is there really much else I can do to reduce the size of the APK? I was thinking about maybe using **JPG** format source files for my **Background** OpenGL textures instead of **PNG** \- anyone have any experience with this? Does it hurt performance at all? I can see that it would make quite a difference - my atlas of backgrounds in PNG format for XHDPI is 1.7MB - and a 90% compressed JPG comes in at around 650KB. I'm just not sure if it's a good idea as everyone always advocates PNG \> JPG.

Any pointers from personal experience would be helpful & also if I've overlooked anything other than using JPG's.

# Answer
If you use an alpha-channel for your assets (which is most likely), then you're out of luck with vanilla JPEG anyway.

PNG provides a pretty good compression while also being lossless and a format with alpha-channel. There's not much you can improve there, except using a specialized GPU format such as PVR or similar which will allow you to specify different bit-depths per channel. But the real strength of a format like PVR is that it will consume less GPU memory, **not** the reduced disk-space requirement.

All that being said: I think you're overreacting. 16MB is *nothing* for a game and there's really no point in reducing the file-size to shave off some MB. It will only make your workflow more tedious in the long run.

**Update:** Another approach would be to ship your game with just one set of assets (eg. MDPI) and then load the higher-resolution ones on-demand. For example you could detect the presence of an HDPI display and show a dialog to the user, asking him if he wants to download the high-res assets.

Of course this makes your code and also your app-deployment more complicated. I would only suggest this approach if it's impossible to stay within some file-size boundaries imposed by others (eg. the iTunes AppStore has a 100 MB limit on downloads over cellular-networks).

Google has already a mechanism for this in place, which is called APK Expansion Files. So if your app gets larger than 100 MB (the limit for Apps in the Google Play store), then you should move your high-res assets into APK Expansion Files, which will allow additional downloads up to several GB (2 x 2GB at the time of writing this).

If you're certain you'll hit the 100 MB threshold, you could already start moving your hi-res assets into an expansion-file. Otherwise just pack everything into one APK.
> 3 votes

# Answer
First of all I'd start with the MP3 file. If you've got Ogg Vorbis already, why having a MP3 as well? Especially 128 kbit/s on a mobile device sounds excessive.

The MP3 is taking like 1/3 of your assets, with the PNG files being significantly smaller.

As such I'd start trying to convert the MP3 to Ogg Vorbis. I'd expect the file to become smaller. Also let it downsample to 32 or 64 kbit/s at most (same applies for the other sound effects IMO).

Also are you sure you need all the different resolutions of your images? Do they scale that bad? Especially the background might scale far better than any tiles or sprites.
> 2 votes

# Answer
JPG is a photo format. It's a very efficient format for real-world images. PNG is a successor to GIF. It's a very efficient format for artificial images.

The reason is that the compression algorithms differ. The compression for both works by assuming some data is more common than others, and optimizing for that. Photo's have lots of smooth gradients, and very few hard edges. A diagram, on the other hand has many lines with sharp edges and no smooth gradients (the same applies to text rendered as image). Thus PNG does well on sharp edges, and JPG causes visual artifacts. But on smooth gradients, JPG excels.

Your textures may be closer to pictures, depending on how they're generated.
> 1 votes

---
Tags: android, opengl-es2, assets, png
---


# Question
Title: What are mental ray shaders and can I use them in my own game?
I'm using the FBX SDK to import and display FBX models in my OpenGL app. It works fine so far with a simple phong shader and displays basic models.

However I have some FBX models that have custom (Mental Ray) Arch & Design materials. Can I render these models with such materials in my app?

My (completely noob) understanding of how this works is that the Arch & Design thing is a shader. A graphic designer edited some data fields, and the way the model is rendered is that such data is passed to the Arch & Design shader during rendering, and the shader takes care of it (ie does all the lighting calculations etc).

Is it possible for me to use that flashy Arch & Design shader in my app, so I manually parse the FBX model and send the data fields to the shader? How do I get hold of it?

Any clarification will be appreciated, you can probably tell that I'm somewhat confused.

# Answer
mental ray is a stand-alone 3D renderer. It's primarily application domain is film and TV. As a renderer, it supports a concept of "shaders" as functions that compute lighting effects. However, these are not *mechanically* the same shaders that you'd use in OpenGL or D3D. They are built in their own language, tied to the mental ray lighting and renderer engine. Further, the renderer isn't designed for real-time use.

Consequently it is not possible to use the shaders directly in your own game or application. You will need to manually re-implement the effects you are after (or find somebody else who has and use their implementation), probably making tweaks and adjustments for performance.
> 2 votes

---
Tags: shaders
---


title: How can I make new strategies viable?

text:
# Question
Title: How can I make new strategies viable?
I am making a 2D platformer where the player has to reach the end of the level as fast as possible. I would like the player to be able to find new ways to reach the end of the level faster.

Making multiple path is not enough, in my opinion, because the shorter one will be easily findable and the others will become useless. I thought that maybe I should add abilities to the player to increase the number of possibilites.

I would like the player to be able to find strategies I have not thought about. For example players who are doing speedruns find new path and strategies to beat a game faster. I would like to help the research of new strategies. I would like to make new strategies possible even if I have not specificaly thought about them.

My question is, how can I make it possible for the player to make up new strategies ?

# Answer
This is almost paradoxical, because if you focus too much on "planning" for alternative routes you ultimately tend towards constricting the number of available routes to *exactly* those you've planned for, achieving a pale semblance of your goal instead.

There is some level of specific design work you may need to do to facilitate this (for example, rooms in Rogue Legacy must have explicit extra paths added for heroes with dwarfism traits, levels in Fallout 3 often have lock-picking and computer-hacking paths to achieve some goal); you just don't want to take this so far as to end up always having "the path for this ability," and "the path for that ability."

The abstract techniques you should employ to allow for multiple paths and strategies in a game align closely with those you'd probably want to employ to foster replayability in general. This includes things like designing for composability:

* give a player (eventual) access to many abilities, each of which do a relatively small thing on their own, and possibly have a small downside
* approach the design of your gameplay space in terms of verbs and nouns: simple things that can be done, and simple things that can be operated on
* don't artificially restrict those combinations, and let your playtesters explore, and listen to their feedback when they say "hey, I tried to use X to do Y here and I thought it would work, but it didn't."
* if possible, design levels and areas to be true to their real-life analogues; players can relate to real spaces and their own internal fantasies of being (for example) a crazy parkour acrobat traversing an actual urban landscape, or a daring Lara Croft or Indiana Jones-like spelunker. Forming gameplay spaces around familiar structures allows players to more easily project those fantasies into the game and see options for exploration.

For example, grenade-hopping and the like is a direct consequence of two simple factors:

* explosions push things around in relatively physically-accurate way
* the player is tougher than most other things

These combine to make grenade-hopping a viable option, even if it wasn't *designed* into the game (by contrast, some sequence-breaking-enabling things, like the foam gun in Shadow Complex, *were* specifically designed into games for sequence breakers).

This sort of thing is a far more organic then premeditated process. Keep building simple composable gameplay elements and then trying them together yourself or through playtesters. See what they come up with; that may inspire you to add other abilities to further compliment a strategy you see emerging ("emergent gameplay" was the 90s buzzword for this sort of thing, incidentally). Or it may necessitate you adding downsides to abilities to complicate the exploiting of some mechanic you feel trivializes the game too much, or something.
> 8 votes

# Answer
The kind of gameplay experience you are talking of is a result of glitches and chaos in an environment that is too complex to allow for complete testing of every possibility. The more complex the world and set of abilities you create, the more likely it is there are paths you haven't thought of. Even if there is an infinite number of ways, there are always some ways that are superior to others. A game's speedrun can only be improved up to a point and from there it's very hard to make a tiny improvement.

Consider leaving in bugs like an enemy attack that knocks the player character far away allowing you to traverse over chasms you wouldn't be able to without getting hit. Another example would be that getting hit leaves you invulnerable for a second or two and you are then able to go through things like spikes that would normally instakill you.

The way to create gameplay that is unpredictable is by leaving in buggy behavior, giving a set of powers that you haven't fully tested and nerfed to limit the player and letting the player / monster /environment interaction result in cool things like very strong knock back or temporary invulnerability. If all that fails you can leave in bugs like players being able to phase through walls at certain speeds.
> 3 votes

# Answer
One way is the Quake 3 way. Based on a bunch of what were originally bugs in the code, you get all sorts of weird interactions.

* Plasma climbing.
* Grenade jumping.
* Rocket jumping.
* Strafe jumping.
* Grenade/rocket jump (youtube video of me doing one of these: https://www.youtube.com/watch?v=i6rqumD-9Hk)
* Overbounce (never learned to do this one).

If your player has access to a load of different ways to move, they will learn to combine them in weird ways to get through the level in new ways. Check out stuff like Quake Done Quick to see this in action.
> 1 votes

---
Tags: game-design, platformer
---


# Question
Title: Manually writing a dx11 tessellation shader
I am looking for resources on what are the steps of manually implementing tessellation (I happen to be using Unity CG, but any help is appreciated).

Today it seems that it is all the rage to hide most of the gpu code far away and use rather rigid simplifications such as unity's SURFace shaders. And it seems useless unless you're doing supeficial stuff.

A little background: I have procedurally generated meshes (using marching cubes) which have quality normals but no UVs and no Tangents. I have successfully written a custom vertex and fragment shader to do triplanar texture and bumpmap projection as well as some custom stuff (custom lighting, procedurally warping the texture for variation etc).

I am using the GPU Gems book as reference. Now I need to implement tessellation, but It seems I must calculate the tangents at runtime by swizzling normals (ctrl+f this in gems: `<normal.z, normal.y, -normal.x>`) **before** the tessellator gets them (during some sort of per-triangle geometry pass, which comes before vert and frag).

And I also need to keep my custom vert+frag setup (with my custom parameters/textures being passed between them) - so apparently I cannot use surface shaders.

Can anyone provide some guidence?

# Answer
The Direct3D 11 Tessellation stage is designed to be a bit generic so that applications can implement different approaches.

There have been a number of presentations on this topic over the years at various conferences. I have links to them at this blog post.

This topic is covered in a number of Direct3D 11 books. See this blog post for a list of recommendations.

The legacy DirectX SDK's Direct3D 11 Win32 desktop samples are available here and here.
> 1 votes

---
Tags: directx11, procedural-generation, fragment-shader, tessellation, geometry-shader
---


title: Animation State

text:
# Question
Title: Animation State
Well i'm not entirely sure how to manage animations. I've looked at a few solutions, havok and ue4, which seem to use state machines but the states and their interactions are created using external tools with some really nice debugging features. Obviously i don't have the resources to build something that complex. So i was wondering how to manage animations and their states in code without creating a bunch of spaghetti.

# Answer
> 1 votes
Well since you spaghetti so kindly, I personally use an enumeration for which animation state the character is in. The states I use for a 2D platformer are simply RUN, IDLE, JUMP\_RISE, and JUMP\_FALL. Each animation state corresponds with a set of 8 sprites, which are loaded to my camera function, which changes what the player looks like on screen. Are you looking more specifically at 2D animations or 3D? Both function on essentially the same principles, but you may require a 3rd party program for 3D animations depending on your skill level.

---
Tags: animation
---


# Question
Title: How can I profile the speed of my vertex and fragment shaders separately?
I'd like to know how I can check to see if either my vertex or my fragment shader is a bottleneck in my rendering pipeline.

I've read about using `glQueryCounter` with the `GL_TIMESTAMP` target to get clock checkpoints between OpenGL commands, but these don't distinguish between different types of shaders.

For example, if one frame on the GPU took 8 ms to render, can I tell that the vertex shader took 7 ms and the fragment shader took 1 ms?

# Answer
Vertex and fragment shaders run concurrently, not sequentially, and the GPU automatically load-balances between them, so it's not possible to meaningfully assign specific timings like 7 ms for one and 1 ms for the other.

However, you can do a simple experiment to measure where the bottleneck lies: set the view-projection matrix to all zeros for all your draw calls. This makes all vertices output zero for their positions and makes all triangles degenerate; it therefore short-circuits all rasterization and fragment shading, while keeping all the vertex shader work (the shader compiler can't optimize anything away, since it doesn't know the matrix will be set to zero at runtime).

When you measure performance with the matrices zeroed, you'll be seeing the amount of time needed to run just the vertex shaders, without any concurrent rasterization or fragment shading work in the GPU. You can then compare this to the amount of time needed for ordinary rendering for each pass. If the two times are similar, the pass is probably highly vertex-bound; if the zeroed-matrix rendering is significantly faster, it's probably pixel-bound. It's also possible to get an intermediate result, indicating that the work is split about evenly between the two.
> 12 votes

---
Tags: opengl, shaders, performance, profiling
---


title: Unreal Engine 4 -- Casting

text:
# Question
Title: Unreal Engine 4 -- Casting
I am currently developing my first classes in Unreal Engine 4. Coming from using UScript extensively, I'm getting a little bit confused by how typecasting works in pure C++. More specifically, class/object casting.

I am currently putting together a switch statement in MyCustomGameMode which calls upon MyCustomPlayerController for MyCustomPlayerControllerVariable.

The function in question that I am overriding is this one: `virtual UClass* GetDefaultPawnClassForController(AController* InController);`

Currently I'm trying to call the variable with the following line of code, which I know is incorrect, but I'm not sure why:

```
Cast<MyCustomPlayerController>(InController).MyCustomPlayerControllerVariable

```

I am interested in casting the "InController" to MyCustomPlayerController but `Cast<MyCustomPlayerController>(InController)` doesn't seem to work, what am I doing wrong here?

# Answer
> 3 votes
`Cast<Foo>` returns a `Foo *`. So the proper way to access your variable should be:

```
Cast<MyCustomPlayerController>(InController)->MyCustomPlayerControllerVariable

```

---
Tags: unreal
---


# Question
Title: Why is my application getting more CPU usage while it's halting the operation
I have a question about the way OS gives CPU time to the applications. Usually when I render my scene with a single object in it I get ~8% CPU usage, but when I stop the framework for further process while my window has lost focus I see that my application has a ~50% CPU usage. Now, I'm a little bit confused about this behavior because supposedly I should get no CPU time at all.

The pseudo code is something like this:

```
while(open)
{
  // Window
  window->update();

  // Freeze when we have no focus
  if (freeze) continue;

  // Physics, Input, Render ...
  do_the_stuff();
}

```

The situation that I'm talking about is when I set `freeze` to true and just process the window messages. It means there is only one job to do per frame.

# Answer
In your loop you probably have vsync on, or other stuff like "wait for input" that limits your cpu usage because the program has to wait for other tasks. When you "freeze" your application it becomes just an infinite loop. If you launch the following program

```
int main()
{
    while(true);
    return 0;
}

```

of course it won't terminate, and its cpu usage will be 100%. You probably have 50% because your system is a dual core pc. You'll get 25% with a quad core, because it isn't a multithreading application.

I haven't tried it but probably if you launch another expensive program it will have a higher priority than yours in background that will reduce its cpu usage. I think the OS tries to use as many cpu's resource as it can. All the "normal" application (no game or programs like WinRAR) usually wait for user's input or they have a sleep() function inside them, so they can't have a lot of cpu usage. The only program remaining is yours, so it goes at 100%.

I think you can't put the thread to sleep because it won't know when it has to wake up. Sleep simply tells the OS not to schedule the program for the time passed in the barracks. A sleep(1000) means that the program will stop for a second even if, in the meanwhile, it acquires focus. A solution is:

```
if(freeze)
{
    sleep(100);
    continue;
}

```

if you use higher number you'll get a little delay after you click on the application and before it starts.
> 2 votes

---
Tags: windows
---


title: How do I correctly destroy a MobFox ad?

text:
# Question
Title: How do I correctly destroy a MobFox ad?
Is anyone here using MobFox to display their Android app's ads? I was previously using the AdMob SDK but recently switched to MobFox and while it only took a short time to integrate it, there are a few outstanding issues which I can't work out.

With the AdMob SDK, in my **onDestroy** method, I would have this line:

```
adView.destroy();

```

However, I've looked through MobFox but I can't see an equivalent, am I missing something?!

(there is all the usual **pause();**, **resume** methods etc..... just can't find a **destroy()** method)

# Answer
Just found it. For anyone else wondering about this, the correct method to call is:

```
adView.release();

```
> 2 votes

---
Tags: android, advertisements
---


title: Unity refuses to open 2 popup windows

text:
# Question
Title: Unity refuses to open 2 popup windows
So am am making a unity program, where if you click 2 different objects, 2 different windows are supposed to pop up.

To make them, I use private

```
private bool showPopUp = false;
private Rect rectangle = new Rect(int, int, int, int);

```

Both have a collider so that I can use OnMouseDown() to set showPopUp to true.

the onGUI class simply says

```
void OnGUI()
    {
        if (showPopUp)
        {
            rectangle = GUILayout.Window(0, rectangle, ShowGUI, "Prescription");
        }
    }

```

and my showGui looks like this

```
void ShowGUI(int windowID)
    {
      //some GUILayout things like textboxes and stuff are in here too

        GUILayout.BeginVertical();
            if (GUILayout.Button ("Okay"))//(GUI.Button(new Rect((Screen.width/4)-30, (float)(Screen.height/1.2)-30,60, 25), "OK"))
            {
                showPopUp = false;
            }
        GUILayout.EndVertical();

        GUI.DragWindow();
    }
}

```

These are two totally different classes, and on two completely different objects. However, if I have one of the popup windows open., and the to open the second, the first one goes blank, the second doesn't even show up, and I get this error:

> ArgumentException: GUILayout: Mismatched LayoutGroup.Repaint UnityEngine.GUILayoutUtility.BeginLayoutGroup (UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption\[\] options, System.Type LayoutType) (at C:/BuildAgent/work/aeedb04a1292f85a/artifacts/EditorGenerated/GUILayoutUtility.cs:210) UnityEngine.GUILayout.BeginHorizontal (UnityEngine.GUIContent content, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption\[\] options) (at C:/BuildAgent/work/aeedb04a1292f85a/artifacts/EditorGenerated/GUILayout.cs:235)

What do I need to change to allow me to open 2 windows at once?

# Answer
the problem is with

```
rectangle = GUILayout.Window(0, rectangle, ShowGUI, "Prescription");

```

since both of them have an ID of 0, unity tries to make 2 different windows with the same ID, causing a crash.

All you need to do is give one an ID of 0, the other an id of 1, so the other would look like

```
rectangle = GUILayout.Window(1, rectangle, ShowGUI, "Prescription");

```
> 2 votes

---
Tags: c#, unity
---