# Question
Title: Should I implement anti-aliasing by rendering large and scaling down?
Having read about anti-aliasing, I came to realise that I could render my scene 8× the original size of the screen, then shrink it to render it on my original screen to improve the effect that I have rendered on the screen.

Is this a good idea? How can I do this? Do I need a shader?

# Answer
Um, why don't you just use multisampling like everyone else? Even if you're using deferred rendering, there are ways to use multisampling in tandem with that.

Multisampling covers triangle edge aliasing, while anisotropic filtering covers texture aliasing. Between those two, you pretty much have all the antialiasing techniques you need. Unless you're procedurally generating textures, of course.
> 4 votes

# Answer
The modern technique is to render your scene to one or several framebuffer objects of the desired size, then use these framebuffer objects as textures and render them to the screen. Basic usage means setting the texture to `GL_LINEAR` and does not require a shader. Advanced usage means using a shader to enhance the antialiasing, for instance by doing edge detection or picking from several FBOs (to achieve quincux antialiasing, for instance).

Another way is to use the accumulation buffer (tutorial here). This will make advanced usage such as gamma correction more difficult to implement, but the basic idea is very simple. It doesn't require shaders either.
> 3 votes

# Answer
If you're using D3D there's no need for shaders to implement this. Just create your extra large render target, render your scene to that, and at the end of the frame call StretchRect() to do the resizing of the big render target to the back buffer.

Depending on where the aliasing is coming from, this may not look any better than MSAA, and MSAA is much quicker because it only runs the pixel shader once for each output pixel, and not eight times.

Note that even when using the fixed function pipeline any modern card will convert those settings into pixel shaders in the driver.

You should also make sure you're using the right texture filter settings, and that your textures have mip maps, as both of those are cheap to fix and can cause some nasty aliasing if they aren't right.
> 0 votes

---
Tags: opengl, antialiasing, scale
---


# Question
Title: Drawing a textured triangle with CPU instead of GPU
I understand the benefits of GPU rendering and such, but for a certain limited application I need to render textured triangles purely using CPU.

I've built a 3D engine capable of object handling, transform, projection, culling and the likes ... now all I need is a little code snippet that draws a single textured triangle onto a bitmap... any language accepted!

* **Inputs:** Texture bitmap, Triangle U/V/W coords, Triangle X/Y screen coords
* **Output:** The textured triangle drawn at the given screen coords

I've currently been using a platform function to draw triangles to screen, but I'm looking to handle it myself to speeden up the process.

# Answer
With full source (or even just a thorough explanation) of a perspective correct textured triangle rasterizer being too long for an answer, I'll gladly refer you to Chris Hecker's classic series of articles on the topic, including source:

http://chrishecker.com/Miscellaneous\_Technical\_Articles

From your link I assume you are using Flash as a platform, so I sure hope you know how to efficiently turn on/off individual pixels there.
> 9 votes

---
Tags: 3d, textures, performance, uv-mapping
---


title: Browser Game Database structure

text:
# Question
Title: Browser Game Database structure
```
users
id
username
password
email
userlevel

characters
id
userid
level
strength
exp
max_exp

map
id
x
y

```

This is what I have so far. I want to be able to implement and put different NPC's on my map location. I am thinking of some npc\_entities table, would that be a good approach? And then I would have a npc\_list table with details as how much damage, level, etc the NPC is.

Give me some ideas with the map, map entities, npc how I can structure it?

# Answer
> 5 votes
Your question made me think that you're starting your game with the DB design, and this seems to be the case. Now you basically have some tables and you want to add more "stuff".

Let me say that starting with the DB is a **very bad** idea. Firstly it doesn't represent a game-world properly and is not suited for lots of changes. Let's assume that you have a nice and normalized DB design and you notice that you'll have to change things because you want to add "feature X". That might force you to re-do the entire architecture.

I suggest you start the other way round. Define what your game should do. Write it down. If you're eager to start coding, then write some code that works with values from a text-file or hard-coded values. Once you figure out what you need and how things play together, you can plug the DB into that.

The DB isn't your game, it's just a data-storage. Your game should be written in a way that this storage is abstracted so that you can start with some simple (hard-coded) values and later plug in the code that actually does the DB connection etc. Also things like the "login" (eg. username, password etc.) is really not something you need right off the bat.

---
Tags: databases, sql
---


# Question
Title: Fastest way to group units that can see each other?
In the 2D game I'm working with, the game engine is able to give me, for each unit, the list of other units that are in its view range.

**I would like to know if there is an established algorithm to sort the units in groups**, where each group would be defined by all those units which are "connected" to each other (even through others).

An example might help understand the question better (E=enemy, O=own unit). First the data that I would get from the game engine:

```
E1 can see E2, E3, O5
E2 can see E1
E3 can see E1
E4 can see O5
E5 can see O2
E6 can see E7, O9, O1
E7 can see E6
O1 can see E6
O2 can see O5, E5
O5 can see E1, E4, O2
O9 can see E6

```

Then I should compute the groups as follow:

```
G1 = E1, E2, E3, E4, E5, O2, O5
G2 = O1, O9, E6, E7

```

It can be safely assumed that there is a commutative property for the field of view: \[if A sees B, then B sees A\].

Just to clarify: I already wrote a naïve implementation that loops on each row of the game engine info, but from the look of it, it seems a problem general enough for it to have been studied in depth and have various established algorithms (maybe passing through some tree-like structure?). My problem is that I couldn't find a way to describe my problem that returned useful google hits.

Thank you in advance for your help!

# Answer
> 7 votes
If your "can see" relation is symmetric, so that "A can see B" implies "B can see A", then the groups you want to compute are the connected components of the graph defined by the "can see" relation. As others have noted, there are simple algorithms for computing these, such as:

```
while ungrouped units remain:
    let u = arbitrary ungrouped unit
    let g = new group
    let s = temporary stack
    assign u to g
    push u onto s
    while s is not empty:
        let v = topmost unit in s
        remove v from s
        for each unit w that v can see:
            if w is ungrouped:
                assign w to g
                push w onto s
            end if
        end for
    end while
 end while

```

(A queue or any other collection that efficiently implements the operations "add new element" and "remove and return some element" can be used in place of the stack `s` above.)

If your "can see" relation is *not* symmetric, you need to decide whether you want your groups to be the *strongly* or the *weakly* connected components. For weakly connected components, the algorithm above will work as is, except that the line `for each unit w that v can see` should be replaced with `for each unit w that can see v, or that v can see`. For strongly connected components, you can use one of the algorithms (Kosaraju's, Tarjan's or Gabow's) mentioned on the linked Wikipedia page.

For non-symmetric relations, you may also want to compute the transitive closure of the relation, or of its strongly connected components. For this, you can use the Floyd–Warshall algorithm; see this answer on SO for (a bit) more information.

---

**Ps.** As the Wikipedia article I linked to above notes, it may be more efficient to dynamically update the groups as the visibility relation changes. I'm not familiar with the advanced(?) algorithms mentioned on Wikipedia, but it shouldn't be hard to cobble together something that at least beats recomputing the groups from scratch every time.

One half of this is easy: if two units in different groups acquire a line of sight between them, merge the groups. Dealing with units losing sight of each other is a bit more tricky; one simple but perhaps not optimal solution is to rerun the grouping algorithm for the units in the affected group whenever that happens. There are some optimizations you can make to that, if the visibility changes occur one pair of units at a time:

* If a unit could only see one other unit, and loses sight of it, just remove it from its previous group and assign it to a new group.
* Otherwise, you could start at one of the affected units and run an A\* search on the visibility graph (using e.g. straight-line distance as the heuristic) for the other unit. If you find it, the group didn't break up; if you don't, the set of units the search visited forms the new group.
* You could try to guess which of the two units is more likely to belong to the smaller half of the group, if it does split, and start the search from that unit. One possibility would be to always start from the unit that can directly see fewer other units.

# Answer
> 4 votes
What you have is a connectivity graph. And generally, the best way to group the connected nodes (ie: characters) together is with a graph search algorithm. Depth-first, breadth-first, whichever. All you're doing is building a list of which nodes are reachable from all others. So long as your graph is undirected (if A is visible to B, then B is visible to A), this works fine.

There may be some algorithms to improve this for specific cases. For example, if sometimes characters don't move (and terrain doesn't move too, so immobile characters remain visible) then you can choose not to test them again to update their connectivity graphs.

But in general, you're going to have to retest visibility every frame. Odds are, that's going to be slower than the graph traversal to find the visibility groups.

# Answer
> 3 votes
Seems like a standard graph connectivity problem. There may well be some sort of algorithm for this, and it might look like the following:

```
remaining units = all units
for each unit in remaining units:
    current group = create a new group
    add this unit to current group
    for each unit visible to this unit:
        if unit is in a group already:
            merge current group into that existing group
            set current group as that existing group
        else:
            remove that unit from remaining units
            add that unit to current group

```

I expect it is possible to implement this via a tree, like hierarchical clustering, but I doubt that would work out quicker - trees tend to be O(log N) whereas most of the checks I give above can be implemented as O(1).

# Answer
> 2 votes
I agree with all others who responded in terms of this being a graph connectivity problem, however let me point out that what you need here is the Delaunay Triangulation graph generated from all your relevant units. What this does is ensures that only units closest to one another will be connected in the graph that you generate. You will find it very challenging to do this any other way, because graph crossings (non-planarity) will cause units too far from one another to be incorrectly connected within the graph.

The above only applies if you are using a continuous space (as in most free-movement FPSes); however if you already have an underlying grid (a planar graph) on which your units move, then you can just use that to evaluate connectivity instead.

---
Tags: algorithm
---


# Question
Title: How to get several frequency ranges at the same time in fmod?
After reading documentation and tutorials about fmod I still have a question about frequency ranges.

I've found how to get a frequency range using low and high pass DSP at the same time on the main channel, but I can't find how to get several ranges at the same time. For example I want, for a specific phase of my game, to hear range 400 to 600Hz and 1000 to 2000hz of the same sound. I tried to create a channel by range, but it doesn't seem to work (or maybe I do something wrong). How can I do that ?

Thank you

# Answer
Somewhere (on the fmod forums) someone suggested me to use low / high pass DSPs. The trick is to split signal into branches in order to only keep frequency range needed on a specific branch (a branch will handle 400 to 500Hz, an other only 1000 to 2000Hz... and so on).

If I want to isolate only 400Hz to 600Hz and 5000Hz to 10000Hz from a sound, the goal is to have something like that :

```
                         o -- HighPass -- LowPass -- o (400Hz to 600Hz)
                        /                             \
main channel output--- o                               o --- main channel input
                        \                             /
                         o -- HighPass -- LowPass -- o (5KHz to 10KHz)

```

Now let's code it (the code below presumes that you already have all your fmod stuff initialized) :

```
// Creates the sound we want to play
FMOD::Sound *sound;
result = system->createSound("science.mp3", FMOD_DEFAULT, 0, &sound);

// Declares the channels and DSP we will use
FMOD::Channel *pChan; // main channel
FMOD::ChannelGroup *pChanGrp; // channel group where we will split our signal
FMOD::DSP *pDSPhigh1; //HighPass1
FMOD::DSP *pDSPlow1; //LowPass1
FMOD::DSP *pDSPhigh2;  //HighPass2
FMOD::DSP *pDSPlow2; //LowPass2

FMOD::DSP *pDSPChanHead;
FMOD::DSP *pDSPChanGrpHead;

// let's play our sound and set our main channel pointer
system->playSound(FMOD_CHANNEL_FREE, sound, false, &pChan);

// creates the channel group and gets the head DSP pointer
result = system->createChannelGroup( "my_chan_grp", &pChanGrp );
result = pChanGrp->getDSPHead(&pDSPChanGrpHead);

// now let's create our first low pass DSP
result = system->createDSPByType( FMOD_DSP_TYPE_LOWPASS, &pDSPlow1 );
result = pDSPlow1->setParameter( FMOD_DSP_LOWPASS_CUTOFF, 600.f ); // we want the cutoff at 600Hz
result = pDSPChanGrpHead->addInput(pDSPlow1, 0); // connecting to channel group head

// now let's do the same with our second low pass DSP
result = system->createDSPByType( FMOD_DSP_TYPE_LOWPASS, &pDSPlow2 );
result = pDSPlow2->setParameter( FMOD_DSP_LOWPASS_CUTOFF, 10000.f ); // we want the cutoff at 10000Hz
result = pDSPChanGrpHead->addInput(pDSPlow2, 0); // connects to group head

// Now we need to create high pass DSP
result = system->createDSPByType( FMOD_DSP_TYPE_HIGHPASS, &pDSPhigh1 );
result = pDSPhigh1->setParameter( FMOD_DSP_HIGHPASS_CUTOFF, 400.f ); // we want the cutoff at 400Hz
result = pDSPlow1->addInput(pDSPhigh1, 0); // connects HighPass1 to LowPass1

result = system->createDSPByType( FMOD_DSP_TYPE_HIGHPASS, &pDSPhigh2 );
result = pDSPhigh2->setParameter( FMOD_DSP_HIGHPASS_CUTOFF, 5000.f );
result = pDSPlow2->addInput(pDSPhigh2, 0); // connects HighPass2 to LowPass2

// now we have to get the DSP Head pointer of the main channel and disconnect all existing DSP in order to avoid having our sound still playing without any modification
result = pChan->getDSPHead(&pDSPChanHead);
pDSPChanHead->disconnectAll(false, true);
// and finally connect channel DSP head to HighPass1 and HighPass2
result = pDSPhigh1->addInput(pDSPChanHead, 0);
result = pDSPhigh2->addInput(pDSPChanHead, 0);

// don't forget to activate your new DSP
pDSPhigh1->setActive(true);
pDSPhigh2->setActive(true);
pDSPlow1->setActive(true);
pDSPlow2->setActive(true);

```

I hope this will help someone.
> 0 votes

# Answer
High pass and low pass filters are usually shelves, that is if you apply a low pass filter at a given frequency then you're losing frequencies about that cutoff frequency and can't get them back.

In order to get more than one limited range of frequencies, the most straightforward way is to use EQ.

One of the FMOD dsp types of DSP is FMOD\_DSP\_TYPE\_PARAMEQ. For each frequency band you want to affect, create one FMOD\_DSP\_TYPE\_PARAMEQ unit object and set the parameters appropriately. With EQ, you can't directly affect the range. Instead, you set a center frequency and the bandwidth or Q (more about EQ here: http://tweakheadz.com/EQ\_and\_the\_Limits\_of\_Audio.html).

> FMOD\_DSP\_TYPE\_PARAMEQ
>
> Enumeration
>
> typedef enum { FMOD\_DSP\_PARAMEQ\_CENTER,
> FMOD\_DSP\_PARAMEQ\_BANDWIDTH, FMOD\_DSP\_PARAMEQ\_GAIN } FMOD\_DSP\_PARAMEQ; Values
>
> FMOD\_DSP\_PARAMEQ\_CENTER Frequency center. 20.0 to 22000.0. Default = 8000.0.
>
> FMOD\_DSP\_PARAMEQ\_BANDWIDTH Octave range around the center frequency to filter. 0.2 to 5.0. Default = 1.0.
>
> FMOD\_DSP\_PARAMEQ\_GAIN Frequency Gain. 0.05 to 3.0. Default = 1.0.
>
> Remarks
>
> Parametric EQ is a bandpass filter that attenuates or amplifies a selected frequency and its neighbouring frequencies.
>
> To create a multi-band EQ create multiple FMOD\_DSP\_TYPE\_PARAMEQ units and set each unit to different frequencies, for example 1000hz, 2000hz, 4000hz, 8000hz, 16000hz with a range of 1 octave each.

Here's a quick example (assuming you initialized FMOD and omitting error checking for brevity):

```
FMOD::DSP* dspObj;

systemPtr->createDSPByType(FMOD_DSPTYPE_PARAMEQ, &dspObj);
dspObj->setParameter(FMOD_DSP_PARAMEQ_CENTER, 500);
dspObj->setParameter(FMOD_DSP_PARAMEQ_BANDWIDTH, 0.2);
dspObj->setParameter(FMOD_DSP_PARAMEQ_GAIN, 3.0);
FMOD::DSPConnection* eq1Connection;
systemPtr->addDSP(dspObj, &eq1Connection);

systemPtr->createDSPByType(FMOD_DSPTYPE_PARAMEQ, &dspObj);
dspObj->setParameter(FMOD_DSP_PARAMEQ_CENTER, 1500);
dspObj->setParameter(FMOD_DSP_PARAMEQ_BANDWIDTH, 5.0);
dspObj->setParameter(FMOD_DSP_PARAMEQ_GAIN, 3.0);
FMOD::DSPConnection* eq2Connection;
systemPtr->addDSP(dspObj, &eq2Connection);

```

In DAW-land, you could route the audio from your source channel to two new aux channels and apply separate sets of high and low pass filters to achieve something sort of like this. However, I don't believe FMOD supports that kind of routing and it might raise performance concerns. Also, taking into account resonance the final mix using this approach could sound very strange.

Also, FMOD has the capacity to load some VSTs. If you're just exploring the API and not trying to implement FMOD for a full-on game, look at http://kvraudio.com and see if you can find some VSTs to do what you're trying to achieve.

I also don't know if it's possible to cut everything except for multiple frequency band sin FMOD. This is similar to the use case for a comb filter, but if you're doing this much synthesis you may be better off working on the sample level and implementing your own DSP effects by adding callbacks into a FMOD\_DSP\_DESCRIPTION structure.
> 2 votes

---
Tags: fmod
---


# Question
Title: Is SharpDX mature enough to adopt yet or should I just start using SlimDX right now?
I'm about to stop my game-project in XNA because from what I can gather it's development is coming to an end (and it's already behind current technology). Therefore, I need to adopt a new framework or API.

I have just spent 2 days looking at C++ and decided it's really not for me - however I do find the raw access to DirectX appealing. SharpDX sounds like a good place to start, but it has no documentation and no code comments. I feel like it's not quite ready for use.

I'm interested in the opinions of people that have used either or both of these frameworks, to help me decide for sure which one I should learn? Thanks for any advice.

# Answer
> 16 votes
I'm the author of SharpDX, so my advice is going to be biased, but I would like at least to respond about some of your concerns.

About SharpDX documentation, the current state is very limited, as I have been working so far to bring the whole DirectX API accessible from .NET and new Win8 OS. As I'm closed to finish on this side, I'm working on providing a full website and some articles to explain key concepts of SharpDX, and how you can get the best of it. Also, keep in mind that this project is mainly to bring DirectX to .NET, so It is still a low level API. So it requires you to dig a little bit into the behavior of the C++ API in order to understand how it is working. Fortunately, almost every single method in SharpDX does map to a single method in the DirectX API, so It is easy to check how to use a method by checking DirectX API. The documentation system that will be available with SharpDX 2.0 final will provide a way to find a SharpDX API from a DirectX name and vice-versa.

Is SharpDX ready to be used for developing a game? In short, Yes.

First of all, I have been hired by a Japanese company to participate to the development of a new 3D engine in C#, and we are using SharpDX for the rendering backend on Windows.

Secondly, I have received lots of private mails from developers from companies that are using SharpDX to develop multimedia application (ranging from games, level editor, online photo publishing...etc.). Some of these customers are quite big (Unfortunately, I can't cite them).

Lastly, some public open source projects are using (or going to use) SharpDX for their main backend rendering. For example, Delta Engine is already using SharpDX for its Direct3D11 rendering (that will be available also for Win8). Upcomming ANX project (an open-source XNA successor) is also using SharpDX for the rendering, gamepads and audio management.

But SharpDX is just a step on the road to build a game engine, and then a game. Because the API is low-level, you can't expect to have the same kind of high-level features you were used to with a framework like XNA. But with a minimal framework, you could do lots of things.

Also, you could consider to use a well established product like Unity to develop portable games in C#.

---
Tags: xna, slimdx, sharpdx
---


# Question
Title: How to design a separated tutorial mode?
I'm working on a "social" game that's about 90% completion. One of the remaining features is the tutorial mode.

Basically, the tutorial mode will restrict the user to access some parts of UI and limit the features (like store items). The tutorial will only progress if a certain event is triggered, specifically following the tutorial.

The code is ready and we already have an "almost" working game. The problem is I haven't foreseen the tutorial mode while I was doing those 90%. My requirement is there shouldn't be any loading/transition from tutorial mode to normal mode. This means I have to pick up the progress from the tutorial (no re-rendering of assets and stuff).

How should I design this in a way where I won't touch anything from my old code? I want it to be as easy as just plugging it in. I don't want to jam the tutorial in my old code since this will lead to many bugs.

# Answer
Some more information would help you get better answers. Without knowing much about what type of game you have or what you level structure looks like, I can only make a stab in the dark.

That said, if I were doing something similar with my current project, I would create a special level that guides the user through the subjects in question. Your NPC's could be created with only the items you want available in the tutorial, for example.

As far as preventing access to certain UI elements, if you can't add or remove the elements you do/don't want in your tutorial, you may have to incorporate a filter into existing code in order to determine whether an element should exist or not (think "access restrictions").
> 3 votes

# Answer
I am working on a tutorial for my C# game right now. I'm separating the tutorial from the game by using events. In my game, I have a bunch of events that are triggered when the game state changes in a variety of ways: Entities moving, getting destroyed, being built, upgrade complete, etc. My tutorial listens to the events of interest and has the ability to manipulate the HUD. That's all you need. To make it perfectly clear, the game has no idea that the tutorial is happening.

This may also be important: My Tutorial is a subclass of Scenario, where the Game is always executing a Scenario. Since I'm using C#, I could feasibly take any of my Scenarios and toss them in a C# script file, but right now, all of my Scenarios are compiled directly into the game.

The class is a bit of a work in progress right now, but here's a slightly out of date version you can look at: http://asteroidoutpost.svn.sourceforge.net/viewvc/asteroidoutpost/trunk/Scenarios/TutorialScenario.cs?view=markup
> 2 votes

# Answer
I am also working on a tutorial for my flash game and this is how I have it set up. Each portion of the game checks a Tutorial object to check to see if an action is available for the player to do. If the tutorial module doesn't exist or is inactive, then we can assume that the player can do anything.

Using your Sim City game for example, let's say that when the tutorial starts you don't want the player to be able to do anything until the appropriate time. You could have flags in your tutorial object like, PLAYER\_CAN\_USE\_TOOLBAR, PLAYER\_CAN\_SWITCH\_VIEWS or PLAYER\_CAN\_DESIGNATE\_ZONE etc all set to FALSE. As the player steps through your tutorial you can then start setting those flags to true.

For your UI portion, block the signal to the model or controller that actually performs the action if your tutorial flags aren't set:

```
// If our tutorial module/tracker exists, but the action flag is set to false
// then leave our method early
if (mTutorial.isActive() && !mTutorial.checkFlag(PLAYER_CAN_DESIGNATE_ZONE)) {
  return false;
}
//Do the rest of the action here

```

For wating for specific events you could pass event back into your tutorial object to validate that is what the player needs to do to continue that tutorial step. For example, if you needed the player to create a residential zone at a particular X,Y:

```
var evt:GameEvent = new GameEvent(EVENT_CREATE_ZONE, ZONE_TYPE_RESIDENTIAL, startX, startY, endX, endY);
if (mTutorial.isActive()) {
  if (!mTutorial.checkFlag(PLAYER_CAN_DESIGNATE_ZONE)) {
    return false;
  }
  //Check to see if this event is okay
  if (!mTutorial.validateEvent(evt)) {
    //Show why the player can't do this via popup
    return false;
  }
}
//Do the rest of the action here

```

I hope that helped. Unfortunately, you'll have to add the tutorial checks into your old code to get this to work. But by assuming that all actions are valid unless the tutorial object exists should ease this integration process and allow you to minimize your bugs.
> 0 votes

---
Tags: architecture
---


# Question
Title: Implementing a Custom Mouse Cursor in XNA
I have tried making a custom mouse cursor, hiding the real mouse, taking the real mouse delta and clamping it to a maximum speed. Here is the problem:

* In *windowed* mode, the "real" mouse cursor moves off the window while the custom mouse cursor (since it's movement is being scaled) is still somewhere inside the game window. This becomes bizarre and is obviously not desired, as clicking at this point means clicking on things outside the game window. Is there any way to accomplish this in windowed mode?
* In *fullscreen* mode, the "real" mouse cursor is bounded to the edges of the screen. So I get to a point where there is no more mouse delta, yet my custom cursor is still somewhere in the middle of the screen and hence can't move further in that direction. If I wanted to clamp it to the edge of the screen when the real cursor is at the edge, then I would get an abrupt jump to the edge of the screen, which isn't desired either

Any help would be appreciated. I'd like to be able to limit the speed of the mouse.

# Answer
Let's get the obvious stuff out of the way, the tool is there: http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.mouse.setposition.aspx

In fullscreen it is easy to use, just do some controlled repositionings and the edge problem is gone. For some other games this could lead to the problem of a trapped mouse in windowed mode, but if you do it just right I think you may solve your problem without upsetting John McDonald:

Whenever the player has moved the mouse too quickly, reposition it to where the game cursor ends up, this way the player can actually still drag the mouse outside the window if so desired, and you don't get the clamping problem until you'd have to cap the cursor movement anyway.
> 3 votes

# Answer
Your object should follow the cursor...

```
Vector2 MousePos = Mouse.GetState().Position;

if (dragging)
{
   YourObject.Position += 0.1f * (MousePos - YourObject.Position);
}

```
> 2 votes

---
Tags: xna, mouse
---


title: Playing NSF music in FMOD.net

text:
# Question
Title: Playing NSF music in FMOD.net
So, as the title says, I want to be able to play NSF files using FMOD, because my project already uses FMOD and I'd rather not replace it. This will involve figuring out how existing players and emulators work and porting it. I haven't yet found an existing player that uses FMOD.

My starting point is the MyNes source from http://sourceforge.net/projects/mynes/. There are two big steps between here and what I'm looking for.

1. MyNes plays from a ROM, not NSF. So, I have to rip out the APU and get it to play NSF files.
2. The MyNes APU uses SlimDX, so I have to convert that to FMOD.NET.

I am really stuck about how to go about either of these, because I'm not that familiar with audio formats and it's hard finding resources online. So here are a few questions:

1. From what I can tell from the NSF spec at http://kevtris.org/nes/nsfspec.txt, it's just contains the relevant memory section of the ROM, plus the header. If anyone can verify or correct this that would be great.
2. The emulator APU uses data from the rest of the emulator to play, including things like cycle counts. I'm not sure what replaces this in a standalone player. Can't I just load all the music data at once into a stream and play it?
3. Joining #1 and #2, does the header data from the NSF substitute for some of the ROM data in the emulator code?
4. Using FMOD, will I be following the usercreatedsound example for loading a stream? And does this format count as PCM? Specifically MyNes says PCM8. Any tips on loading / playing the stream in FMOD are appreciated.

As an aside, I don't really understand the loading / playing sections of the spec I linked at all. It seems to apply to 6502 systems / emulators only and not to my situation.

I know it's a long shot for anyone here to have enough experience in this area to help, but anything you can provide is definitely appreciated. A link to an existing .NET library that does this would be even better, but I don't believe one exists.

# Answer
> 1 votes
Are you trying to play arbitrary files or are you making a game and your source music is in a NSF file? If it's the latter (for example a lot of shipped emulated games do this) then it would probably be easiest to just save out the wave from your sound file using some other software (like winamp) and play that.

# Answer
> -1 votes
FMOD supports file type plugins. I got here because I was looking for one of those, actually. Find one for NSF and you'll be home free.

---
Tags: c#, audio, fmod
---


title: Transition Player Position

text:
# Question
Title: Transition Player Position
I'm currently working on a Java MMO with a pretty solid start, but I've come across an issue I need a little help with.

I'm working on player positions. Meaning their X/Y on the screen, if the PlayerA has a higher FPS (Frames Per Second) than other players, the resulting action will be that PlayerA will move faster than everyone else. I know the reasoning for this, it's because when the game draws I just use `x++`.

What would a better method be?

# Answer
> 5 votes
Basically, you need to repeat performing multiple different tasks at independent intervals. In pseudocode that will typically look something like this:

```
updateTime=1000/120
nextUpdate=time()
repeat{
    while(nextUpdate<time()){
        updatePlayerPositionPhysicsAndStuff()
        nextUpdate+=updateTime
    }
    render()
}

```

So `updatePlayerPositionPhysicsAndStuff` will run exactly 120 times per second, while `render` will take up all the leftover computing power running as often as there is time for.

# Answer
> 7 votes
Sounds like you might want to start using a delta time and a time-based movement speed. It could be a little difficult considering that it looks like you could be using a tile-based engine, but if you use a delta-time, your movement equation will look something like this:

```
x += unitsPerSecond * deltaTime;

```

Where x is a floating point variable (float or double), unitsPerSecond is how fast you want your characters to move per second, and deltaTime is in fractional seconds. Having your position as a floating-point value is **key**.

---
Tags: java, mmo, coordinates
---


# Question
Title: What does SetTextureStage(0, D3DTSS_COLORARG2, 0) in DirectX mean?
I'm trying to convert some DirectX code to Ogre3D and was wondering what the following translates to:

```
pDev->SetTextureStage(0, D3DTSS_TEXCOORDINDEX, 0)
pDev->SetTextureStage(0, D3DTSS_COLORARG1,     D3DTA_TEXTURE)
pDev->SetTextureStage(0, D3DTSS_COLOROP,       D3DTOP_MODULATE)
pDev->SetTextureStage(0, D3DTSS_COLORARG2,     0)

```

What is the modulation operation happening here? Is the texture getting modulated with the background? Or is it getting zeroed?

I've tried searching for what this means and unfortunately I haven't come across anything meaningful. Any help to shed light on this matter will be much appreciated.

# Answer
This is one of the D3DTA macros; checking in d3d9types.h reveals that D3DTA\_DIFFUSE is defined as 0x00000000 so that's the one.

It's obvious that the reason why is because you can bitwise-or these with various options, so the rendering backend is checking to see if the option to do so has been selected and is using a DWORD instead of the macro directly. E.g. it might look something like:

```
DWORD colorarg2option = D3DTA_DIFFUSE;
if (options.colorarg2 & something) colorarg2option |= D3DTA_COMPLEMENT;
if (options.colorarg2 & somethingelse) colorarg2option |= D3DTA_ALPHAREPLICATE;
pDev->SetTextureStage (0, D3DTSS_COLORARG2, colorarg2option);

```
> 2 votes

---
Tags: directx, textures
---


# Question
Title: In XNA 3.1, is it possible to disable texture filtering?
I want to disable texture filtering (since I'm making a retro-style game where it looks bad if a texture gets filtered like that), but since I'm on XNA 3.1 there seems to be no option to set a `SamplerState` with `SpriteBatch.Begin` or anything. Is it possible to do this?

# Answer
> 4 votes
The behaviour of `SpriteBatch` in XNA before 4.0 is rather ugly. Note that this answer only applies to XNA pre-4.0.

This is a list of render states that `SpriteBatch` controls (pre-4.0).

When `SpriteBatch` applies those settings depends on the `SpriteSortMode` parameter. The only reliable way to modify those settings is with `SpriteSortMode.Immediate`.

The way this works that, in immediate mode, `SpriteBatch` will set its render state when you call `Begin`. Immediately after calling `Begin` you can set your own render state, *before* you call `SpriteBatch.Draw`.

(States that `SpriteBatch` does not control can be set outside of the `Begin`/`End` block.)

The states you want to change (as r2d2rigo mentioned) are:

```
GraphicsDevice.SamplerStates[0].MagFilter = TextureFilter.Point;
GraphicsDevice.SamplerStates[0].MinFilter = TextureFilter.Point;
GraphicsDevice.SamplerStates[0].MipFilter = TextureFilter.Point;

```

# Answer
> 0 votes
Call

```
GraphicsDevice.SamplerStates[0].MagFilter = TextureFilter.Point;
GraphicsDevice.SamplerStates[0].MinFilter = TextureFilter.Point;
GraphicsDevice.SamplerStates[0].MipFilter = TextureFilter.Point;

```

before using `SpriteBatch.Begin`. And remember to restore the values after `SpriteBatch.End`.

# Answer
> -1 votes
This is very possible. You can use a custom shader with spritebatch. The source to the default spritebatch shader is available from the XNA 'education catalog'. What you will need to do is get this shader and change the texture filtering in the shader from linear to point filtering, and then use your new version of the shader with spritebatch. To use it with spritebatch, call spritebatch.Begin, but set the sprite sort mode to immediate (This effectively means no batching). Then, apply the correct technique on your new effect. Then draw your sprites. Spritebatch will draw them immediately with whatever effect is currently applied.

IIRC using a custom shader with spritebatch is far simpler in XNA 4.0.

---
Tags: xna, textures, filtering
---


title: OpenGL/GLSL: Render to cube map?

text:
# Question
Title: OpenGL/GLSL: Render to cube map?
I'm trying to figure out how to render my scene to a cube map. I've been stuck on this for a bit and figured I would ask you guys for some help. I'm new to OpenGL and this is the first time I'm using a FBO.

I currently have a working example of using a cubemap bmp file, and the samplerCube sample type in the fragment shader is attached to GL\_TEXTURE1. I'm not changing the shader code at all. I'm just changing the fact that I wont be calling the function that was loading the cubemap bmp file and trying to use the below code to render to a cubemap.

You can see below that I'm also attaching the texture again to GL\_TEXTURE1. This is so when I set the uniform:

```
glUniform1i(getUniLoc(myProg, "Cubemap"), 1);

```

it can access it in my fragment shader via `uniform samplerCube Cubemap`.

I'm calling the below function like so:

```
cubeMapTexture = renderToCubeMap(150, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE);

```

Now, I realize in the draw loop below that I'm not changing the view direction to look down the +x, -x, +y, -y, +z, -z axis. I really was just wanting to see something working first before implemented that. I figured I should at least see something on my object the way the code is now.

I'm not seeing anything, just straight black. I've made my background white still the object is black. I've removed lighting, and coloring to just sample the cubemap texture and still black.

I'm thinking the problem might be the format types when setting my texture which is GL\_RGB8, GL\_RGBA but I've also tried:

GL\_RGBA, GL\_RGBA GL\_RGB, GL\_RGB

I thought this would be standard since we are rendering to a texture attached to a framebuffer, but I've seen different examples that use different enum values.

I've also tried binding the cube map texture in every draw call that I'm wanting to use the cube map:

```
glBindTexture(GL_TEXTURE_CUBE_MAP, cubeMapTexture);

```

Also, I'm not creating a depth buffer for the FBO which I saw in most examples, because I'm only wanting the color buffer for my cube map. I actually added one to see if that was the problem and still got the same results. I could of fudged that up when I tried.

Any help that can point me in the right direction would be appreciated.

```
GLuint renderToCubeMap(int size, GLenum InternalFormat, GLenum Format, GLenum Type)
    {

    // color cube map
    GLuint textureObject;
    int face;
    GLenum status;

    //glEnable(GL_TEXTURE_2D);
    glActiveTexture(GL_TEXTURE1);
    glGenTextures(1, &textureObject);
    glBindTexture(GL_TEXTURE_CUBE_MAP, textureObject);
    glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

    for (face = 0; face < 6; face++) {
        glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, InternalFormat, size, size, 0, Format, Type, NULL);
    }

    // framebuffer object
    glGenFramebuffers(1, &fbo);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);

    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X, textureObject, 0);

    status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    printf("%d\"\n", status);
        printf("%d\n", GL_FRAMEBUFFER_COMPLETE);

    glViewport(0,0,size, size);

    for (face = 1; face < 6; face++) {

        drawSpheres();
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, textureObject, 0);

    }

     //Bind 0, which means render to back buffer, as a result, fb is unbound
       glBindFramebuffer(GL_FRAMEBUFFER, 0);

       return textureObject;
    }

```

# Answer
Well, I can't guarantee that this will help you figure out what's going on. You simply haven't posted enough information about what you're doing to track down any particular errors. Though I can correct one thing of yours really quick:

```
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X, textureObject, 0);

...

for (face = 1; face < 6; face++) {
    drawSpheres();
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, textureObject, 0);
}

```

This will only call `drawSpheres` *five* times. I'm guessing you wanted to call it 6 times.

But I can post a working answer. Note that this code is designed to be run alongside my tutorial series, so it makes reference to code that isn't present. But this is mainly things like creating meshes and so forth; nothing truly important.

Here are the salient points. The shaders for the main sphere object.

Vertex shader:

```
#version 330

layout(std140) uniform;

layout(location = 0) in vec4 position;
layout(location = 2) in vec3 normal;

out vec3 modelSpaceNormal;

uniform Projection
{
    mat4 cameraToClipMatrix;
};

uniform mat4 modelToCameraMatrix;

void main()
{
    gl_Position = cameraToClipMatrix * (modelToCameraMatrix * position);
    modelSpaceNormal = normal;
}

```

Fragment shader:

```
#version 330

in vec3 modelSpaceNormal;

uniform samplerCube cubeTexture;

out vec4 outputColor;

void main()
{
    outputColor = texture(cubeTexture, modelSpaceNormal);
//  outputColor = vec4(normalize(modelSpaceNormal), 1.0);
}

```

The creation of the cubemap texture that will be used as a render target:

```
void CreateCubeTexture()
{
    glGenTextures(1, &g_cubeTexture);
    glBindTexture(GL_TEXTURE_CUBE_MAP, g_cubeTexture);

    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, 0);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    std::vector<GLubyte> testData(CUBE_TEXTURE_SIZE * CUBE_TEXTURE_SIZE * 256, 128);
    std::vector<GLubyte> xData(CUBE_TEXTURE_SIZE * CUBE_TEXTURE_SIZE * 256, 255);

    for(int loop = 0; loop < 6; ++loop)
    {
        if(loop)
        {
            glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + loop, 0, GL_RGBA8,
                CUBE_TEXTURE_SIZE, CUBE_TEXTURE_SIZE, 0, GL_RGBA, GL_UNSIGNED_BYTE, &testData[0]);
        }
        else
        {
            glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + loop, 0, GL_RGBA8,
                CUBE_TEXTURE_SIZE, CUBE_TEXTURE_SIZE, 0, GL_RGBA, GL_UNSIGNED_BYTE, &xData[0]);
        }
    }

    glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
}

```

I actually fill the texture with data (rather than passing NULL to glTexImage2D) as a debugging aid. It ensures that everything was working prior to starting to use the texture as a render target.

Also, notice that I provide a BASE\_LEVEL and MAX\_LEVEL. I *always* do that with my textures immediately after creation. It's just a good habit, as OpenGL can be picky sometimes about texture completeness and the mipmap pyramid. Rather than remembering the rules, I just set them to the correct values religiously.

Here's the main drawing function:

```
void display()
{
    //Draw the cubemap.
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, g_framebuffer);
    glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, g_depthbuffer);

    for(int loop = 0; loop < 6; ++loop)
        DrawFace(loop);

    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);

    //Draw the main scene.
    //The projection matrix is in a uniform buffer.
    ProjectionBlock projData;
    projData.cameraToClipMatrix = glm::perspective(90.0f,
        (g_viewportSize.x / (float)g_viewportSize.y), g_fzNear, g_fzFar);

    glBindBuffer(GL_UNIFORM_BUFFER, g_projectionUniformBuffer);
    glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(ProjectionBlock), &projData);
    glBindBuffer(GL_UNIFORM_BUFFER, 0);

    glViewport(0, 0, (GLsizei)g_viewportSize.x, (GLsizei)g_viewportSize.y);

    glClearColor(0.75f, 0.75f, 1.0f, 1.0f);
    glClearDepth(1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glutil::MatrixStack modelMatrix;
    modelMatrix.ApplyMatrix(g_viewPole.CalcMatrix());

    if(g_pSphere)
    {
        glutil::PushStack push(modelMatrix);

        glUseProgram(g_progMain.theProgram);
        glUniformMatrix4fv(g_progMain.modelToCameraMatrixUnif, 1, GL_FALSE,
            glm::value_ptr(modelMatrix.Top()));

        glActiveTexture(GL_TEXTURE0 + g_cubeTexUnit);
        glBindTexture(GL_TEXTURE_CUBE_MAP, g_cubeTexture);

        g_pSphere->Render("lit");

        glBindTexture(GL_TEXTURE_CUBE_MAP, 0);

        glUseProgram(0);
    }

    glutPostRedisplay();
    glutSwapBuffers();
}

```

This makes reference to `DrawFace`, which draws the given face of the cubemap. That is implemented as follows:

```
void DrawFace(int iFace)
{
    glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
        GL_TEXTURE_CUBE_MAP_POSITIVE_X + iFace, g_cubeTexture, 0);

    GLenum status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER);
    if(status != GL_FRAMEBUFFER_COMPLETE)
        printf("Status error: %08x\n", status);

    //The projection matrix is in a uniform buffer.
    ProjectionBlock projData;
    projData.cameraToClipMatrix = glm::perspective(90.0f, 1.0f, g_fzNear, g_fzFar);

    glBindBuffer(GL_UNIFORM_BUFFER, g_projectionUniformBuffer);
    glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(ProjectionBlock), &projData);
    glBindBuffer(GL_UNIFORM_BUFFER, 0);

    glViewport(0, 0, (GLsizei)CUBE_TEXTURE_SIZE, (GLsizei)CUBE_TEXTURE_SIZE);

    const glm::vec4 &faceColor = g_faceColors[iFace];
    glClearColor(faceColor.x, faceColor.y, faceColor.z, faceColor.w);
    glClearDepth(1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    if(g_pSphere)
    {
        glutil::MatrixStack modelMatrix;
        modelMatrix.Translate(g_faceSphereLocs[iFace]);

        glUseProgram(g_progUnlit.theProgram);
        glUniformMatrix4fv(g_progUnlit.modelToCameraMatrixUnif, 1, GL_FALSE,
            glm::value_ptr(modelMatrix.Top()));

        const glm::vec4 &sphereColor = g_faceSphereColors[iFace];
        glUniform4fv(g_progUnlit.objectColorUnif, 1, glm::value_ptr(sphereColor));

        glActiveTexture(GL_TEXTURE0 + g_cubeTexUnit);
        glBindTexture(GL_TEXTURE_CUBE_MAP, g_cubeTexture);

        g_pSphere->Render("flat");

        glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
        glUseProgram(0);
    }
}

```

This function makes reference to a set of global tables that I use to give each face a distinct background color, a distinct sphere color, and to position the sphere (in camera-space) properly for that face.

The salient points for `DrawFace` are these.

As a general rule, unless I have *certain* knowledge that state is set, I set that state. I set the viewport each time I call `DrawFace`. I set the projection matrix each time. Those are superfluous; I could have set them back in `display` before the loop that calls `DrawFace`, just as I do with the current FBO and depth renderbuffer.

But I *also* clear the buffers, which is different for each face (since each face has a different color).
> 11 votes

---
Tags: opengl, glsl, cubemap
---


title: Audio Thread as daemon thread

text:
# Question
Title: Audio Thread as daemon thread
I'm looking to set up two threads in my puzzle game, one for logic/graphics, and one for audio. Am I correct in thinking that the thread that handles the audio should be set as a daemon thread, because the game can end without that thread finishing?

# Answer
Yes, but.

* If you exit using System.exit() then it will shut down your audio thread anyway.
* It's probably tidier to send a message to the audio thread telling it to shut down and close its streams.
* You should consider having three threads unless the logic is really simple.
> 2 votes

---
Tags: java, audio, multithreading
---


# Question
Title: How to make it so units don't stack up in one location?
> **Possible Duplicate:**
> Is there a simple way to stop enemies standing in the same spot?

So I'm making a game in AS3, it's a strategy DotA-like game (for flash game equivalent, there's UDE) so far so good, I have the A\* pathfinding algorithm all sorted out and the minion units move to the desired location as I want them to be. The problem a rise when a unit stops in a node that has already occupied by another friendly unit. Both (or more than two) of them stacks up in one location, it looks like they're one unit.

I want to add collision detection so when they collide they don't stack up together. But now they stop when they collide on they way to a node. This isn't good because they won't move at all midway (they won't respond to enemy attacks like that). I've added a deltatime so they only stopped for 2 seconds before they move again to their designated designation. This moves them again but they flicker. Not how I want it.

So, like the title said. How to make more than one units don't stack up in a node? And if possible, how to make them not flicker while moving (it's good if they can tell other friendly units on the way and avoid them accordingly)?

# Answer
Not 100% on the best way to avoid your problem, but the first thought that comes to mind is maybe have a "feeler" radius around each unit. This feeler circle would detect if any other unit (friendly or not) is within the circle and act appropriately. I.E. stop if the unit is a friendly unit, and maybe walk around to the side of it so they line up uniformly, or attack if the unit is un-friendly.

As I said, just the first thought that came to mind.

Good luck. Cheers.
> 0 votes

# Answer
If you're using A\* path-finding (or something else which is pretty quick), and you're detecting the paths multiple times (not just once on startup/creation of your map), simply mark any locations which have units in them as non-walkable and let the path-finder work around them.

This will require pretty much constant recalculation of your paths, so make sure your performance doesn't sink if you decide to do it this way.
> 0 votes

---
Tags: collision-detection, actionscript-3, collision-avoidance
---


title: Spin/Rotational Blur

text:
# Question
Title: Spin/Rotational Blur
How do I perform a circular/rotational/spin blur on an image - using DirectX9.0 and HLSL?

For example:

# Answer
You will need to work in Polar Coordinates. In order to convert Cartesian Coordinates into Polar you use the following:

```
r = sqrt(x * x + y * y);
theta = atan2(y, x);

```

This will get the coordinates around `{0, 0}` \- so we need to change the Cartesian origin before converting:

```
float mx = x - 0.5;
float my = y - 0.5;
float r = sqrt(mx * mx + my * my);
float theta = atan2(y, x);

```

Once you have the polar coordinates you can use a typical multi-tap blur to perform the blur.

```
const int SAMPLES = 15;
extern float PARAM_RadialBlurLength = 0.01f; // In radians

float2 offsetCoord = inputTexCoord - float2(0.5, 0.5);
float r = length(offsetCoord);
float theta = atan2(offsetCoord.y, offsetCoord.x);

float4 sum = (float4)0;
float2 tapCoords = (float2)0;
for(float i = 0; i < SAMPLES; i++)
{
  float tapTheta = theta + i * (PARAM_radialBlurLength / SAMPLES);
  float tapR = r; // If you alter this according to 'i' you will get a swirl.

  // Remember we need to invert the origin offset we
  // used to create the co-ordinates, the the + 0.5 on each.
  tapCoords.x = tapR * cos(tapTheta) + 0.5;
  tapCoords.y = tapR * sin(tapTheta) + 0.5;

  sum += tex2D(inputSampler, tapCoords);
}
sum /= SAMPLES;
return sum;

```
> 3 votes

# Answer
A blur just uses temporal coherence. It doesn't really matter what technology you're using to implement it, so long as you know how to do alpha, you're all good to go.

```
loop
{
lastRotation = currentRotation
++currentRotation;

draw image texture at lastRotation with some degree of alpha (eg. 50%, this is the blur)
draw image texture at currentRotation with full alpha (the actual image that is spinning)
}

```

Of course, you needn't just have one `lastRotation`, you can have an array of them, such that you can have an extensive blur behind your actual spinning image. Each one will reflect the rotation as it was further back in time.

HTH.
> 4 votes

---
Tags: hlsl, graphic-effects
---


# Question
Title: Is using a half-edge mesh structure feasible?
Is it feasible to use half-edge mesh, in games, instead of vertex-face structure? What comes to my mind is that it could be useful in mesh simplification (dynamic level of detail). However, I'm worried it could take too much memory, or even have a negative impact on a games rendering performance.

# Answer
I just read about the half-edge mesh structure; this page was helpful. Thanks for showing it to me!

If your main game mechanic involves lots of dynamic level of detail calculations on meshes, then it would be a great choice. Also if you were developing a mesh editor, you might consider using it if the user would often perform operations which the structure is better at. Otherwise, it doesn't seem like an advantage for game purposes. Personally, I would rather precalculate level of detail meshes and then use the conventional mesh format.

Furthermore, the restriction that it can only represent manifold surfaces sounds like a deal-breaker to me. I imagine very few game models are actually capable of being represented this way.

I think with any alternate data structure, you should consider the cons along with the pros. This data structure looks neat, it certainly has its pros, but it doesn't seem a better fit for games than the current widely used format of vertices and faces (whatever its name may be).
> 4 votes

---
Tags: rendering, data-structure
---


# Question
Title: Can you recommend a game server for a facebook board game?
I am seeking a game server that will scale well. All commercial and/or free software alternatives are welcome. Game will be a boardgame that is similar to poker. Some technical details are listed below.

* There will be a table which consists of 4 people, to send them message I need a channel manager. A table will be ready to play for at least 5 minutes. There should be a reliable channel manager.
* People will wait for some time(i.e.) and if they are not playing they will be kicked by server, so there will be a reliable timed task queue to execute some tasks.
* It should be quick enough to response and show the changes to all 4 people on that table simultaneously.To achive this server should have a powerfull I/O library.
* I think to use inmemory to have quick response times, but it comes with scalability problems.
* And some variables should be thread safe so a variable should be thread safe between multiple nodes.
* Flash(AS3) and Unity (.Net 2.0 C# mono) client API's should be available for socket connection.

PS: I am using Reddwarf server, it lacks of documentation and multiple node.

# Answer
What kind of game? Assuming you mean an MMORPG, there are no MMORPGs with millions of simultaneous users. There are a few MMORPGs with millions of users, but each logical server only supports a couple of thousand players. EVE Online is an exception in running everything in one logical server, but that has only supported about 60,000 players.

If you mean a game like Farmville, then that is done with multiple servers, but you wouldn't use technology like RedDwarf, but web technology instead, with a lot of distributed caching.

There are lots of MMO middleware companies, but hardly any of them are selling technology that has actually been used in active games, so their concurrency claims are not always useful.

You need to do some research into what is currently feasible and in use, and then be more precise with your requirements.
> 1 votes

# Answer
You want a server that supports millions of players? That doesn't really sound possible, even if an MMO has a million+ users, there are probably only a few thousand online at the same time - and even that requires a whole building for the servers. Basically, that kind of power is only achievable to big corporations like Blizzard, and if you plan to compete with them you better hire some technicians to handle stuff like this. Could you please edit your question?

Final answer: no, there are no games with millions of online users, and no you certainly can't get a server that would support it.
> 0 votes

---
Tags: server
---


# Question
Title: Why are my scene's depth values not being written to my DepthStencilView?
I'm rendering to a depth map in order to use it as a shader resource view, but when I sample the depth map in my shader, the red component has a value of 1 while all other channels have a value of 0.

The Texture2D I use to create the DepthStencilView is bound with the D3D11\_BIND\_DEPTH\_STENCIL | D3D11\_BIND\_SHADER\_RESOURCE flags, the DepthStencilView has the DXGI\_FORMAT\_D32\_FLOAT format, and the ShaderResourceView's format is D3D11\_SRV\_DIMENSION\_TEXTURE2D.

I'm setting the depth map render target, then i'm drawing my scene, and once that is done, I'm the back buffer render target and depth stencil are set on the output merger, and I'm using the depth map shader resource view as a texture in my shader, but the depth value in the red channel is constantly 1. I'm not getting any runtime errors from D3D, and no compile time warning or anything.

I'm not sure what I'm missing here at all. I have the impression the depth value is always being set to 1.

I have not set any depth/stencil states, and AFAICT depth writing is enabled by default. The geometry is being rendered correctly so I'm pretty sure depth writing is enabled.

The device is created with the appropriate debug flags;

```
#if defined(DEBUG) || defined(_DEBUG)
    deviceFlags |= D3D11_CREATE_DEVICE_DEBUG | D3D11_RLDO_DETAIL;
#endif

```

This is how I create my depth map. I've omitted error checking for the sake of brevity

```
D3D11_TEXTURE2D_DESC td;

td.Width     = width;
td.Height    = height;
td.MipLevels = 1;
td.ArraySize = 1;
td.Format    = DXGI_FORMAT_R32_TYPELESS;
td.SampleDesc.Count   = 1;
td.SampleDesc.Quality = 0;
td.Usage          = D3D11_USAGE_DEFAULT;
td.BindFlags      = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
td.CPUAccessFlags = 0;
td.MiscFlags      = 0;
_device->CreateTexture2D(&texDesc, 0, &this->_depthMap);

D3D11_DEPTH_STENCIL_VIEW_DESC dsvd;
ZeroMemory(&dsvd, sizeof(dsvd));
dsvd.Format = DXGI_FORMAT_D32_FLOAT;
dsvd.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
dsvd.Texture2D.MipSlice = 0;
_device->CreateDepthStencilView(this->_depthMap, &dsvd, &this->_dmapDSV);

D3D11_SHADER_RESOURCE_VIEW_DESC srvd;
srvd.Format = DXGI_FORMAT_R32_FLOAT;
srvd.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvd.Texture2D.MipLevels = texDesc.MipLevels;
srvd.Texture2D.MostDetailedMip = 0;
_device->CreateShaderResourceView(this->_depthMap, &srvd, &this->_dmapSRV);

```

# Answer
> 2 votes
Depth-writing being enabled is definitely the first thing to check. If I had $5 for every time I thought something was definitely enabled by default...

So try explicitly enabling it just to be absolutely certain. Also double-check your depth range and ensure that it's not something like minz 1 and maxz 1 (which would give the same result even with depth writing enabled).

---
Tags: c++, directx11, depth-buffer
---


title: Circular Bullet Spread Is Not Even

text:
# Question
Title: Circular Bullet Spread Is Not Even
I'm creating a bullet shooter much in the style of Touhou. Right now I want to have a very simple circular shot being fired from the enemy.

However, the spacing is very uneven, which isn't very good if you want to survive.

The code I'm using is this:

```
private function shoot() : void
{
    const BULLETS_PER_WAVE : int = 72;
    var interval : Number = BULLETS_PER_WAVE / 360;

    for (var i : int = 0; i < BULLETS_PER_WAVE; ++i)
    {
        var xSpeed : Number = GameConstants.BULLET_NORMAL_SPEED_X * Math.sin(i * interval);
        var ySpeed : Number = GameConstants.BULLET_NORMAL_SPEED_Y * Math.cos(i * interval);

        BulletFactory.createNormalBullet(bulletColor_, alice_.center, xSpeed, ySpeed);
    }

    canShoot_ = false;
    cooldownTimer_.start();
}

```

I imagine my mistake is in the `sin` & `cos` functions, but I'm not entirely sure what's wrong.

# Answer
Golden rule when working with any kind of angle: Make sure you are using the correct unit. In this case, you should be using radians, not degrees.

```
Math.sin(i * interval * Math.PI / 180);
Math.cos(i * interval * Math.PI / 180);

```

If you want to fire bullets directly between boss and player, use `atan2`, FYI.
> 13 votes

# Answer
You are doing the division the wrong way round, and you are using degrees rather than radians, like the maths functions do. By chance this results in a pattern that look a bit like the desired. Just fix your calculation of the interval variable.

```
var interval : Number = 2 * Math.PI / BULLETS_PER_WAVE;

```

Edit: For those not familiar with the concept this code produce the desired angle between bullets in radians, thus enabling leaving the calculation of `xSpeed` and `ySpeed` as it is with no further constants applied.
> 7 votes

# Answer
I think you should do 360 / BULLETS\_PER\_WAVE instead which gives in your case 360 / 72 = 5 degrees between each bullet. Also are you sure that the Math.sin and Math.cos functions wants their input in degrees and not radians?
> 5 votes

# Answer
While you have been answered, here is a funnier answer : learn from nature.

Use the golden ratio instead.

```
const GOLDEN_RATIO : Number = 1.618033989;
var interval : Number = 2 * Math.PI * GOLDEN_RATIO;

```

See : http://www.mathsisfun.com/numbers/nature-golden-ratio-fibonacci.html
> 4 votes

# Answer
Apart from possible degree/radian issue, I reckon the main problem is that you're using integer values for the calculations. You haven't shown `GameConstants.BULLET_NORMAL_SPEED_X` or its Y counterpart but make sure they are represented as floating point numbers, not integers. Alternatively, cast them into floating point values during the multiplication for the speed calculation.
> 3 votes

---
Tags: mathematics, actionscript
---


# Question
Title: How can I downsample a texture using FBOs?
I am rendering a scene to FBO as my render target whose size is 8 times the size of the orignal screen in OpenGL. Now i wan to downsample the texture generated by FBO to the size of the screen so as to achieve spatial anti aliasing. How do i achieve the down sampling ? Please provide implementation details.
**Note : If there is a better way of doing anti aliasing in FBOs please mention that too. I am trying to remove the aliasing in the image attached below.**

# Answer
Since your render target is exactly 8 times the size of the screen, I'd just use `glGenerateMipmap`, after setting `glTexParameteri(..., GL_TEXTURE_MAX_LEVEL, 3);`. Then, just blit or whatever from mipmap level 3, and you're done.

But really, you're wasting a *lot* of performance by not using multisampling+aniso. Supersampling won't give you much that you won't get with multisampling and anisotropic filtering, and your rendering will be that much faster for it.
> 2 votes

---
Tags: opengl, textures
---


# Question
Title: Best solution for multiplayer realtime Android game
I plan to make multiplayer realtime game for Android (2-8 players), and I consider, which solution for multiplayer organization is the best:

1. Make server on PC, and client on mobile, all communition go through server ( ClientA -\> PC SERVER -\> All Clients )
2. Use bluetooth, I don't used yet, and I don't know is it hard to make multiplayer on bluetooth
3. Make server on one of devices, and other devices connect ( through network, but I don't know is it hard to resolve problem with devices over NAT ? )
4. Other solution ?

# Answer
Disclaimer; I haven't done *much* with java and the android platform.

However my more extensive experience with the '.net' languages on the windows mobile platforms, along with the windows platform, is that a good 75-90% of all the code required to create and maintain a Bluetooth or network data connection are maintained/supported with the OS or the libraries that would be need to access the hardware.

So far this also seems true with Android, with the OS exposing methods for creating data connections over Bluetooth or the internet, along with enabling/disabling the respective hardware.

I would imagine that Bluetooth would be the preferred method of connection, as this would be the least expensive to implement (No servers). And allow for a more local gathering/game. Bluetooth is fairly easy as to use. it functions similar to normal network sockets once you know which device you want to connect to.

The others are are correct in that Bluetooth v2.0/v2.1 is not currently capable of support large data loads. This will change with the eventual spread of v3.0 and higher. and there are ways of getting around this limitation.

For now though there is a simple concept, yet complex solution, which you may wish to try. I have been using it for awhile, It is similar to peer to peer, but it involves having the game hosted on all the devices simultaneously. That way if a connection is temporarily lost, slowed, or a player is dropped for any reason, other players will not be affected. This allows users that have been dropped to rejoin the ongoing game with little or no disruption to other players or their own game.

**CON:** Each player would actually be playing their own somewhat unique instance of the game, that would be linked with the other players to keep the games from straying too far out of sync with each other.

**CON:** The supporting code *can be* extensive/complex and difficult to wrap your head around depending on what you want to achieve.

**PRO:** No central server or device required! No $$$ upkeep required.

**PRO:** A heavy exchange of data would only occur when a player (re)joined, or a game was initialized. - Even this can be reduced by ensuring that all the games are going to be generated, and progress the same way by all the players. **POTENTIALLY** reducing energy consumption that occurs due to heavy network usage.

**PRO:** Data becomes less time sensitive, as the devices would already have all the data they require to keep a game going without the other players. Allowing *you* to focus more on the actual game experience for the individual users, rather than a group of players.

I have lacked the time to implement a full in-depth game engine that utilizes this. The games I've made have been limited to recreating games similar to Monopoly, and Uno, which seemed to function extremely well.

The easiest was the one that emulated Uno. I essentially stacked the decks of the losers after a player won as to ensure that player won all the games. 95%+ of the time I couldn’t tell that I wasn’t playing the exact same game as everyone else.

I started building a game similar to Master of Orion II, but the game itself was a little much for me to undertake by myself.
> 2 votes

# Answer
It heavily depends on the game, but some friends and I were thinking about the same issues only a couple months ago, and here's what we determined. I'm in a pros and cons mood again.

## Computer Based Server

**Pros**

* Tried and true
* Scaleable

**Cons**

* Need to write a "multi-server" that can host multiple games at the same time. This will likely use slightly different technology than your android phone. You can still use java, but can you still use the android packages?
* Can be expensive to run, and maintain
* You could potentially pull it down one day for a verity of reasons. Fans may not be happy if the server goes down only a couple months after purchasing the game.

## Peer To Peer with one of them in control

**Pros**

* Ad-hoc servers where friends can join other friends when they want to
* Little to no running cost on your part
* The server code will be mixed in with the client code, no need to write a separate server application.

**Cons**

* Need to write a simple centralized peer-finder. (I did mine in php+mysql in a couple hundred easy lines)
* The servers are running on phones. Phones can be slow. Will all target phones be able to host a game?
* What happens if the server phone gets disconnected?
* Easier than client-server for hackers to get in

---

As for bluetooth, I would expect that to be similar to the peer to peer method above. I also don't think you should have any issues with NAT.

*EDIT*: It also heavily depends on your experience. I'd start with writing some relatively small client/server games to get the hang of networking first. It's a tough topic that is easy to get wrong the first time. I got mine right on the third try. Follow known patterns, and don't try to make something up yourself.
> 9 votes

# Answer
One of the biggest considerations you need to make is reliability. Phones are not very reliable; in fact, you should probably assume that in a 8 player game someone is likely to disconnect (incoming call, bad reception, player quits...)

With this in mind, understand that you should minimize the impact of a disconnected user. In your second option, you've essentially made a phone the server. If that phone goes MIA, the game is effectively over for all players.

John covered the pros and cons of a traditional client \<-\> server architecture. This is probably the most resilient way to provide a reliable multiplayer experience for everyone.

You could also consider a technique along the lines of a lock-step-simulation. This can be implemented in a purely peer-to-peer manner. The general idea is that every client is expected to send it's update (series of commands, or lack thereof) every simulation step. In a subsequent simulation step, the commands of each player are applied to the game logic. Many RTS games employ this kind of networking scheme.

The technique can be difficult to implement and can be very difficult to debug. It is certainly more difficult than having a more traditional client-server architecture. It also implies a lag between a player's input and when the game responds to the input. However, if one player were to drop off, the remaining players could just exclude him from the game and continue. It can also potentially decrease network traffic compared to other schemes.

If you want to learn more about this technique, start with this excellent article on the subject. Otherwise, I would strongly discourage a network scheme where a single phone is responsible for a multiplayer session, and suggest the simpler client \<-\> server architecture.
> 4 votes

---
Tags: architecture, android, networking, multiplayer, mobile
---


title: Learning to optimize with Assembly

text:
# Question
Title: Learning to optimize with Assembly
I am a second year student of Computer Games Technology. I recently finished my first prototype of my "kind" of own pathfinder (that doesn't use A\* instead a geometrical approach/pattern recognition, the pathfinder just needs the knowledge about the terrain that is in his view to make decisions, because I wanted an AI that could actually explore, if the terrain is already known, then it will walk the shortest way easily, because the pathfinder has a memory of nodes).

Anyway my question is more general: How do I start optimizing algorithms/loops/for\_each/etc. using Assembly, although general tips are welcome. I am specifically looking for good books, because it is really hard to find good books on this topic. There are some small articles out there like this one, but still isn't enough knowledge to optimize an algorithm/game...

I hope there is a modern good book out there, that I just couldn't find...

# Answer
I'll be the one going against the grain here and say, it is never too early to *learn* about optimizations, especially assembly optimizations and more importantly, debugging in assembly. I believe that you will gain the maximum benefit of it if you are a student (because then you have very little to lose \[i.e. time/money wise\]) and everything to gain.

If you are in the industry and not tasked with tinkering around in assembly, then don't. Otherwise, if you are a student or have time in general, I would find the time to learn to disassemble programs and see if I can come up with a better solution than the compiler. If I can't, who cares! I just learned how to write as well as compiler and that is a HUGE plus when you are faced with a bug in release code (with no debug symbols) and staring at the disassembly because that's the only thing you can look at.

**The answer**

This is one of the best resource I have found for learning about optimizations.

http://www.agner.org/optimize/

**The rant**

If you read some articles by major developers (for example, reasoning behind the making of EASTL and closer inspection of the code will lead you to comments like **did this because GCC is terrible at inlining this if statement** which will tell you, what the majority of people tell you **trust the compiler** is not always right, ESPECIALLY in game development) and then set foot in the industry you will find that optimizations are an everyday thing and knowing what the assembly output means is a big plus. Also, people don't seem to realize (especially on stackoverflow) that profiling games is very hard and not always accurate.

There is a caveat though. You can spend time optimizing something and later on realize that was time wasted. But what did you learn? You learned not to repeat that same mistake in a similar circumstance.

What SO is now taking is in my opinion a religious stance to the statement **don't optimize until you profile** and **don't worry, the compiler knows better than you**. It hinders learning. I know experts in the industry who are paid very good money (and I mean VERY good money) to fiddle around in assembly to optimize the game and debug it because the compiler is bad at it or simply cannot help you, because, well, it cannot (GPU related crashes, crashes where data involved is impossible to read in a debugger etc. etc.)!

What if someone who loves doing that, hasn't fully realized it yet, asks the question here and is turned away/off by the many answers **compiler knows better than you!** and never becomes one of those highly paid programmers?

One final thought. If you start doing this early, you will find that soon you will start writing code that is at worst, has no performance improvements whatsoever because the compiler optimized it the same way or at best, has some performance improvements because now the compiler can optimize it. In either case, it has become habit, and you are no slower at writing code this way than what you did before. A couple of examples are (there are many more):

1. Pre-incrementing unless you really want post-increment
2. Writing loops for containers using a constant local size variable rather than calling size() on the container within the loop.

**EDIT:** Update after 8 more years in the industry. Learn assembly. Learn how optimizers work and the assembly they generate (CompilerExplorer is a great tool for that). I have run across countless crashes in Test builds (optimized builds for internal testing) where you cannot rely on the debugger even with debug symbols. The compiler has optimized out too many things and the assembly is your only source of valuable information to find the bug from the crash dump. Each build takes 30-40min if you're lucky and first in the build queue - so you cannot rely on some traditional techniques to isolate the bug. Multiplayer makes things worse. Knowing assembly and how to read optimized assembly will simply make you better and ultimately more valuable to the team.
> 21 votes

# Answer
The first tip you'll get is this - don't.

Modern compilers are actually really really good at optimizing code, and will be much more likely to do a better job of it than any self-rolled assembly language you may write.

The exception would be any specific case where you have determined for certain that the compiler is doing a bad job of optimizing, so that's the second tip. There are no general guidelines here, you need to know your own code, know what it's doing, be able to jump into a disassembly of it, and be able to determine for absolute certain that the compiler is doing a bad job.

Even in this case you still may not want to. You need to be certain that there is not going to be any ongoing maintenance overhead for you. You may wish to come back to this code in 6 months time and modify part of it, or you may find an extremely subtle bug that's going to be more difficult to fix in an assembly language version. Even if you think you've worked all the bugs out, once your program goes to the public bugs you never even thought could happen will become a reality for you. That's quite an eye-opener (and a humbling experience).

And even if you're happy to accept that, you may still find that there is absolutely no measurable performance improvement as your main bottleneck could be somewhere completely different in your program. So that brings me back to number 1 again. Don't.
> 22 votes

# Answer
Usually, solid optimisation doesn't depend on using Assembly, or doing micro-optimisations with code in higher level languages. If you read a lot of research papers (as I do -- or try to!), you'll see that oftentimes the improvements made to algorithms are at a broader conceptual, "qualitative" level, rather than at the more "quantitative" level of micro-optimisation. I would stress that order-of-magnitude gains are more likely to be found by looking at algorithms from this point of view, or from vectorising/parallelising existing solutions.

Having said that, I recently happened upon this, which may be a good route towards learning x86 ASM specifically for game developers.

---

**ADDENDUM**

Two sources off the top of my head:

Additionally, reading research papers is an excellent way to follow the thought processes of the wise as they optimise algorithms for better performance. Most often, gains are seen by:

* Reducing the use of the most costly operations (div, SQRT, trig ops, and conditionals, primarily);
* Improving cache performance through use of more efficient data structures, memory alignment, and reduced conditionals;
* Reducing quality of output in acceptable areas for improved performance;
* Vectorisation (SIMD);
* Parallelisation (threading, includes shifting tasks off to the GPU);
* And of course (increasingly rarely) hand-coded assembly. First inspecting C/C++ assemblies to see where the compiler is making non-optimal choices, of course. You will find more of this in older papers from the 80's and 90's, IME.

Reading research also keeps you at the cutting edge of your field, instead of waiting for that knowledge to filter down into the industry.
> 15 votes

# Answer
I think it might be too early.

Anyway, it is important to understand that the compiler itself does not produce slower code than the assembly equivalent, you don't get any performance simply from writing the same assembly code as the compiler would.

For a start at least concentrate on assembly-free optimizations. Igor Ostrovsky have a few good articles that demonstrate some of the basics: http://igoro.com/archive/fast-and-slow-if-statements-branch-prediction-in-modern-processors/

Do note that branch mispredictions and cache misses are what you should primarily optimize against, even if you have to pay by doing some extra arithmetic operations it is usually worth it to avoid an unpredictable branch or reading randomly from too much memory.

And of course, most importantly, optimize your algorithm first. A slow implementation of a fast algorithm will almost always be faster than a fast implementation of a slow algorithm.
> 3 votes

# Answer
This book is exceptionally good for a text book. But its not specifically geared towards optimization. Assembly Language for x86 Processors, 6th edition

It's more about teaching the fundamentals of assembly, using MASM. Then towards the end of the book it gets into how to inline assembly with c++ and integrate it into bigger programs.

I put this up here because it makes sense to learn the fundamentals of assembly before you learn how to optimize programs with it.

I like this book because Irvine teaches you how to use the tools needed to write masm programs. He specifically goes into how to use the IDE (Visual Studio C++) and the debugger. Each chapter has a few videos dedicated towards solving problems. Some of this information is available freely on the website listed.
> 2 votes

---
Tags: c++, optimization, books
---


# Question
Title: Is it possible to do freelancing with 3dsmax?
I am learning 3dsmax architecture for building models of houses. Is it possible to do freelancing with house modelling thing? For various reasons I have to stay at home.

So I was wondering if I can earn some money by making some house models for someone.

I really don't know how this works but may be someone can give some ideas.

Would I need to go to construction or real estate companies and ask them if they want something like this?

# Answer
There are basically two paths you can go down.

1) Prepare models beforehand and try to sell them. A pretty popular website with a lot of art on it is TurboSquid. http://support.turbosquid.com/entries/174743-publishing-products This lets you work on what you know and at your own pace.

2) Join an art collective that does outsourcing and do work for hire. I know some people who did this from home, but I can't think of the name of the company they went through. This is generally more demanding and you'd be expected to do revisions and so forth. You'd be either paid on a per-piece or by schedule.

As I'm not an artist I can't really comment any further, but those are your basic options.
> 4 votes

---
Tags: 3dsmax
---


# Question
Title: How do I get AI Agents to move along a curve?
Currently my very basic AI framework has agents that move along a a jagged path made up of a series of points.

They do this by simply moving their position from one point to the next. When they reach the next point they move towards the next and so on. How can I change this so that they move smoothly along a curved version of the path, and how do I generate the curve?

# Answer
> 4 votes
You're after some sort of path smoothing. Of course, as bummzack pointed out you also want to make sure that any path smoothing that you perform results in legal movements for your agents.

This article from Gamasutra explains pretty much everything you need to know, including path smoothing, legal turns and realistic, smooth turning algorithms.

Another alternative, which is slightly simpler, is to use a Seek behaviour with a small bounding circle/sphere to check whether the agent is at or close to the next point in the path.

# Answer
> 7 votes
Since you already know your control points, you just need to update your interpolation code to use an algorithm for curvature (Hermite or Cosine, for example).

These sites offer a great explanation and sample code that should get you started:

Paul Bourke Interpolation Methods

Sol::Tutorials - Interpolation Tricks

# Answer
> 0 votes
I'm going to go against the grain here and suggest that, instead of pre-generating your curves, just handle it on a frame-by-frame basis, using (for example) the same logic you'd use to create a homing-missile.

This will be much easier, and probably more realistic because you don't need special-cases for when there are walls between two points - you just handle collision detection as usual.

The downside is the movement will look sub-optimal. The object will always take the most direct path from one waypoint to the next, meaning, unlike with a spline, he won't start turning *towards* waypoint 3 until he has already passed waypoint 2. Depending on your situation, this may or may not be fixable by adjusting your waypoints (if it's even a problem).

# Answer
> 0 votes
The path finder should give you the path and you should not modify that. I belive that it is possible to modify your path finder algorithm to take into account that path with sharp turns are wrose than those with smooth curves as it already does with long path vs short ones.

I will post here some solution if I can find a moment to think about it deeply, but i think this is the way to go.

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


# Question
Title: How can I support scrolling when using batched rendering for my tiles?
I have tiled map 100\*75 and tiles are 32\*32 pixel.I want to use batching for performance .I don't figure it out , because of my game needs scrolling and every frame i draw 22\*16 tiles (my screen is 20\*16 tile) .I thought that batching tiles for every frame .Is it good or any suggestion?

edit :to more clarify I want to use occlusion culling and batching at the same time.I thought that drawing only visible areas and batching them together .But there is a something i couldn't figure out .When scrolling screen with translate matrix , if one row become invisible , I bind new row and batch them again.Every batched objects needs to buffer again.So I batch tiles and buffer to VBO every time when one row become invisible .I don't know these way is efficient or not .This is my question .And i am open to any suggestions.

# Answer
> 2 votes
> to more clarify I want to use occlusion culling and batching at the same time.

Occlusion culling? You are drawing *tiles*, not 3D polygonal meshes. They're axis-aligned. It takes very simple math to know exactly which tiles are on-screen.

Plus, even for Android hardware, drawing a few things off-screen will do nothing to your performance. As long as you're using proper texture atlasing (no texture changes between tiles), you could probably just draw the entire 100x75 map every frame with no problems.

Batching means bundling stuff into a single draw call. And batching is at its most efficient when the batches are *static*: they don't change from frame to frame. If you have to rebuild your index list or add new vertices, you're batching wrong.

You didn't say what screen size you're rendering to, so I'll assume it's around 1024x768. If, **and only if**, you profile your application and detect that simply drawing the 100x75 map is too slow, you can break the map up into 32x32 segments. If one of these segments is on the screen, you draw it. Even if it's just one tile. That's the best way to avoid non-static batching.

Again, only bother to do this if you actually have a performance deficiency. As in, you ran it on the hardware of choice and it wasn't performing the way you wanted it to.

# Answer
> 1 votes
In my experience this is best solved by simply transforming the co-ordinates that you are about to draw by a scrolling amount (deviation from the starting point).

You mentioned in a reply to another answer that you are using OpenGl. You can use glTranslate to move objects in your scene.

```
glTranslate(x, y, z)

```

http://www.opengl.org/sdk/docs/man/xhtml/glTranslate.xml

I imagine you're drawing your tiles in a loop over a 2D array. So the code might look something like this:

```
glPushMatrix();
glTranslate(scrollX, scrollY, 0);

for (int i=0; i < array.size(); i++)
    for (int j=0; i <array[i].size(); j++)
        array[i][j].Draw();

glPopMatrix()

```

You can calculate the scroll value using the player/cursor position from the edges of the viewport. Note that this draws tiles that are off screen and might have a performance impact. You can perform culling by calculating the tile values that are visible and use those as bounds in your loop.

```
for (int i = leftValue; i <= rightValue; i++)

```

See this page on MSDN for some further information. It is the technique I described but for C# and XNA.

# Answer
> 0 votes
What tools are you using, what platforms do you intend to release for? Most probably it doesn't really matter how you do the drawing, unless you use some really obscure technique a modern computer should be plenty fast.

Try out your options, flicking together a benchmark to find out how fast the different options are shouldn't be too hard.

# Answer
> 0 votes
There are several solutions to this:

1. simplest solution: put all tiles into **one** big image. All drawing calls will reference this image and draw different parts of it. This can be executed in one batch. The image might get too big for the phone to handle or contain tiles which are only used in one level and waste memory.
2. defer the drawing to a renderer class: the renderer will sort all sprites by drawOrder then image. This will batch all draw calls using the same source image per drawing layer. Your scrolling algorithm just marks which sprites are visible.
3. Combine 1. and 2.: put tiles of the same drawing layer into one image file and then let the renderer draw per layer.

---
Tags: android, graphics-programming, parallax-scrolling, opengl-es2
---


# Question
Title: Finding direction of travel in a world with wrapped edges
I need to find the shortest distance direction from one point in my 2D world to another point where the edges are wrapped (like asteroids etc). I know how to find the shortest distance but am struggling to find which direction it's in.

The shortest distance is given by:

```
int rows = MapY;
int cols = MapX;

int d1 = abs(S.Y - T.Y);
int d2 = abs(S.X - T.X);
int dr = min(d1, rows-d1);
int dc = min(d2, cols-d2);

double dist = sqrt((double)(dr*dr + dc*dc));

```

Example of the world

```
                   :
                   :  T
                   :
    :--------------:---------
    :              :
    :           S  :
    :              :
    :              :
    :  T           :
    :              :
    :--------------:

```

In the diagram the edges are shown with : and -. I've shown a wrapped repeat of the world at the top right too. I want to find the direction in degrees from S to T. So the shortest distance is to the top right repeat of T. but how do I calculate the direction in degreed from S to the repeated T in the top right?

I know the positions of both S and T but I suppose I need to find the position of the repeated T however there more than 1.

The worlds coordinates system starts at 0,0 at the top left and 0 degrees for the direction could start at West.

It seems like this shouldn’t be too hard but I haven’t been able to work out a solution. I hope somone can help? Any websites would be appreciated.

# Answer
You'll have to tweak your algorithm a bit to calculate the angle - currently you only record the absolute difference in position, but you need the relative difference (i.e. can be positive or negative depending on positioning).

```
int dx = T.X - S.X; // difference in position
int dy = T.Y - S.Y;

if (dx > MapX / 2) // if distance is bigger than half map width, then looping must be closer
    dx = (dx - MapX) * -1; // reduce distance by map width, reverse
else if (dx < -MapX / 2) // handle the case that dx is negative
    dx = (dx + MapX) * -1;

//Do the same for dy
if (dy > MapY / 2)
    dy = (dy - MapY) * -1;
else if (dy < -MapY / 2)
    dy = (dy + MapY) * -1;

double dist = sqrt(dy*dy+dx*dx); // same as before
double angle = atan2(dy,dx) * 180 / PI; // provides angle in degrees

```
> 8 votes

# Answer
In such a world there are **infinite** number of paths from S to T. Let's denote the coordinates of T by `(Tx, Ty)`, the coordinates of S by `(Sx, Sy)`, and the size of the world by `(Wx, Wy)`. The wrapped coordinates of T are `(Tx + i * Wx, Ty + j * Wy)`, where `i` and `j` are integers, that is, elements of the set `{..., -2, -1, 0, 1, 2, ...}`. The vectors connecting S to T are `(Dx, Dy) := (Tx + i * Wx - Sx, Ty + j * Wy - Sy)`. For a given `(i, j)` pair, the distance is the length of the vector, `sqrt(Dx * Dx + Dy * Dy)`, and the direction in radians is `atan(Dy / Dx)`. The **shortest path** is one of the 9 paths, where `i` and `j` are in `{-1, 0, 1}`:

The `i` and `j` values for the **shortest path** can be determined directly:

```
int i = Sx - Tx > Wx / 2 ? 1 : Sx - Tx < -Wx / 2 ? -1 : 0;
int j = Sy - Ty > Wy / 2 ? 1 : Sy - Ty < -Wy / 2 ? -1 : 0;

```

Thank you, @IlmariKaronen, @SamHocevar and @romkyns for your help!
> 12 votes

# Answer
Compute one possible direction vector, even if it's not the shortest, then wrap its X coordinate so that it is in the `[-MapX/2,MapX/2]` range, and same for Y:

```
int DirX = (T.X - S.X + 3 * MapX / 2) % MapX) - MapX / 2;
int DirY = (T.Y - S.Y + 3 * MapY / 2) % MapY) - MapY / 2;

```

That's it! You also get the distance without further calculations:

```
double dist = sqrt((double)(DirX*DirX + DirY*DirY));

```
> 5 votes

# Answer
I guess there are a number of ways to do this. Here are 2 I can think of off the top of my head:

**#1: Handle cases manually**

There are exactly 10 cases that can happen:

* It's in the same tile as `S`
* It's in any of the 8 surrounding tiles
* It's not found at all.

For each of the surrounding tiles though, they are permutations of different calculations for the X or Y distance component. Because it's a finite number of cases, you can just hard-code how to calculate them, and find the shortest distance between all of them.

Here's an illustration of 2 cases for finding `dx`. Case 1, where `T` is in the same tile as `S`, dx is just `S.x - T.x`. For the tiles to the right, `dx` will be calculated as `TileWidth - S.x + T.x`.

```
               :
               :  T
               :
:--------------:---------
:              :
:           S  :
:  |--------|--:--|
:dx=(S.x-T.x) dx=(TileWidth-S.x+T.x)
:  T           :
:              :
:--------------:

```

As a small optimization, find the minimum distance before you take a square root. Then you save yourself up to 7 `sqrt` calls.

**#2: Abstract the coordinates**

If you need to do something more spacially "fluid", like a path-finding algorithm, just abstract the coordinates so your path finding algorithm doesn't even realize the world is made of repeating tiles. The path-finding algorithm could go infinitely in any direction theoretically (ok well you'll be limited by numeric limits, but you get the point).

For simple distance calculation, don't bother doing this.
> 0 votes

# Answer
Don't bother with the "9 directions". The reason is that there are 5 degenerate cases amongst those 9: "straight north", "straigt west", "straight south", "straight east" and "identical". For instance, straight north is degenerate because it represents the case where northwest and northeast join and produce the same result.

Thus, you have 4 directions to calculate, and can just pick the minimum.
> 0 votes

# Answer
Thanks for all the answers in the end I used Toomai edited by Scott Chamberlain. I had too make a few changes due to the fact that my coordinate system starts with y at the top left and increases as you move down (basically inverted compared to normal graph coordinates for y).

I've posted in case anyone else finds this page and has the same reversed y system.

```
  int dx = T.X - S.X; // difference in position
int dy = S.Y - T.Y;

if (dx > MapX / 2) // if distance is bigger than half map width, then looping must be closer
    dx = (dx - (MapX / 2)) * -1; // reduce distance by half map width, reverse
else if (dx < -MapX / 2) // handle the case that dx is negative
    dx = (dx + (MapX / 2)) * -1;

//Do the same for dy
if (dy > MapY / 2)
    dy = (MapY - dy)) * -1;
else if (dy < -MapY / 2)
    dy = (dy + MapY);

double angle = atan2(dy,dx) * 180 / PI; // provides angle in degrees

angle = 180 - angle; //convert to 360 deg

```
> -1 votes

---
Tags: c++, algorithm
---