# Question
Title: How to achieve a Gaussian Blur effect for shadows in LWJGL/Slick2D?
I am currently trying to implement shadows into my game, and after a lot of searching in the interwebs I came to the conclusion that drawing hard edged shadows to a low resolution pass combined with a Gaussian blur effect would fit best and make a good compromise between performance and looks - even though theyre not 100% physically accurate.

Now my problem is, that I dont really know how to implement the Gaussian blur part. Its not difficult to draw shadows to a low resolutions buffer image and then stretch it which makes it more smooth, but I need to add the Gaussian blur effect.

I have searched a lot on that and found some approachs for GLSL, some even here, but none of them really helped it.

My game is written in Java using Slick2D/LWJGL and I would appreciate any help or approaches for an algorithm or maybe even an existing library to achieve that effect.

Thanks for any help in advance.

# Answer
> 2 votes
I tackled almost an Identical problem about a year ago. Since then I've figured out how to add gaussian blur to create better shadows. I'm assuming you're starting from a point like this: Shadow Blog Post, Image of Shadows With No Blur. And this is what you're after Image of Shadows WITH Blur.

My lighting system code that included shadows can be found here: Lighting Manager. I ended up using a Shader "Wrapper" by Jeremy Klix here: Shader Wrapper.

The shaders I used are here: Shaders. Take a look at the bassicBlur.vrt, blurHorz.frg and blurVert.frg. Combined they are a simple 2 pass (X then Y) gaussian blur. I define the 2 (horizontal and vertical) shader objects around line 66. Then during rendering, I use the shaders around 135. The shader takes two parameters: radius of the blur and the resolution of the rendered area. The idea is that you:

1. Enable the shader
2. Enable a multiple blend function
3. Draw the shadow map
4. Revert the blend function
5. Disable the shader

Let me know if you'd like more details.

# Answer
> 0 votes
The good news is that constant width Gaussian filter is separable thus you can gain good performance even for large kernel sizes, i.e this cuts the computation from the naive O(n^2) cost down to O(2n). The separable Gaussian filter is implemented by having two passes over the image: First performing 1D horizontal Gaussian blur, followed by 1D vertical Gaussian blur. This is pretty much the standard way to implement Gaussian filter nowadays. Here is an explanation how to implement it in GLSL,

---
Tags: java, lwjgl, slick, shadows, blur
---


title: RTS Movement + Navigation + Destination

text:
# Question
Title: RTS Movement + Navigation + Destination
I'm looking into building my own simple RTS game, and I'm trying to get my head around the movement of single, and multi selected units. (Developing in Unity)

After much research, I now know that its a bigger task than I thought. So I need to break it down. I already have an A\* navigation system with static obstacles taken into account.

I don't want to worry about dynamic local avoidance right now. So I guess my first break down question would be:

**How would I go about moving mutli units to the same location.** Right now - my units move to the location, but because they're all told to go to the same location, they start to 'fight' over one another to get there.

I think theres two paths to go down:

1) Give each individual unit a separate destination point that is close to the 'master' destination point - and get the units to move to that.

2) Group my selected units in a flock formation, and move that entire flock group towards the destination point.

*Question about each path:*

1a) How can I go about finding a suitable destination point that is close to the master destination? What happens if there isn't a suitable destination point?

1b) Would this be more CPU heavy? As it has to compute a path for each unit? (40 unit count).

2a) Is this a good idea? Not giving the units themselves a destination, but instead the flock (which holds the units within). The units within the flock could then maintain a formation (local avoidance) - though, again local avoidance is not an issue at this current time.

2b) Not sure what results I would get if I have a flock of 5 units, or a flock of 40 units, as the radius would be greater - which might mess up my A\* navigation system. In other words: A flock of 2 units will be able to move down an alleyway, but a flock of 40 wont. But my nav system won't take that into account.

# Answer
> 2 votes
You might want to take a look at these articles. They are a bit old; however I think they cover what you are looking for.

Coordinated Unit Movement

Implementing Coordinated Unit Movement

# Answer
> 1 votes
1a) just flood from the destination depending on how many units were told to go there

1b) you can keep the path mostly along the same path and split only in the last few meters

2b) let the flock rearrange itself when squeezing past obstacles (using local avoidance of static obstacles)

---
Tags: movement, rts
---


title: More vertices vs more textures

text:
# Question
Title: More vertices vs more textures
I'm currently working on a dynamic 'door' creator, and I'm trying to decide which is more efficient. Not much experience with 3D render speeds, so I'm asking before I choose which direction to go because its a lot of work either way. (The doors will be able to open/close.)

So I came up with two possibilities.

1. I generate all the triangles (as in the left picture), and go on my way.
2. I generate only two triangles, then create and save a whole new texture that is filled only with pixels that are not 'covered' by the door (the others are marked as transparent). I would then dynamically add the texture to a texture atlas. Then when the outside portion (gray) of the door is drawn, it would appear as in the right picture.

Hence, more vertices, or more textures? Before I start down one road, any advice on this? Or any other suggestions?

Thoughts: Creating a new texture for each instance would eventually take up too much memory, but they would be reusable. My gut says this would be better for a small game world with not many unique doors, so maybe I should just implement both and let the user decide.

# Answer
If the engine or API you are using already has boned/skinned animation capability, creating a door with a single joint and no vertex weighting would handle the open/close animation with a single texture... If you have only a few unique doors modeling them should not be that big a deal. This has the benefit that the door is still in the scene, and you can animate the open/close easily. This would be the solution I would use.

It seems to me you are talking about subdividing the mesh based on the door texture and that just feels backwards to me. Also breaking the object into 2 meshes so you can animate opening the door will be a bit of work, as will be manually handling the animation.

If you want to go the transparent texture route, there is a dirty trick -- you can paint the door pixels with alpha 0 and and the shader/render pipeline will ignore the alpha unless you jump through some specific hoops to turn on blending in the rendering pipeline, at which point the "door" disappears until you stop enabling/disabling blending around the draw call for that object. This technique has no "door" in the world, the door will just be visible or not visible with no open/close animation effect unless you mess around with the blend settings to animate the transparency fading in and out.

From my point of view -- any graphics card with a gig of ram can handle a crudload of doors using any of these techniques.. none of them have a particular heavy rendering load compared to any of the others (a slightly larger vertex buffer vs 2 textures or a blend state change while rendering is trivial) .. and only the subdivision method really requires anything in the way of CPU overhead, and that's pretty much one time for each unique door type, so I don't see any real efficiency issues with any of these choices -- the question is what gives you the effect you want during game play.....
> 1 votes

---
Tags: 3d, texture-atlas, efficiency
---


# Question
Title: How can I handle game-state updates in an MMO while the player is logged out?
I have a plan to build MMO strategy game like Goodgame Empire or Travian for Windows Phone. I want to program it in C# Monogame (because I have some good experience with it).

But I still can't figure out how to do game-server communication.

My plan is communicate with database through web service (WCF).

For example, if player build some building then the game saves information about that building through a web service method to a database.

But what if the player isn't logged in?

For example farms produce some food every hour. How to count how much food the player has when he logs into game after some time?

If you have some idea please let me know ;)

# Answer
> 6 votes
Your server would have some kind of background process (could also be implemented as a timer or a thread) which runs at regular intervals and updates all players. The process would run daily, hourly or every few minutes depending on how often you want the players farms to update and generate resources.

Any online players would get notified immediately that their resource count changed. Any offline players would get notified about their new resource count as soon as they are logged in.

An alternative solution would be to update the resource count of an offline player as soon as they log in. You check how much time has passed since they last logged out and update their resource count accordingly. But keep in mind that this makes offline interaction difficult. When other players can see the resources of another player, they won't get an up-to-date number before the player logged in. Checking whether or not the resources of a player grows could be used to see when they are online which might violate their privacy and/or might give the other player knowledge about their opponents online behavior you don't want them to have. Another problem you might run into is that it might get difficult to make sure that offline- and online processing work in *exactly* the same way. Subtle differences between them could lead to exploitable bugs.

---
Tags: c#, xna, monogame, databases
---


# Question
Title: How to unpause a particular gameobject in unity?
Say, I have a GUI Menu attached in a game scene. The game will be in pause state by default. I did it by setting "Time.timescale=0.0f"; I want my game to unpause only when Play button clicked. My question is how to access game scene from the script? And, what I to write on "OnClick" event? Your any suggestion will be highly appreciated. Regards

# Answer
> 2 votes
"How to access game scene from the script?" If you want to load a game scene use LoadLevel as mentioned. If you want to set the value of Time.timescale on a button click use this. However, I would suggest implementing a fsm to handle various game states.

# Answer
> 0 votes
I'm not 100% sure of what is your problem. But what I understand is that you start your game with Time.timescale at 0 and whant a specific game object to be "unpaused" (ie. not affected by the Time.timescale property).

As far as I know it's not possible for a specific game object to use a different TimeScale value.

I'd suggest to implement and use your own Timer system for pause and not use timescale anymore. The idea is that all your game object could use their own timers (updated by Time.time / Time.deltatime provided by Unity), then you'd be able to pause and unpause any game object you want, independantly from the rest of the game.

I hope it helps.

---
Tags: unity
---


title: how to re-use a sprite in cocos2d-x

text:
# Question
Title: how to re-use a sprite in cocos2d-x
some times it takes time to create the sprite structures in the scene, I might need to setup structures inside this sprite to meet requirement, thus I would hope to reuse such structures with the game again and again.

I tried that, remove the child from parent, detach it from parent , clean parent with the sprite. but when I try to add the sprite to another scene, it's just wont pass the assertion that the sprite already have parent

did I miss some step ?

add an example:

I have a sprite A which involves of quite a few steps to construct, so I used it in scene A layer A, and then I want to use it in scene A layer B, scene B layer A1 etc..... generally speaking I don't want to reconstruct the sprte again.

# Answer
Do you mean you want to quickly reuse sprite without re-create it?

You may need to consider using ObjectPool to create those sprites ahead of time for certain number of instances you may need, then whenever you need to use it in the game, there will be no time wasted in creation.

Edit: ObjectPool is where it has a whole bunch of objects already created ahead of time. Basically it has 2 managed arrays of objects which are free-array and active-array. At first, you just pre-create those objects to cut the time that would be lost and would hurt user experience if you create them on-the-fly during gameplay, all of those objects sit in free-array. Then whenever you need to use it, you pop it one-by-one from free-array and use in your game. So they will be removed from free-array and added into active-array. After you're done using it, you reset their states and return them back to free-array. It goes like this. Performance is great in magnitude compared to on-the-fly approach.
> 1 votes

# Answer
It's a guess, but are you sure you are retaining the sprite before detaching it from it's parent? when you detach an sprite (or any node in general), it usually get's deleted too.

In cocos2d for every instance, it's counted how many objects, are depending on that instance to work. In other words, the system keeps track of how many times that object is retains. so when you stop using that instance, it's cleaned up automatically. Adding an sprite as a child results in that sprite being retained, and later removing it, results in it being released. In your case it's possible that removing that sprite from parent, which causes a release, brings "retain count" down to zero, and ultimately deletes the sprite. Thus when you later try to attach to another node, you are attaching a deleted pointer. Try this instead:

```
sprite->retain();
sprite->removeFromParent();
newParent->addChild(sprite);
sprite->release();

```

note that you also need to release the sprite at the end of the process, so that later that sprite could be deleted normally.
> 0 votes

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


# Question
Title: Weird texture binding bug on Mali-400 MP
On Mali-400 MP, there's a weird bug with texture binding.

Sometimes, shaders use textures from wrong samplers.

On other mobile and desktop GPUs, the same code works fine, but on Mali, almost every draw call is broken:

As you see, lightmap texture (at sampler 6) is used instead of diffuse texture (0).

Anyone knows a workaround to this?

# Answer
> 2 votes
That was an issue with the driver not compiling `uniform sampler2D u_LightmapTexture[MAX_LIGHTMAPS]` correctly.

Unrolling the array of `sampler2D`s fixed the issue.

---
Tags: opengl-es
---


# Question
Title: Are there any advantages to different programming paradigms specifically releated to game programming?
I have been researching three different programming paradigms namely procedural, object oriented and functional. So far I have been able to find a lot of good information regarding general differences and advantages/disadvantages like readability, re-usability, difference in learning curve, program size, etc.

I am now looking for differences more related to game programming, but I am struggling to find good examples. Does anyone know of specific issues when programming games that these paradigms handle differently, that I could look into? This could include things like handling I/O, rendering and programming AI, but other things related to game programming would also be appreciated.

# Answer
> 1 votes
Procedural maybe the fastest way in CPU speed terms, but would be also the worst to work with. Games in AI and Physics have a lot of code, and controlling such things with a ton of function calls can be very frustrating to maintain the code for later use and reuse.

Functional is the the most slow in CPU speed terms, and you should totally avoid these in 3D games and any game with too many entities and mechanics. Keeping 60FPS is a hard work and in a game it's one of your highest priorities.

OOP is great! Sometimes hierarchy of the objects and type casts can be a bit slow than rather calling some functions, but the simple way of keeping things make the code a lot easierr than a procedural. Of course, Interfaces can be useful, but those means some overload on the CPU, and you should keep track only on hierarchy of the classes. Here is a example of a lib for AS3 game programming totally made in OOP: https://github.com/useflashpunk/FlashPunk

This idea is so great that people tried to make derivations in other IDEs like Starling(Punk) and Haxe(Punk).

I'm not into 3D game programming, so I can't make examples about it for you, but I think that 2D is enough.

---
Tags: software-engineering
---


# Question
Title: Word for a relationship specifying that 2 objects don't affect each other
I am aiming to create an Enum for a terrain\_surface\_layer.type property. The 3 types of terrain\_surface layers I wish to implement are the following:

1. Single - only a single type of terrain\_surface is placed on this layer
2. Mixer - when a terrain\_surface is placed on this layer, terrain\_surfaces that overlap this new terrain\_surface have their effectiveness on the terrain reduced. The totality of effectiveness of the set of terrain\_surfaces at a particular point on the terrain\_layer is 1, eg the effectiveness is a sum of exclusive effectiveness of each terrain\_surface.
3. Disjoint - any terrain\_surface can be placed on this layer without any implicit constraints/validation on the terrain\_surface being placed

How else would you describe a Disjoint relation of this type? This type of relationship between objects is not exclusive to this particular functionality and I am sure I will encounter it again.

# Answer
> 1 votes
**Decoupled**, or **Independent**

Thesaurus

# Answer
> 1 votes
I would go with **Cosmetic**, if it provides no other effects other than visual ones.

---
Tags: data-structure
---


# Question
Title: Large 2D Arrays Causing Garbage Collection
I've been working on a game in Java that, for this post's sake, looks like Terraria and has random world generation. I've been using Vectors to contain my tile/block objects, but recently due to the nature of the calculations I perform on them fairly often, I've switched my system to 2D arrays, using 'chunks.'

Each 2D array (chunk) of blocks is 256x256. That's a lot of data, and considering that's only for one chunk (the player will probably have 30-50 chunks generated by the end of the game), the amount of live objects increases quickly.

Today I started getting lag spikes in-game when I generated about 15 chunks or so. After a few print statements, it was clear that the spikes were pretty inconsistent, and although I have no knowledge of the Java garbage collector, I can only assume it is the culprit.

I read that the more live objects you have (the ones that are still referenced somewhere), the more the GC will lag when it does its thing. Plus, all these blocks are taking up huge blocks of memory which is causing the GC to start in the first place.

I have tried saving the unloaded chunks to a file for later use, but as you can imagine, saving that much data isn't exactly efficient. I'm stumped here.

**Does anyone have any suggestions on how to reduce the amount of live objects in-game?**

# Answer
Before anything, I'd look for a heap profiler and make sure it's the GC that's causing problems. However, if you find that it is indeed the number of objects you have in memory, you've already come up with the basic solution; **page your chunks out to disk once in a while and only keep nearby ones in memory.**

But, as you've seen, there are problems with the approach, namely slowness. My first recommendation here is the same as above; use a profiler and check what's actually taking so long. A few general tips:

1. You can spread out the disk writes over multiple update steps, or compress the data before writing it (although, that might be slower than the alternative, depending on your CPU/disk).
2. You may also check to make sure the format (XML, json) you're writing to isn't introducing unnecessary overhead. I haven't done serialization in a while, but from brief research`ObjectOutputStream` outputs to a binary format which might be faster than human-readable. The exact format of the data is difficult to recommend without knowing what tile data you need. Here is a reference for Minecraft's chunk format.
3. The GC may be trying to cleanup all your unloaded chunks. This is where Byte56's comment comes in. If you use an object pool to manage all your tile objects, then instead of leaving all those orphans for the GC to destroy, you'll reuse them in other chunks that get paged in later.

Again, you should prove your suspicions with a profiler before taking any action. Don't waste any time optimizing that you could be using to finish your game. I've used VisualVM before, and found it useful.
> 2 votes

---
Tags: java, performance, optimization
---


# Question
Title: Save a mouse coorinates after a specific number of seconds
I have a specific method that saves my mouse x and y coordinates. I want that mouse coordinates be saved by specific time (for example after 1000ms). How I need to do that in Java? Please add a simple usage example.

```
 public void mouseMoved(MouseEvent e) {
        currentX = e.getX();
        currentY = e.getY();

        if(enemy.onWall() == true){
            timer.schedule(new TimerTask(){
                public void run() {
                    saveX = e.getX();
                    saveY = e.getY();
                    enemy.setCont(true);
                    move();
                }
            },100);
            enemy.setOnWall(false);
        }
    }

```

But this code saves mouse coorinates immediately and then waits for 1000ms and I have old coordinates.

# Answer
EDIT

Actually, Timer's schedule method should work in this case - maybe it's running *straight away* because you have 100ms as your delay time instead of 1000 (from your code above that is).

---

If you're working in a multi-threaded environment, then make sure you handle possible concurrency issues.

A possible alternative would be to use `System.nanoTime()`

Declare these variables:

```
long delay = 1000;
long start = 0;
Point temp;

```

In the `mouseMoved` method:

```
    if(enemy.onWall() == true){
        temp = e.getLocation();
        start = System.nanoTime();
        enemy.setOnWall(false);
    }

```

(is enemy.setOnWall(false); supposed to be called after 1000ms?)

And in your game loop:

```
if (start > 0 && (System.nanoTime() - start) / 1000000 >= delay) {
    saveX = temp.getX();
    saveY = temp.getY();
    enemy.setCont(true);
    move();
    start = 0;
}

```

The "timer" is initiated when you move the mouse and is checked each frame to see if the duration since `start` was set is at least as long as the delay; if it is, the coordinates set at the start should be applied.

Since you move the mouse frequently, you may want to `return` the `mouseMoved` method if a coordinate is already scheduled to be saved.

This way you avoid multiple threads and result in a fairly accurate timed task.
> 5 votes

---
Tags: java, realtime
---


title: How to handle game objects in DirectX

text:
# Question
Title: How to handle game objects in DirectX
Coming from XNA, I would use the content pipeline and create XML files for game objects. However, if I changed something in the XML, I would need to do a rebuild of the project so it will create the XNB file.

Do I need to create XML files on my own and create\* encrypt/decrypt process and XML parser? Or should I simply hard code (since any changes would need a rebuild anyway)?

Most of the things in my game project will be random. However, the base types (like Armor types) will be static. Meaning one type of armor will give 20% armor. And another type of armor will give 50% armor.

* I do not want to use any third party solutions. I want to do everything myself so I can learn how to handle these situations.

# Answer
If you are deciding to get down in the dirt with low level DirectX api coming from XNA, you are in for some shocks -- there is no content pipeline that you don't create for yourself, and so many things you take for granted in XNA just don't exist at the low level, so you'll be writing a lot of engine code if you are planning anything more than the simplest of demos... This is in fact what I've been involved with for the last couple of months... building an engine around SharpDX/DX11 in C#... Our team is coming out of an XNA/Unity background, and despite a lot of progress so far -- we don't have much beyond materials(shaders)/meshes/input/HUD implemented and tested at this point... physics integration is in progress and we have lots more engine features planned... but there is still a long way to go :)

If you want to keep to the more XNA level of abstraction you may want to look at SharpDX.Toolkit.. it provides and XNA-like interface but fully backed by DX11 instead of DX9 but doent have content pipeline support... If you are hooked on the content pipeline features then look at Monogame...

So if you do decide to play in the dirt, you can forget about XNB files.. you will be loading your mesh and texture data directly from the various model and image formats supported by the raw DX11 API, or integrating with a more capable asset library like AssImp (asset importer for C#)

I just read your OP a bit closer and it seems sort of like you are talking XML as data to drive the game... in that case if you stick with C#/SharpDX you can embed the XML as a resource in your assemblies and visual studio will handle rebuilding when you make changes. Short of knowing more about the language and API you are planning to use, there isn't much more I can say
> 1 votes

---
Tags: c++, game-design, directx, data-structure, data-driven
---


# Question
Title: A Star pathfinding algorithm, multiple node set optimization
I'm trying to determine if this is an optimization I should pursue or if this is way to complicated to be worth my time. I've successfully implemented the A Star Algorithm for my video game. I used this awesome reference. Here's a video of the algorithm working in my mobile game. In game, the screen size is a programatic coordinate system of (135, 185). Those aren't actual pixels, just think of them as coordinates. And my pathfinding nodes are every 5 coordinates, so that means 135/5 = 27 nodes horizontally and 37 nodes vertically.

Because of all the stuff going on in my game I want to optimize the A Star algorithm so that I don't have to use that many nodes unless it's necessary. Let's say you're in a building and you have lots of narrow hallways, you'll need nodes that close together. But if you're in a wide open field or something you won't need nodes that are so close together simply because there aren't many obstacles in your way.

So I'm thinking of implementing two different node coordinate systems, one that's a node every 5 coordinates as calculated above and then another that's a node every 8 coordinates. The idea is that if I have fewer nodes the calculations will be much faster. I'll need some sort of detection that determines which node system to use or possibly to combine both.

Example: Let's say the soldier wants to walk from coordinate (10, 10) to (100, 100), I'll need to determine whether the pathfinding algorithm use the nodes every 5 coordinates grid or the nodes every 8 coordinates grid or does it use the 5 for the first half and the 8 for the second half...

Thoughts?

-----EDIT-----

Here's a video of the pathfinding's calculation duration in game. With a grid of 135x185, I had 3 soldiers move from one end of the screen to the other through various obstacles. The quickest path was calculated in 46 ms, the next 99 ms, and the longest in 127 ms. I ran my game through XCode Instruments time profiler but didn't notice any pathfinding functions hogging CPU time. The biggest chunks of time was being spent on animations of the soldier's body parts....

Here's the code for my A Star Implementation in C# with Xamarin Studio. I've also noticed that there are some other A Star Implementation posts on this site, I'm reviewing them now to see if some of the optimization suggestions for other people apply to me.

-----EDIT-----

I still am not able to get any good information from XCode Instruments regarding the CPU usage of my pathfinding function, but I did some manual time measuring myself using DateTime and discovered this: The foreach loop where I "Calculate the F G H for all nodes on openList" is using about 50% of the path CPU time for long paths. My "GetAdjacentNodesToThisNode" function that is called many many times ends up using about 33% of the CPU time for long paths. So clearly optimizing those two sections of code would help. I'll see what I can do.

-----EDIT-----

I was able to reduce the pathfinding CPU usage dramatically (but about 60% on long paths) by simply replacing my static function calls with the code itself. It results in code duplication which I hate, but the performance boost is noticeable!!

```
public static List<AStar_Node> AStarAlgorithm ( long startNode, long endNode, bool forceMove_regardlessOfIsWalkable )
{
    // The UIApplicationDelegate for the application.
    AppDelegate appDel = (AppDelegate)UIApplication.SharedApplication.Delegate;
    DateTime before = DateTime.Now;

    List<AStar_Node> openList = new List<AStar_Node>();
    AStar_Node CurrentNode;
    AStar_Node StartNode;
    AStar_Node EndNode;
    long diagonalMoveCost = 14;
    long vertOrHorzMoveCost = 10;

    long startNodeX = (((startNode-1)%appDel.globals.NumOfNodesX));
    long startNodeY = (((startNode-1)/appDel.globals.NumOfNodesX));
    //          Console.WriteLine("startNodeX = " + startNodeX + " startNodeY = " +startNodeY);

    long endNodeX = (((endNode-1)%appDel.globals.NumOfNodesX));
    long endNodeY = (((endNode-1)/appDel.globals.NumOfNodesX));
    //          Console.WriteLine("endNodeX = " + endNodeX + " endNodeY = " +endNodeY);

    StartNode = appDel.globals.BattlefieldGraph[startNodeX, startNodeY];
    // subtract the vertOrHorzMoveCost value from the StartNode's G so that it's initialized correctly
    StartNode.G -= vertOrHorzMoveCost;
    // Make the CurrentNode the start node and make the start node's parent node itself...
    CurrentNode = StartNode;
    appDel.globals.BattlefieldGraph[startNodeX, startNodeY].parentNode = CurrentNode;
    openList.Add (CurrentNode);

    EndNode = appDel.globals.BattlefieldGraph[endNodeX, endNodeY];

    // Clean up the closed nodes from the previous pathfinding calculation
    for ( int rows = 0; rows < appDel.globals.NumOfNodesY; rows++ )
    {
        for ( int cols = 0; cols < appDel.globals.NumOfNodesX; cols++ )
        {
            appDel.globals.BattlefieldGraph[cols,rows].isClosed = false;
        }
    }

    bool Loop = true;
    bool PathFound = false;

    while ( Loop )
    {
        // Calculate F G H for all nodes on openList
        foreach ( AStar_Node node in openList )
        {
            // Calculate G
            if ( Library_AstarAlgorithm.ThisNodeIsHorizontalOrVerticalToThatNode(node, node.parentNode) )
            {
                node.G = node.parentNode.G + vertOrHorzMoveCost;
            }
            else
            {
                node.G = node.parentNode.G + diagonalMoveCost;
            }

            // Calculate H using Diagonal Method
            long xDistance2 = Math.Abs(node.X - EndNode.X);
            long yDistance2 = Math.Abs(node.Y - EndNode.Y);
            if ( xDistance2 > yDistance2 )
                node.H = diagonalMoveCost*yDistance2 + vertOrHorzMoveCost*(xDistance2 - yDistance2);
            else
                node.H = diagonalMoveCost*xDistance2 + vertOrHorzMoveCost*(yDistance2 - xDistance2);
            // Calculate H using Manhattan Method
            //                  node.H = (Math.Abs(node.X - EndNode.X))*10 + (Math.Abs(node.Y - EndNode.Y)*10);

            // Calculate F by adding G and H
            node.F = node.G + node.H;
        }

        // Find lowest cost.  Because I've been sorting the list by F
        CurrentNode = openList[0];

        // Remove CurrentNode form openList
        openList.Remove (CurrentNode);
        // Move CurrentNode to closedList
        //              closedList.Add (CurrentNode);
        CurrentNode.isClosed = true;

        //              Console.Write("Moving to Node ");
        //              Library_AstarAlgorithm.PrintNode(CurrentNode);

        // Stop when you add the target node to the closed list, in which case the path has been found
        if ( CurrentNode == EndNode )
        {
            //                  Console.WriteLine("Path Found!");
            Loop = false;
            PathFound = true;
        }

        List<AStar_Node> adjacentNodesList = Library_AstarAlgorithm.GetAdjacentNodesToThisNode(CurrentNode);
        //              Console.WriteLine("New List of adjacentNodes.count() = " + adjacentNodesList.Count());

        foreach ( AStar_Node node in adjacentNodesList )
        {

            // If it is in the closed list, ignore it
            if ( node.isClosed )
            {
                // Ignore the node

            }
            // If it is not walkable and we're not on force move, ignore it
            else if ( !node.isWalkable && !forceMove_regardlessOfIsWalkable )
            {
                // Ignore the node

            }
            // Otherwise do the following
            else
            {
                // If it isn’t on the open list, add it to the open list. Make the current node the parent of this node. Record the F, G, and H costs of the node.
                if ( ! openList.Contains(node) )
                {
                    // Set the parentNode
                    node.parentNode = CurrentNode;

                    // Calculate G
                    if ( Library_AstarAlgorithm.ThisNodeIsHorizontalOrVerticalToThatNode(node, node.parentNode) )
                    {
                        node.G = node.parentNode.G + vertOrHorzMoveCost;
                    }
                    else
                    {
                        node.G = node.parentNode.G + diagonalMoveCost;
                    }

                    // Calculate H using Diagonal Method
                    long xDistance = Math.Abs(node.X - EndNode.X);
                    long yDistance = Math.Abs(node.Y - EndNode.Y);
                    if ( xDistance > yDistance )
                        node.H = diagonalMoveCost*yDistance + vertOrHorzMoveCost*(xDistance - yDistance);
                    else
                        node.H = diagonalMoveCost*xDistance + vertOrHorzMoveCost*(yDistance - xDistance);
                    // Calculate H using Manhattan Method
                    //                          node.H = (Math.Abs(node.X - EndNode.X))*10 + (Math.Abs(node.Y - EndNode.Y)*10);

                    // Calculate F by adding G and H
                    node.F = node.G + node.H;

                    //                          Console.Write("Added to openList: ");
                    //                          Library_AstarAlgorithm.PrintNode(node);

                    //                          openList.Add (node);
                    //                          Console.WriteLine("Adding node with F value " + node.F);

                    // Add node to the openList in such a way that it's sorted by F.  Smallest first, largest last.
                    long openListCount = openList.Count();
                    bool didInsert = false;
                    for ( int i = 0; i < openListCount; i++ )
                    {
                        // Insert node at the correct place based on the F values...
                        if ( openList[i].F >= node.F )
                        {
                            //                                  Console.WriteLine("inserting " + node.F + " infront of " + openList[i].F);
                            openList.Insert(i, node);
                            didInsert = true;
                            break;
                        }
                        //                              if ( didInsert )
                        //                                  Console.WriteLine("You shouldu never see this");
                    }

                    if ( !didInsert )
                        openList.Add (node);
                }
                // If it is on the open list already, check to see if this path to that node is better, using G cost as the measure. A lower G cost means that this is a better path. If so, change the parent of the node to the current node, and recalculate the G and F scores of the node. If you are keeping your open list sorted by F score, you may need to resort the list to account for the change.
                else
                {
                    // Determine the cost of going from node to CurrentNode
                    long tempCost;
                    if ( Library_AstarAlgorithm.ThisNodeIsHorizontalOrVerticalToThatNode(node, node.parentNode) )
                    {
                        tempCost = vertOrHorzMoveCost;
                    }
                    else
                    {
                        tempCost = diagonalMoveCost;
                    }

                    if ( (tempCost+CurrentNode.G) < node.G )
                    {
                        // Update node's parentNode and recalculate FGH scores

                        node.parentNode = CurrentNode;

                        // Calculate G
                        if ( Library_AstarAlgorithm.ThisNodeIsHorizontalOrVerticalToThatNode(node, node.parentNode) )
                        {
                            node.G = node.parentNode.G + vertOrHorzMoveCost;
                        }
                        else
                        {
                            node.G = node.parentNode.G + diagonalMoveCost;
                        }

                        // H does NOT need calculated here

                        // Calculate F by adding G and H
                        node.F = node.G + node.H;

                        //                              Console.WriteLine("F has been recalculated, now we need to resort for this value.  It's index is " + openList.IndexOf(node));
                        int thisIndex = openList.IndexOf(node);
                        int indexToCheck = thisIndex - 1;
                        bool switchNeedsPerformed = false;
                        int indexToSwitch = -99999;
                        // Resort if need be...
                        while ( indexToCheck >= 0 )
                        {
                            if ( openList[indexToCheck].F > openList[thisIndex].F )
                            {
                                switchNeedsPerformed = true;
                                indexToSwitch = indexToCheck;
                            }
                            else
                            {
                                if ( switchNeedsPerformed )
                                {
                                    //                                          Console.WriteLine("making a swap. Putting " + openList[thisIndex].F + " before " + openList[indexToSwitch].F);
                                    AStar_Node tempNode = openList[thisIndex];
                                    openList.Remove(tempNode);
                                    openList.Insert(indexToSwitch, tempNode);
                                    break;
                                }
                            }
                            indexToCheck--;
                        }
                        //                              Console.WriteLine("thisIndex-2 = " + openList[thisIndex-2].F + " thisIndex-1 = " + openList[thisIndex-1].F + " thisIndex = " + openList[thisIndex].F);
                        //                              Console.WriteLine("thisIndex = " + openList[thisIndex].F + " thisIndex+1 = " + openList[thisIndex+1].F + " thisIndex+2 = " + openList[thisIndex+2].F);

                    }

                    //                          Console.Write("Already exists in openList: ");
                    //                          Library_AstarAlgorithm.PrintNode(node);
                }
            }
        }

        // Stop when you fail to find the target node, and the open list is empty. In this case, there is no path
        if ( openList.Count() <= 0 )
        {
            Console.WriteLine("Path Not Possible.  OpenList is empty!");
            // There is not path, exit loop
            //                  Loop = false;
            return null;
        }

        //              Console.WriteLine("Looping through with openlist.coutn = " + openList.Count());

    }

    // **** OPTIMIZATION **** //
    // Here is where I optimize the path that we're returning.
    // If I make up the path based on a smaller number of nodes, there will be less animations that have to start and stop.  Doing so will reduce the CPU usage
    List<AStar_Node> Path = new List<AStar_Node>();

    if ( PathFound )
    {
        CurrentNode = EndNode;
        try
        {
            while ( CurrentNode != StartNode )
            {
                Path.Add(CurrentNode);
                // Reset the isClosed variable to false;
                CurrentNode = CurrentNode.parentNode;

            }
            Path.Reverse();
        }
        catch(Exception e)
        {
            Console.WriteLine("Warning Inside AStarAlgorithm");
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
            return null;
        }

    }
    else
    {
        Console.WriteLine("No Path possible.  Reached Blockade!");
        return null;
    }

    Console.WriteLine("AStarAlrogirthm Duration in ms = " + DateTime.Now.Subtract(before).TotalMilliseconds);
    return Path;
}

```

# Answer
What you're really looking for are navigation meshes:

These meshes will conform to the walkable areas in your game. You can make the nodes as small as you like. In this way, you can have far fewer nodes for your A\* algorithm to work on. You can still have smaller nodes if you like for fine detail pathing, or you can use something like steering to get between nodes.

If you'd still like to do your idea of a larger grid and a smaller grid, that's fine too. The larger nodes would just be made up of multiple smaller *walkable* nodes. There's no reason to make the larger nodes include non-walkable areas. I think what you'd eventually end up with is something like the navigation mesh above.
> 4 votes

# Answer
This article: http://www.ai-blog.net/archives/000152.html gives a good overview of Navigation meshes and discusses dealing with realtime modification of the mesh due to environmental changes at least a little bit...

The basic idea is that you mesh out all the potentially walkable spaces by default, then either mod a section of the mesh, or deal with moving around obstacles using a little ray casting to find the clear path...
> 1 votes

---
Tags: algorithm, physics, path-finding, optimization
---


# Question
Title: Elevation model for hexagonal game grids
**TL;DR:**

Where should elevation be anchored on a civ-style hexagonal grid? Center, side or vertex? (Or more complex?)

**Question proper:**

Consider for a moment a classic game we all know and love (maybe?), Sid Meier's Alpha Centauri. The map model introduced the brand new concept of visible terrain elevation to the classic Civ formula. In SMAC, every vertex of the game board had an elevation, allowing the map beautiful rolling hills, a complete necessity, considering the mind worm boils waiting around every corner.

Would a vertex-only elevation map translate neatly to a hexagonal grid?

The obvious alternatives are side-based elevation mapping and center-based elevation mapping; as well as inner-vertex elevation mapping (giving the opportunity for cliffs! Yay!)

The last option is applying a triangular lattice to the game grid encompassing centers and vertices, and having vertex-only or inner-vertex elevation.

Which of these options is likely to work well? Which are likely to suck all the juice out of the CPU and RAM in a hurry?

# Answer
> Would a vertex-only elevation map translate neatly to a hexagonal grid?

It depends on the tessellation of the grid. If you tessellate your plane like so, then yes.

In this case, you can change the green triangle (x6) any way you like:

> Which of these options is likely to work well?

They all work well. Chances are that you'll be using multiple methods, anyway. You can't *just* use mid-point elevation unless you just want one-tile mountain features, you'd have to "raise" the edges as you go up a mountain if you want multiple-tile topography.

> Which are likely to suck all the juice out of the CPU and RAM in a hurry?

This is a non-issue (unless you're writing this for some sort of embedded system?) as all the map generation work will be done before anyone plays the game, during the loading phase.
> 10 votes

# Answer
Great that at least some one else thought of this. To bad I only encounter this page several years later. However, I am going to answer your question for the basic hexagons instead. The pictures that have been shown until now are not 100%. And on a 1 meter map the grid will be out of shape. Meaning no 60 degree turn possible.

I have been experimenting on:

* Different sizes of hexagons: Which triangle (in pixels) basis gives the highest accuracy on 1 meter maps once printed out. This includes having them as perfect as possible when turning them 60 degree's. Also when turning them 180 degree's for refitting.
* Different combined layers of hexagons.
* Single hexagons for cutting out high detailed pictures (RAM = insufficient at big maps).
* The exact limits of my computer plus what I feel is allowable.

I did not experiment yet on having elevation by making different shaped hexagons. But I do know that the basis needs to be correct before making the elevation.

---

Summary:

* Accuracy of 1 mm or less on a 1 meter map. The 60 degree rule.
* I need lines that can fit themselves when turned 180 degree´s.
* I need the triangle to fit on my screen with maximum zoom.

I narrowed down my selection to 3 with these rules:

Small:

* Size; +26 x +45, 27 x 46 pixels
* Inaccuracy on 1 meter; 0,74 mm
* Sequence; 131213131312131

Medium:

* Size; +41 x +71, 42 x 72 pixels
* Inaccuracy on 1 meter; 0,20 mm
* Sequence; 1312131313121313131312131

Large:

* Size; +56 x +97, 57 x 98 pixels
* Inaccuracy on 1 meter; 0,05 mm
* Sequence; 1312131313121313131213131312131

The one's are 1 pixel.

The two's and three's are groups of 2 pixels. A 2 is 4 pixels in total and A 3 is 6 pixels in total.

If you add a sequence up, you will see that they are the width in pixels. If you add them up and counting 4 and 6 instead of 2 and 3. You get the hight in pixels.

The + numbers are what you add in pixels when you place 2 triangles on top of each other or against each other.

Feel free to ask questions. On my email.
> -1 votes

---
Tags: game-mechanics, tiles, hexagonal-grid, topography
---


# Question
Title: Is it a bad idea to couple action and animation?
I'm making an ARPG (like Legend of Zelda but with more action), and this question raised during the development:

**Should action and animation be coupled? Or should they be independent?**

With this I mean, the process of executing an action (eg. Attacking) should be:

1. Input
2. Start Animation
3. Frames 1-3 are transitioning, do nothing
4. Frames 4-7 are attack moves, do the attack action during these (searching enemies in front of the character, pick the closest and deal the damage)
5. Frames 7-10 are transitioning, do nothing again
6. Animation finished, release input again.

This way, it's like the action is triggered by the frames, as events on the animation itself.

If it helps, I'm making the game on an Entity/Component System.

Should it be done this way? Why yes/no? What are the advantages/disadvantages?

# Answer
You really don't have much choice. Ignoring some (IMO) terrible other options, you can either:

a) couple your behavior to specific animations - so artists don't make one attack animation, they make several that your behavior plays at the appropriate times

or

b) have animations emit events and export state variables that game logic is driven from - requires lots of effort put into tools to make the workflow nice, but lets gameplay be driven by art and design far more easily which is usually a very good thing

If you have the time and expertise to develop the tools, I'd go with the second option every time, but small indie/hobby/old-school games do tend to lean more towards the former.
> 4 votes

---
Tags: architecture, animation
---


# Question
Title: Calculating angle a segment forms with a ray
I am given a point C and a ray r starting there. I know the coordinates (xc, yc) of the point C and the angle theta the ray r forms with the horizontal, theta in (-pi, pi\]. I am also given another point P of which I know the coordinates (xp, yp): how do I calculate the angle alpha that the segment CP forms with the ray r, alpha in (-pi, pi\]?

Some examples follow:

I can use the the atan2 function.

# Answer
> 1 votes
No conditions, you don't need normalised vectors, a single trig function:

```
Vector2 pc = p - c;
float crossp = pc.x * ray.direction.y - pc.y * ray.direction.x;
float dotp = pc.x * ray.direction.x + pc.y * ray.direction.y;
return Math.atan2(crossp, dotp);

```

Here is the explanation. A fast summary:

* Cross product between two vectors is the same as `sin(theta) * len(v1) * len(v2)`
* Dot product between two vectors is the same as `cos(theta) * len(v1) * len(v2)`
* Since `atan2` requires two variables (the y and the x component), it already outputs detailed info (an angle on the \]-pi, +pi\] range, so it gives sense of direction too)
* `atan2(y, x)` is simply `atan(y / x)`, if you put the entire formula, `atan((sin * len1 * len2) / (cos * len1 * len2))` you see that len1 and len2 cancel themselves, so we're just with `atan(sin / cos)`. Since sin represents the vertical component of a triangle and cos represents the horizontal component of a triangle, everything goes well, no need to take a single `sqrt` and no need to use conditionals to change the range.

# Answer
> 1 votes
We find the vector from c to p (p - c), and compute its angle with the x-axis. Then we subtract, and put it into the right range.

```
theta2 = atan2(p_x - c_x, p_y - c_y)
alpha = theta2-theta
if (alpha > pi) alpha -= 2pi
if (alpha <= -pi) alpha += 2pi

```

This assumes that theta is in the range (-pi, pi\], and atan2 gives its result in the range (-pi, pi\] as well. Otherwise you can just make those while loops.

Note this is a signed angle, not an absolute one.

---
Tags: geometry, angles
---


# Question
Title: How to specify colour in a single 32 bit value
I'm writing my first game using OpenGL 2 ES (for Android), and I've currently got a particle engine and some player sprites running successfully. I'm using 4 floats for the colour of each particle which seems like total overkill. It makes sense that I should be able to use a single 32 bit int (or perhaps a single float) to hold the colours (perhaps in RGBA format) which would presumably save a lot of unnecessary loading/copying/processing, but I'm struggling to understand how I could do this.

I guess that I would need to change the shaders to take the relevant format, and also i'd need to change the way I load the color shader attribute. My fragment shader has:

```
varying vec4 v_Color;
gl_FragColor = v_Color * texture2D(u_TextureUnit, gl_PointCoord);

```

and the attribute (passed into the fragment shader from the vertex shader) is set up with:

```
glVertexAttribPointer(aColourLocation, COLOUR_COMPONENT_COUNT, GL_FLOAT, false, BYTES_PER_VERTEX, floatBuffer);

```

I've searched the documentation for what I should change vec4 and GL\_FLOAT to, and what/how I'd multiply the colour with the texture, and have tried a few things but with no success.

# Answer
> 3 votes
Fragment shaders operate with floats. This is an abstraction over the actual underlying hardware format (GLSL is a high-level language after all), so you shouldn't expect that to indicate that you've actually got a floating-point framebuffer. You'll always use vec4 in your fragment shader irrespective of if you have a 16-bit, 32-bit, 64-bit or 128-bit framebuffer, and there's no memory overhead for doing so.

There's no need to change your fragment shader; don't fall into the trap of thinking that the high-level GLSL you write is any way representative of the low-level hardware instructions that actually run.

For sending colours as a 4-byte format you adjust your glVertexAttribPointer call so that it's using GL\_UNSIGNED\_BYTE for the *type* parameter and GL\_TRUE for the *normalized* parameter. Then also adjust your source data, and you can start sending colours as 4 bytes with a 0-255 range, in RGBA order. The hardware will automatically convert them to floats in a 0-1 range and your fragment shader, once again, remains exactly the same as before. Don't sweat the details of whether or not this is a slow operation: it isn't.

Beware of thinking you're going to be even more efficient if you decide to only send 3-bytes sometimes: hardware prefers to operate on 32-bit boundaries and while you will save a small amount of memory you risk running substantially slower as a result.

---
Tags: android, opengl-es2
---


# Question
Title: How to create scrollable text in AndEngine?
I'm creating some tutorial text that the user should be able to scroll.

Is there any way to make vertical scroll in AndEngine so that we can easily view all the content by scrolling up and down?

# Answer
There is no built in functionality in AndEngine to create a scrollable text. You can render the text and make it scrollable yourself. But in your case it will be better if you utilize Android SDK and add a new "text layer" to your layout.

Basically you want to design the layout in a way where the AndEngine `RenderSurfaceView` will be rendered under another view (let's call it text view). You can then show or hide this text view as you please and use it to render text. You can use any kind of Android SDK GUI Elements there, including scrollable text.

See for example this tutorial.
> 2 votes

---
Tags: andengine
---


# Question
Title: Trying to better understand Unity gameobjects
New to Unity, but develop in C# normally. I can't seem to get how / why / where to grab certain elements. For simplicity, I have a top-level game object, say a cube. I add a sphere to the scene as child to the cube. The child sphere (actually more complex), has navigation mesh, animation object, collider and finally a script in C#.

Now, my C# class is comprised of an instance of an C# class on the class. Something like

```
public class CMyGeneric
{
   public void someMethod()
   {
      // invalid getting to "gameObject" reference
   }
}

public class CMyMainScript
{
   public CMyGeneric myGeneric;

   void Start()
   {
      myGeneric = new CMyGeneric();
   }

   void Update()
   {
      myGeneric.someMethod();
   }
}

```

So, the parent game object is the cube, the child is the sphere, and the CMyMainScript script is attached to the sphere. However, when I try to reference "gameObject" via the CMyGeneric (instance), call within the "someMethod", the "someMethod" doesn't appear to see the overall "gameObject".

Now, how/what am I missing as each thing that gets attached, unity adds to these game objects, and I don't know how to get respective hierarchical levels of where things are even though I know where they are from a relative perspective.

# Answer
> 1 votes
I assume you've left out some code? Like that `CMyMainScript` and `CMyGeneric` extends MonoBehaviour? Are you expecting to be able to access `gameObject` inside your `CMyGeneric` class because you'd instantiated it inside another class?

If you want to access `gameObject` you need to attach that script to a game object by using `this.gameObject.AddComponent<CMyGeneric>()`. This returns the reference to `CMyGeneric` that you'd want to use, and will have the `gameObject` reference properly set.

However, if you're attaching `CMyGeneric` as a script you may as well call `someMethod` inside of the `CMyGeneric` `Update()` method.

Alternatively, if you're not making `CMyGeneric` into a script to be attached, and you want `CMyGeneric` to act on a `gameObject`, just pass the game object into the `someMethod` call.

```
public void someMethod(GameObject gameObject)
{
   // valid "gameObject" reference
}

```

And:

```
void Update()
{
   myGeneric.someMethod(this.gameObject);
}

```

# Answer
> 1 votes
GameObjects are very closely linked to Transforms.

The GameObject could be thought of as a container to hold a set of Components e.g. scripts, colliders etc.

Meanwhile the Transform holds properties than connect the GameObject to the the world e.g. position/scale/rotation and any parent/child relationships.

**Parent:**

When scripting you can access the parent GameObject like this:

```
Transform parent = transform.parent;
parent.gameObject

```

**Children:**

Child GameObjects can be accessed by name (optionally including hierarchy):

```
Transform child =  transform.Find("path/objectname");
child.gameObject

```

Transform also provides `GetEnumerator()` allowing us to iterate through the collection of children:

```
foreach (Transform child in transform)
{
    child.gameObject
}

```

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


title: Diffuse Maps and DirectX

text:
# Question
Title: Diffuse Maps and DirectX
How would I load two diffuse maps onto one mesh. I have a mesh with multiple sub meshes but each one of those sub meshes has a vertex buffer and I don't think that's very efficient. How could I have two diffuse maps on one mesh without having to go into 3d modeling software and merge the Uv coordinates of the two objects. I'm using directX and C++.

# Answer
The only way I can even think of accomplishing this would be to add some sort of selector data to the vertex information that would allow a custom shader to select between the two textures to be applied. This technique can be applied with a little custom code to rewrite/combine the two vertex buffers, and of course the custom shader to take the new vertex format and the two textures to be used.
> 1 votes

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


# Question
Title: How can I get a list of servers hosted by my players?
I'm writing a multiplayer 2D online game, where game servers are hosted by the players. I want to show players a list of the currently hosted game servers.

How would I do that? I know how to let players host servers. But how would I then get a server list? Should I use a database? Is there an easier way?

# Answer
> 7 votes
In order to get a server list, you will need a central matchmaking server to which all game-servers connect and announce that they are online and to which all game-clients connect to obtain the list of currently online servers.

How many servers are you going to have? For comparison, I remember that during the high-times of the original Counter Strike, the WON matchmaking servers listed tens of thousands of gameservers. And that was *Counter Strike*, the most played multiplayer-FPS of all times. So how many people will you convince to host servers for your game?

When you only want to list the servers which are online *right now*, a database would be unnecessary. When you have a thousand gameservers and each one with just a few kByte of information, that's still just a few MByte of RAM. That's not nearly enough data to justify a database and enough to be handled by the cheapest VM instances you can rent.

Losing the data in case of a server reboot isn't a problem either, because you will want your game-servers to reannounce themselves to the matchmaking server every few minutes anyway to make sure that they are still online. So it won't take long after a reboot until your server list is complete again.

A database might be interesting when you would like to collect some usage statistics about your servers and clients and later want to data-mine this information. But that's a different topic.

But while storage space likely won't be an issue, there is another aspect which might get a bit more of a concern and that's bandwidth. I don't know how many clients and servers you expect, how often your clients will request the server list and how much data they receive each time. But you should know and be able to make a rough estimation how much traffic this will consume daily and check what server-hosing which allows that kind of volume will cost you.

When your budget is low and you want your technology to be scalable, you could save a lot of resources by using the Distributed Hash Table algorithm. This technology is used by peer-to-peer filesharing networks like BitTorrent or tools like TOR to reduce the dependence on a central server. In this system, the global server list isn't hosted on one server, it is distributed over many servers. You can use your game-servers or even your game-clients for this purpose. However, you will still need to host at least one server with a known IP as an entry-point into the network. But the load on this server will be a lot lower than on a central matchmaking server.

# Answer
> 1 votes
For simple matchmaking only, you can create an ASP.Net or PHP website that the players login to (via your game app) and push a notification when they create a server. The problem is securing the server to make sure only your players are accessing critical services like advertising a host or requesting the available host list.

There are also services like Kongregate that have an API you can integrate with your app to get matchmaking services, in addition to achievements, leader boards, and other features.

If you run your own matchmaking service, you would probably want some sort of shared data storage that all the user sessions can access in memory... databases tend to be too slow for the quickly changing list of available servers if your game gets any sort of popularity... how you do this shared cache depends heavily on the web server technology you decide to use. Both PHP and ASP.Net have ways to deal with this so long as you only have a single server handling the matchmaking. If you get to the point where you need a web farm to handle your player load, you are pretty much stuck with a database.

---
Tags: java, multiplayer, online, peer-to-peer, hosting
---


# Question
Title: Is there a way to retain a service on android even after the game is uninstalled ..?
I am designing a game which has a service to send user stats to a server ... I want that service to stay and work on the device even when the user uninstalls the game .

# Answer
**You could create some kind of game launcher**, if you can convince people to download it (for a in-game bonus maybe?). Almost every big gaming company has that annoying little program and will not allow you to play their games without it. With this idea you do not prevent users from uninstalling anything and you can collect data related to your apps.

As for stalking/preventing user to uninstall your apps, I would not be surprised if it was considered as a virus or even illegal(technically you are damaging their device, without their consent). However there *are* ways to code stalking app (as there are many, and some nearly undetectable), but if I am not mistaken it requires at least superuser to install it.
> 0 votes

---
Tags: android, server
---


title: How to properly change resolution

text:
# Question
Title: How to properly change resolution
I'm trying to understand how LibGDX handles screen size / resolution, etc. Coming from XNA this seems very confusing to me. Basically I want to support 480x800 for my game. If the screen size is different it should scale the resolution and use letterboxing. To do this I use a FitViewport. And that's the code:

```
public static final int VIRTUAL_WIDTH = 480;
public static final int VIRTUAL_HEIGHT = 800;
Viewport viewport;
SpriteBatch spriteBatch;
ShapeRenderer shapeBatch;
Texture img;

@Override
public void create()
{
    viewport = new FitViewport(VIRTUAL_WIDTH, VIRTUAL_HEIGHT);
    spriteBatch = new SpriteBatch();
    shapeBatch = new ShapeRenderer();
    img = new Texture("test.jpg");
}

@Override
public void resize(int width, int height)
{
    viewport.update(width, height);
}

@Override
public void render()
{
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    shapeBatch.begin(ShapeType.Filled);
    shapeBatch.setColor(Color.GRAY);
    shapeBatch.rect(0, 0, viewport.getWorldWidth(), viewport.getWorldHeight());
    shapeBatch.end();

    spriteBatch.begin();
    spriteBatch.draw(img, 0, 0);
    spriteBatch.end();
}

```

Now if I set the game resolution to be 480x800 right at the beginning, it basically works except that if I change the window size, the resolution keeps to be 480x800. So it stretches the image but keeps the aspect ratio:

And if I run the game with any other resolution like for example 700x500 I get this:

What is going on behind the scenes? (And sorry if my english is bad)

# Answer
You could try using a `Camera` when drawing your images. Create a new `OrthographicCamera` like so:

```
OrthographicCamera cam = new OrthographicCamera(VIRTUAL_WIDTH, VIRTUAL_HEIGHT);

```

Now when you create your viewport, pass the camera into the constructor.

```
Viewport viewport = new FitViewport(VIRTUAL_WIDTH, VIRTUAL_HEIGHT, cam);

```

Now in your render method:

```
@Override
public void render(){

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    spriteBatch.setProjectionMatrix(cam.combined); //Important

    shapeBatch.begin(ShapeType.Filled);
    shapeBatch.setColor(Color.GRAY);
    shapeBatch.rect(0, 0, viewport.getWorldWidth(), viewport.getWorldHeight());
    shapeBatch.end();

    spriteBatch.begin();
    spriteBatch.draw(img, 0, 0);
    spriteBatch.end();

}

```

Now to resize the viewport:

```
@Override
public void resize(int width, int height)
{
    viewport.update(width, height);
}

```

or if you would like to keep the camera center:

```
@Override
public void resize(int width, int height)
{
    viewport.update(width, height, true);
}

```
> 3 votes

---
Tags: libgdx, resolution
---


# Question
Title: New to OpenGL , having trouble understanding matrix transformation
I have modest experience of developing games with sdl , libgdx , unity etc. But never got into learning any low level API. So I thought about learning OpenGL and got started with tutorials provided by lazyfoo.net.(Yes I know he is using the legacy OpenGL but he migrates to modern OpenGL as he progresses through the tutorials).

On the fourth chapter he shows the use of glPushMatrix() and glPopMatrix (). Up until then I had the understanding that whenever I translate the modelview matrix that translates the whole gameworld. Now this process of saving the current matrix on stack has put me into some confusions.

They are:
1.If I push the current matrix on the matrix stack and make change to current state, then pop that saved state again; how are these transformations combined into one matrix? 2.In the tutorial he shows how to do scrolling background with four quads in the background.He translates the matrix to position the camera in the proper place based on user input. Then he pops the matrix from the stack in the render method and translates it to four different positions to draw four quads. My question is why don't we see the quads moving with the camera(which means not moving at all relative to the camera) since they are drawn relative to the camera.
In key input function:
```
//Take saved matrix off the stack and reset it
glMatrixMode( GL_MODELVIEW );
glPopMatrix();
glLoadIdentity();

//Move camera to position
glTranslatef( -gCameraX, -gCameraY, 0.f );

//Save default matrix again with camera translation
glPushMatrix();

```

in render function:

```
//Pop default matrix onto current matrix
glMatrixMode( GL_MODELVIEW );
glPopMatrix();

//Save default matrix again
glPushMatrix();

//Move to center of the screen
glTranslatef( SCREEN_WIDTH / 2.f, SCREEN_HEIGHT / 2.f, 0.f );

//Red quad
glBegin( GL_QUADS );
    glColor3f( 1.f, 0.f, 0.f );
    glVertex2f( -SCREEN_WIDTH / 4.f, -SCREEN_HEIGHT / 4.f );
    glVertex2f(  SCREEN_WIDTH / 4.f, -SCREEN_HEIGHT / 4.f );
    glVertex2f(  SCREEN_WIDTH / 4.f,  SCREEN_HEIGHT / 4.f );
    glVertex2f( -SCREEN_WIDTH / 4.f,  SCREEN_HEIGHT / 4.f );
glEnd();

```

These all might be very silly questions and I believe they are. I think there is a problem in my understanding of how matrices work in OpenGL. It would be very nice of you to enlighten me on this matter :)

# Answer
> 0 votes
There are 3 heavily used transformation matrix values, as follows

For each object in the scene, a World transform that takes vertex coordinates relative to the origin of a mesh/model and converts them to World coordinates relative to the World origin. This transform is made up of the combined Position, Orientation, and Scale of a specific object in the scene.

For each camera in the scene, a View transform that takes world coordinates and converts them into camera relative coordinates.. This transform is made up of the position and orientation of the camera/eye within the scene (it is also possible to scale here but this ability is seldom used)

And finally, for each Viewport (for most games only one, but think about modeling apps like 3DS Max etc that allow you to set up top/front/right/perspective views of the same model as an example of multiple viewports), a Projection transform that takes camera relative coordinates and translates them into "screen" coordnates (which are 2D coordinates suitable for selecting a pixel in the back buffer to be written to by your pixel shader). This transform is made up from the aspect ratio, field of view, and center of view offset of the viewport.

These three transforms, or some combination of them, get passed off to your vertex shaders so the shader can convert vertex lists in GPU memory into screen coordinates. This vertex information usually specifies triangle lists, and these triangles are clipped against the viewport. If the clipped triangle covers any pixels in the viewport, those pixels are scanned, and the pixels shader is called to generate color information for that pixel using color, uv, normals, and any other data passed in the vertex structure. All the color/uv/normal/etc data for the 3 verticies that make up the triangle being scanned are blended based on the distance of the current pixel from each of the 3 verticies. That covers the basics of vertex transformation and the rendering pipeline in modern graphics API.

As mentioned in previous comments and answers, you need to get away from the old style OpenGL techniques which were designed to support graphics cards with fixed function pipelines and no shader capability at all. You need to concentrate on things like vertex buffers, index buffers, texture buffers, and constant buffers, all of which are used to store information persistently on the GPU to be reused over and over during each rendering pass. For simpler applications where you do not have dynamic vertex/index/texture data, the rendering portion of your game loop will be little more than updating the constant buffers that the shaders use to access the transforms, telling the GPU which shader to actually use for the next draw command, and of course making the draw call that will kick off the processing of vertex data to pixel data.

---
Tags: opengl, matrix
---


title: How to create Whirlpool/Vortex effect?

text:
# Question
Title: How to create Whirlpool/Vortex effect?
Im trying to make a Vortex effect on a Circle Body that is a Sensor. I've been looking for this and all examples i look for are in C++ or Objective C and i dont seem to translate them well.

when my objects collition, it calls beginContact(..) and it sets a flag so that i can call bodyToUpdate.applyForce(...);

```
 public void beginContact(Contact contact) {
             setColliding(true);
 }

 //updating collition every frame
 public void act(){
     if (colliding) {
        ball.getBody().applyForce(....);

 }

```

how to calculate the amount of force to apply every frame to make it a vortex?

so i now have the object going straight to the center of the vortex, but no "spin"

```
public void act() {
    if (colliding) {
        ball.getBody().setLinearVelocity(0, 0);

        ball.getBody().applyForce((portal.getBody().getPosition().x - ball.getBody().getPosition().x) * i,
                (portal.getBody().getPosition().y - ball.getBody().getPosition().y) * i,
                ball.getBody().getPosition().x, ball.getBody().getPosition().y, true);

        i++;
    } else
        i = 10;
}

```

# Answer
If you can make the ball travel to the center of the vortex, you have half the answer. In potential flow theory, this is known as a sink.

The other half of the answer also comes from potential flow theory, where you can make use of the irrotational vortex:

<sup>"Irrotational vortex" by Silver Spoon is licensed under CC BY-SA 3.0</sup>

The equation describing the tangential component of the flow (relative to the vortex center) is:

,

where `r` is the distance to the centre of the vortex from the point of interest, and `\tau` is the vortex strength (you can tune this to your particular vortex).

For each body inside the vortex, the first step is to calculate the 'flow' speed at the centre of mass of the body. But now what? You can't just set the speed of the body to that of the vortex, because then the initial tangential momentum the body had when coming into the vortex doesn't have any effect. I would instead reccomend that you use the velocity to apply a drag force. I've already spelled out how to incorporate drag in another answer of mine, so I won't regurgitate it here.

As a side note, you might want to re-implement your sink in a similar way, where the *radial* flow speed is given by:

This equation can easily describe a source or a sink, depending on the sign of `Q`.

Then you can actually just compute the vector sum on the tangential and and radial velocity components, and use the resultant velocity vector to calculate the drag force:

To summarize, I recommend that you superimpose the sink and the vortex to achieve the whirlpool to get a resultant flow velocity at the centre of mass of each body; then use that velocity to calculate an appropriate drag force to apply to the body.

If you want to read more about potential flow, I recommend these MIT lecture notes.
> 1 votes

# Answer
My answer might be too shortcomed if I am missing something, but if all you want is to add additional force to spin things in a vortex way, all you need to do now is to act another force on each of the affected bodies, which goes in the tangent of the angle between it and the vortex center.

So, if *angle* is the radian angle between the vortex center and the body that needs to spin, v1 will be the direction vector from the center to the body, aiming at this angle: v1 = (cos(angle), sin(angle))

From v1, you compute v2 as its orthogonal vector: v2 = (v1y, -v1x) and then use v2 as a new force that accounts for spin. Be careful. if the magnitude of this spin force is too big, it can probably go outside of the vortex orbit, so make sure you balance both forces so it spins but still keeps approaching the middle of the vortex. Let me know in the comments if something is unclear.
> 0 votes

---
Tags: java, libgdx, box2d
---


# Question
Title: Why is there a huge update-delay in my client/server code?
I'm working on my Java game with Libgdx and having trouble with the network code. I can create a server, make multiple clients connect to it, but there is a huge delay between the player's input and the movement.

This is basically how it should work:

1. SERVER: (Launch and listen to connection.)
2. **CLIENT**: I want to connect
3. SERVER: OK, here is the map and all other data
4. **CLIENT**: I pressed "D"
5. SERVER: OK, I move this player, here is your position
6. **CLIENT**: I received my position

On the 2 last steps, when I pressed an input, the server gets it correctly and updates the position and immediately sends the position to the player, but here is my problem:

Server log (the numbers are X- and Y-coordinates):

```
Sat Sep 20 18:49:16 CEST 2014 : Send 2356.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Send 2358.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Send 2360.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Send 2362.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Send 2364.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Send 2366.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2368.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2370.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2372.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2374.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2376.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2378.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2380.0 1376.0

```

Client log:

```
Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Receive : 2336.0 1376.0

```

As you can see, the player receives the data at the wrong moment. Here is when the client start to receive

```
Sat Sep 20 18:49:18 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:18 CEST 2014 : Receive : 2338.0 1376.0
Sat Sep 20 18:49:18 CEST 2014 : Receive : 2340.0 1376.0
Sat Sep 20 18:49:18 CEST 2014 : Receive : 2342.0 1376.0
Sat Sep 20 18:49:18 CEST 2014 : Receive : 2344.0 1376.0

```

As you can see, there is almost a 2 seconds of delay (something like 1.6 / 1.7s).

This is how I send/receive data:

**Sending**:

```
synchronized(this.gestionPlayers) {
   for(GestionPlayer gp : this.gestionPlayers) {
        if(this.serializablePlayer.size() > 0)
            gp.sendPlayer(this.serializablePlayer);
    }
}

```

`sendPlayer` function:

```
try {
    this.objectOut.writeObject(sp);
    this.objectOut.reset();
} catch (IOException e) {
    this.actif = false;
    e.printStackTrace();
}

```

**Receiving**:

```
Vector<SerializablePlayer> p =
    (Vector<SerializablePlayer>) this.objIn.readObject();
this.map.addNewPlayers(p);
this.map.multiplayerRender();

```

`SerializablePlayer` contains the player's ID and coordinates.

If you need more information, just ask. This is the last step in my multiplayer game and I'd be happy if you could help me! :)

# Answer
Your server is more authoritative than it needs to be. The client needs to start moving as soon as the button is pressed, so there is no perceived lag. The server can then essentially replicate packets for other players, (maybe run a physics-sanity-check against a stored world model to prevent cheating, like warping through walls and such). Time stamping the packets and implementing motion prediction helps smooth out player motion on other players' screens.

This GDC presentation (1.5 hours) goes into fine detail on how client/server latency impacts perceived gameplay. It's worth a watch just to be aware of the potential problems of making portions of the gameplay client-authoritative vs server-authoritative, and how to modify game mechanics to hide or eliminate perceived lag.
> 2 votes

---
Tags: java, libgdx, multiplayer, client-server, lag
---


# Question
Title: How do I ensure my skybox is always in the background, with OpenGL?
I created a skybox in OpenGL (through LWJGL), but the only way I found to render it behind all objects was to make it very big. This leads to ugly edges between the 6 skybox planes.

Optimally, I would draw a small skybox and disable DepthTesting on all other objects, but since I want those to display in the right depth order, that isn't possible.

How can I do this?

# Answer
> 5 votes
```
glDepthRange (1, 1);

```

Job's a good 'un, done.

---

How this works:

`glDepthRange()` remaps depth values for the purpose of interacting with the z-buffer. Setting `glDepthRange(1,1);` makes every fragment, regardless of how close or far it actually is from the camera, be treated as if it was exactly at the far plane.

Remember to return it to its default `glDepthRange(0,1)`-setting before drawing other objects. Further details in this StackOverflow question.

# Answer
> -1 votes
the size doesn't matter so much as does the texture that you are applying to the skybox (at least so long as its bigger than your playspace, there are apps out in the wild that will help you create skybox textures with seamless edges. If you are looking to use procedural generation your skybox, you have to do some flat to spherical projection so that as you fill the pixels, they appear to to have information from the correct direction.. I was working on a skybox for a space game using perlin noise and other techniques to get nebular clouds and stars sprinkled over the skybox, so just using the 3D coordinates of the pixel on the plane wasnt enough to pass to the noise functions, I had to treat that 3D coord on the skybox plane as a direction vector, then normalize it before passing it to the noise function (essentially putting the point on the surface of a unit sphere before using it to figure out what the pixel color shoudl be)... that fixed the projection problem and eliminated all visible edges in the skybox.

There is a skybox generator for Blender, an app called SpaceScape, and a FilterForge plugin for photoshop to help with creating skyboxes... I'm sure all of them do something along the lines of what I had to do for my procedural skybox generator.

---
Tags: opengl, java, lwjgl, skybox, depth
---


# Question
Title: How common is arachnophobia among gamers?
I am currently designing a spider as a monster for my game. During my research I found that there seems to be a surprisingly large amount of players who suffer from extreme arachnophobia and get panic attacks when they see a spider on their screen, even when in a context of a video game. This makes it impossible for them to enjoy games which feature spiders. There is a whole community of modders who work on mods to remove any spiders from popular games and thus make them playable for these people.

So I wondered if I might alienate a part of my target audience by adding spiders to my game. Are there any reliable numbers about how large the community of arachnophobic gamers really is?

# Answer
> 3 votes
You can't please everyone. Every feature you add to your game will disadvantage or annoy someone. Deciding to put *graphics* in your game disadvantages **4.2%** of the world population and *sound* **10%**.

*Arachnophobia* prevalence is estimated at **3.5%**.

The issue is more complex than number comparison however. While there are international standard diagnosis criteria for medical conditions, they're a bit arbitrary by necessity. Given a criterion of "significant hindrance to daily life", the level of hindrance deemed to be *significant* is up to an informed medical professional's judgement.

There's also a question of severity. Extreme-degree arachnophobics are likely to suffer more from playing a spider-containing game than a blind player is to be annoyed at playing a graphics-containing game. (Unless of course the spider was insignificant and stylised, but the graphics low-contrast and hard to see, in which case it would be the other way around.)

---

So, what should you do?

Measuring the depth of suffering your actions bring to others is impossible. While there are various guidelines, the distinctions between good and bad game design are a bit arbitrary by necessity. Given a task of "being good to your players", the correct levels of graphics, sound and spiders are...

Does any of this sound familiar?

...up to an informed game developer's judgement.

# Answer
> 1 votes
Arachnophobia is very widespread. But, as an arachnophobic(and gamer) myself, I do not get panic attacks. Actually I do not know anybody who gets panic attack for looking at drawn spider, those cases are very rare. If it is so advanced illness, the person would be probably even afraid to turn a computer on - there are pictures of spiders everywhere.

Surprisingly, killing spiders as an arachnophobic can be even more satisfying than killing regular monsters, especially if you can kill them from afar (and if they dont jump onto screen).
I really doubt high number of really serious arachnophobics(heart attacks) play games - spiders are very favorite monsters in games (show me any RPG without spiders!).

For my original link to paper listing exact % numbers see comments(or Anko's new answer).

---
Tags: graphics-design, demographics
---


title: Weird inheritance hierarchy?

text:
# Question
Title: Weird inheritance hierarchy?
In my RPG, all Food objects should be possible weapons. For instance, I want the player to be able to to try kill bunnies with a cherry or a watermelon.

The problem is that the easiest way to do this is a bit counter-intuitive (and ugly, IMHO):

Item \< Weapon \< Food

*(superclass \< subclass)*

I wrote an interface (IWeapon) and made Weapon and Food implement it, but the amount of repeated code was ridiculously huge (what indicates that they should share a common class, right?).

I do not think that I want Potions, for instance, to be usable as weapons (I don't want to let the player hit the target with a filled vial).

How should I solve my current problem? Should I use inheritance or program to the interface?

What about extensibility? Does it make sense to let all items have attributes such as damage, hitRate, integrity, etc.?

# Answer
@wondra's comment that anything that does damage is a `Weapon` is spot-on. Don't get confused by having the class name be restrictive when it's not the right word. Perhaps in this case you want the class to be `DamageDealer` instead of `Weapon`.

Another, and better, option is to use interfaces for the object types. This way you get a broad hierarchy instead of a deep one, which is easier to manage when it gets large.

A third, and even better, option is to use composition. In this case your Item class would have objects for `DamageDealing` and `Edible` and `Wearable` and each individual object may or may not have those objects exist. This gives you the advantage of being able to at run time decide that jello can't ever be a weapon but flan is both a weapon and wearable.

The third option is what I've done in my overly-complex rpg in which anything can potentially be a weapon, or container, or wearable. It's worked out quite well for me as the complexity has grown.
> 1 votes

---
Tags: java, rpg, inheritance
---


title: Can someone explain dual contouring?

text:
# Question
Title: Can someone explain dual contouring?
I've been trying to understand voxel rendering and have been looking at dual contouring (DC).

So far I understand this much:

1. Run a density function for a set of grid points (i.e noise function)
2. Find which edges in the gird contain changes between end-points
3. From these edges create intersection points (i.e vectors)

**Now this is where I'm stuck, next would be to generate normals, but how?** When looking at this topic this image normally crops up.

Doing research indicates that the normals would be generated from an isosurface. **Is it correct to think that I go from noise to isosurface to normals? If so how would I accomplish each step?**

To my understanding, the next step would be the following from the DC paper;

> For each edge that exhibits a sign change, generate a quad connecting the minimizing vertices of the four cubes containing the edge.

**Is this quote represented by the above image?**

Finally the next step would be to run the QEF with the intersecting points and normals and this would generate my vertex data. **Is this correct?**

# Answer
The normals would be generated based on the gradient of the density function at the same time that you get the intersection points between the edges and the surface. If it's something simple and closed-form like a sphere then you can calculate the normals analytically, but with noise you'll need to take samples.

You have the next steps in the wrong order. First, you generate a vertex for each *cell* that exhibits a sign change. The QEF you are minimizing is simply the total distance to each of the planes that are defined by the intersection point/normal pairs for that cell. Then you walk through the edges that exhibit sign changes and create a quad using the four adjacent vertices (which are guaranteed to have been generated in the last step).

Now, my biggest hurdle in implementing this was solving the QEF. I actually came up with a simple iterative solution that will run well on (for example) a GPU in parallel. Basically, you start the vertex in the centre of the cell. Then you average all the vectors taken from the vertex to each plane and move the vertex along that resultant, and repeat this step a fixed number of times. I found moving it ~70% along the resultant would stabilize in the least amount of iterations.
> 4 votes

# Answer
From reading the paper up to page 2, it appears the weights of volume are stored at the corners of the grid instead of being the weight of the cube itself as normal Marching Cubes style algorithms prefer. These corner weights define a point between along the edge between 2 corners where there is a sign change from corner to corner.. Edges with sign changes also store a normal for the edge which are the angled line in your 2D representation in the OP. That normal information is defined during the creation of the volume (by whatever editing tool or procedural volume creation method is being used), not after the isosurface is generated as would be expected by a Marching Cubes style algorithm. This normal data "states" that the line/surface passing through the point must have the predefined normal value. In cases where Marching Cubes would bend the line at that point to mate up with another point on an adjacent edge, Extended Marching Cubes and Dual Contouring both extend the line/surface out until it intersects with the line/surface passing through the point on the adjacent edge that has a different normal value. This allows creating sharp corners from the volume data where basic Marching Cubes algorithms would round off the surface somewhat. I'm not quite understanding how QEFs (quadratic error functions) play into this except that it seems they make it easier to compute the extended point within a cube where a corner will be located.

Note that I've been talking about lines and edges here in the 2D sense as depicted by the representation in the OP.. I would have to do some more reading and thinking to extend this to 3D for volumetric mesh generation.

To address the 2nd half of your question about how to generate the normals, and thinking from a noise driven procedural point of view, it seems like you would fill your volume with noise data then look for edges with sign changes, then examine the 4 cubes that share the edge to figure out where what triangles are going to be generated, and compute the vertex normal like you would for any other intersection of multiple triangles, taking the average of the normals for each triangle that shares the vertex. This is very speculative on my part as the paper deals mostly with CSG operations and volumes generated from scan-converted meshes, both of which have well defined normals on the surfaces.

I hope at least the 1st part of this answer addresses the differences in how the weight data is represented and used in a manner quite different from basic Marching Cubes, and why the normal data has to be created fairly early on in the volume generation process, where with basic marching cubes normals are typically created as a last stage in the mesh generation process.
> 1 votes

---
Tags: mathematics, rendering, voxels
---


# Question
Title: SHMUP: who's in charge of collision detection?
Simple design question here:

In a Shoot'Em Up, where you often have to deal with hundreds of bullets / missiles / weird flying stuff, who's in charge of detecting collisions? The weapon or the ship?

As there is usualy less ships than bullets displayed on screen, I tend to believe that would be smarter if ships could be in charge of it. But is it really smarter?

# Answer
> 3 votes
The simple answer here is that as the developer, *you* are in charge of collision detection. But "who is responsible" is not really an important question when it comes to collision detection. The important question is: "How many pairs of objects must be tested for collision each frame?"

Now, in a shmup most collisions take place between a bullet/munition and a player/enemy unit. Collisions between two munitions and collisions between two units are usually ignored. This means all we need to do is keep two lists of objects - one for units and one for munitions. In fact, you can probably split up objects into even more groups, reducing the number of potential collisions further. For instance, you could separate player munitions from enemy munitions and player units from enemy units, since player munitions will probably only ever cause damage to enemies, and enemy munitions will only cause damage to players.

With this system, there's probably no optimization required. Each object in one list can be tested against every object in the other. If we have `N` units and `M` munitions then we end up doing `N*M` collision checks. We may have a very large `M`, on the order of several hundred or more, but `N` is probably on the order of 3-6, perhaps up to a dozen.

If you're working on mobile, or you have so many objects that you're still having performance issues, or you need more flexibility to allow collisions between objects of the same type, then chances are you'll want to use a broad-phase algorithm, utilizing a space partitioning data structure to reduce the set of potential collision-pairs before doing the actual collision-detection. You can reinvent the wheel yourself here if you like, but a far less painful approach is to simply use a physics library like Box2D or Bullet and let it take care of the collision detection for you.

---
Tags: collision-detection, shoot-em-up
---


# Question
Title: What's the point of [HiddenInInspector] (as opposite to [NonSerialized])?
I understand the difference between `[HiddenInInspector]` and `[NonSerialized]`, what I'm missing is the use case for `[HiddenInInspector]`: so far every time I've encountered it, it was used by developers who weren't aware of `[NonSerialized]`, that would actually have meant to use that. The result is that they risked to get unexpected values when the variable in question was deserialized.

So, in which case it turns out to be useful to hide something from the inspector but to serialize it? If there is such case, are there any known precautions to take in order to prevent unexpected behaviour?

# Answer
I used `[HiddenInInspector]` quite often. 2 recent use cases I encountered:

**First Motivation: Properties that must be serialized but user doesn't need to be aware of and shouldn't modify explicitly.**

Example: I wrote a Behavior Tree plugin these days. You can edit the tree layout graphically through an editor extension (a UI similar to Mecanim). Every node is represented by a `ScriptableObject` that as a `Rect` defining its bounds marked with `[HiddenInInspector]` attribute. This way the user is allowed to layout the tree nodes only interacting through the gui and not accessing directly the `ScriptableObject`. In addition to **prevent possible errors** and inconsistency it helps to **keep the node inspectors clean** from data not relevant to user interaction.

**Second Motivation: Minimize Custom inspector code**

Example: suppose you need to write some custom inspector code. In my use case I need to guarantee that certain serialized property are not set directly but through class methods to produce the required side effects (es. when add a child to a node must also update the parent reference in the child class.).

I need to write a custom inspector but the target class has a lot of properties, and I need to customize only a few. I can mark the property I need to manage explicitly with `[HiddenInInspector]` , call `base.OnInspectorGUI` from the custom inspector code (which draw every other property in the default way) and just write a bunch of line of codes to customize access to the required fields.

> If there is such case, are there any known precautions to take in order to prevent unexpected behaviour?

`SerializedProperty` are initialized with their default value. Btw in the most common scenarios when you hide them is because you are setting them explicitly somewhere else, so it's up to your custom code to make the relevant checks. In any case unexpected behaviors are potentially the same of a normal serialized property.
> 3 votes

# Answer
HiddenInInspector is useful when you want to serialize something derived from other settings, and not have to have code in the Awake method or elsewhere to make sure that the hidden value has the correct derived value when instances are deserialized. This puts the burden of computing or extracting the derived value from the other settings on the editor code, instead of on the GameObject scripting logic, and thus not part of the released game code.

I've only once found a use for HiddenInInspector when I was creating some GUI extensions to an existing GUI framework to create a dynamic inspector element that used reflection on the data object to be edited in the inspector. I used HiddenInInspector to hide the cached reflection data so that it was serialized and didn't have to be frequently rebuilt.

There may be other uses, but that is the only one I've run into so far.
> 0 votes

---
Tags: unity
---