# Question
Title: Rectangle collision is not working correctly
I have difficulties with the rectangle collision. My character can go through the right side and through the bottom of each platform rectangle. I guess their is a mathematical problem with the collision, but I don't know what is wrong.

What should I change? I want to do a little platformer, something like the old Mario games.

Backgrounds.LevelTilesList is a list of type RectangleF. Every tile in the level is saved in this list.

```
Vector2 Player_Gravity = new Vector2(0, 4.5f);
Vector2 Player_Movement = new Vector2();
Vector2 Player_Size = new Vector2(29, 80);
System.Drawing.RectangleF Player_RectF = new System.Drawing.RectangleF(100, 100, 29, 80);
System.Drawing.RectangleF Player_NewRect;
bool collisionTop, collisionBottom, collisionRight, collisionLeft;

    protected override void Update(GameTime gameTime)
    {
        KeyboardState currentkeyState = Keyboard.GetState();

        if (currentkeyState.IsKeyDown(Keys.Left))
            Player_Movement.X -= 5;
        if (currentkeyState.IsKeyDown(Keys.Right))
            Player_Movement.X += 5;
        if (currentkeyState.IsKeyDown(Keys.Up))
            Player_Movement.Y -= 10;
        if (currentkeyState.IsKeyDown(Keys.Down))
            Player_Movement.Y += 10;

        Player_Movement += Player_Gravity;
        // Calculate new position
        Player_NewRect = Player_RectF;
        Player_NewRect.X += Player_Movement.X;
        Player_NewRect.Y += Player_Movement.Y;

        // check for collision
        for (int j = 0; j <= Backgrounds.LevelTilesList.Count - 1; j++)
        {
            if (Player_NewRect.IntersectsWith(Backgrounds.LevelTilesList[j]))
            {
                float halfBoxWidth = Backgrounds.LevelTilesList[j].Width * 0.5f;
                float halfBoxHeight = Backgrounds.LevelTilesList[j].Height * 0.5f;
                float halfBoxPlayerWidth = Player_NewRect.Width * 0.5f;
                float halfBoxPlayerHeight = Player_NewRect.Height * 0.5f;

                Vector2 posDiff = new Vector2((int)((Backgrounds.LevelTilesList[j].X + halfBoxWidth) - (Player_NewRect.X + halfBoxPlayerWidth)), (int)((Backgrounds.LevelTilesList[j].Y + halfBoxHeight) - (Player_NewRect.Y + halfBoxPlayerHeight)));
                float maxDiffX = halfBoxWidth + halfBoxPlayerWidth;
                float maxDiffY = halfBoxHeight + halfBoxPlayerHeight;

                collisionTop = posDiff.Y < -halfBoxHeight &&
                                        posDiff.Y > (maxDiffY) * -1
                                        &&
                                        !collisionRight && !collisionLeft;

                collisionBottom = posDiff.Y > halfBoxHeight &&
                                        posDiff.Y < maxDiffY
                                        &&
                                        !collisionRight && !collisionLeft;

                collisionLeft = posDiff.X < -halfBoxWidth &&
                                    posDiff.X > maxDiffX * -1 &&
                                    !collisionBottom && !collisionTop;

                collisionRight = posDiff.X > halfBoxWidth &&
                                        posDiff.X < maxDiffX &&
                                        !collisionBottom && !collisionTop;

                if (collisionTop || collisionBottom)
                    Player_Movement.Y *= -0.5f;
                if (collisionLeft || collisionRight)
                    Player_Movement.X *= -0.5f;

                // Adjust the position
                if (collisionBottom)
                {
                    Player_NewRect.Y -= Player_NewRect.Bottom - Backgrounds.LevelTilesList[j].Top;
                }

                if (collisionTop)
                {
                    Player_NewRect.Y += Player_NewRect.Top - Backgrounds.LevelTilesList[j].Bottom;
                }

                if (collisionLeft)
                {
                    Player_NewRect.X += Player_NewRect.Left - Backgrounds.LevelTilesList[j].Right;
                }

                if (collisionRight)
                {
                    Player_NewRect.X -= Player_NewRect.Right - Backgrounds.LevelTilesList[j].Left;
                }
            }
        }

        Player_RectF = Player_NewRect;
        Player_Movement = new Vector2(0, 0);
        base.Update(gameTime);
    }

```

# Answer
> 1 votes
Just to be clear: Per the convention of System.Drawing.RectangleF, rect.Top is a smaller value than rect.Bottom and so "up" is negative y.

Let's consider the case where the intersecting tile's center is above new player rect's center:

posDiff.y is negative.

collisionTop is true.

new player rect's Top is *above* tile's Bottom, otherwise there'd be no intersection

So, this expression is negative:

```
Player_NewRect.Top - Backgrounds.LevelTilesList[j].Bottom

```

So, this code block moves the player ***up***, further into the tile, which is wrong.

```
if (collisionTop)
{
    Player_NewRect.Y += Player_NewRect.Top - Backgrounds.LevelTilesList[j].Bottom;
}

```

So try flipping the sign on that last line of code. Also, step through the code in the debugger to see if everything I described is correct.

---
Tags: xna, c#, collision-detection
---


# Question
Title: How to add a timer - Visual Studio, XNA (C#)
I'm wanting to add a timer in an XNA game using C#. The ultimate goal is to increment a score in a game every second by 10 points. As of now the score stays at zero. Watching YouTube videos is proving to be counter productive as they're quite confusing.

Thanks.

# Answer
I believe something like this should work. (Place the code in the Update block)

```
Timer += gameTime.ElapsedGameTime.TotalMilliseconds; // Increment the timer by the elapsed game time.

if (Timer >= 1000) // Check to see if one second has passed.
{
    Points += 10; // Increment the points by 10.
    Timer -= 1000; // Reset the timer.
}

```
> 3 votes

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


# Question
Title: What's involved in resetting the graphics device?
I'm playing with XNA 4.0, VS2010. I've created a window (not maximized) and drawn some sprites. All is good until I resize the window, after which the sprites stop displaying or only partially display. I'm pretty sure it has something to do with needing to reset the device or something, but can't find any clear instructions or sample code. It's not just a case of needing to increase the preferredbackbuffer size, because even if I shrink the window I get this symptom. I've looked at the source code that I was able to get from Microsoft before they shut down XNA, but it doesn't actually explain anything.

Any help or advice?

If it makes any difference I'm creating DrawableGameComponents and doing my updates and drawing in their Draw/Update routines.

# Answer
When you change the size of the xna control... the viewport is changed...

so you have to recreate your camera projection matrix..

if you are using spritebatch you should recreate it to initialize the projection matrix that it uses internally.
> 1 votes

# Answer
So, after some research, I found the problem (Jamie Hyneman: Well, THERE'S your problem!). Essentially the comment I referenced earlier describes the issue. When you change window size, the device is lost. When the device is lost, rendertargets are invalidated (but not textures). You can either check the RenderTarget2D.IsContentLost flag, or attach to the RenderTarget2D.ContentLost event to trap this as it happens.

Also, the Rendertargets don't seem to ALWAYS get invalidated. It may depend on resource usage.
> 1 votes

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


title: What is Volumetric Rendering?

text:
# Question
Title: What is Volumetric Rendering?
I came across this term when searching for ways to visualize collection of voxels. What is volumetric rendering ? How is it different from normal surface rendering ? Are there any special advantages of using volumetric rendering ?

# Answer
Volumetric rendering refers to a technique for generating a visual representation of data that is contained in a three dimensional space (volume). Examples of this are atmospheric effects such as smoke and fog and techniques applied to scientific visualization such as marching cubes to generate surfaces from volumetric data. In marching cubes, data is represented as voxels, but in the sense that we store some floating point value in a structured grid in three dimensions.

*Volume rendering* is contrasted with *Surface rendering* because the data that is being rendered is coming from a three dimensional data set rather than a two dimensional data set (a surface). In surface rendering, we are only concerned with the effects of lighting interacting with a material at a surface and how to best describe the color at a particular surface. In volume rendering, we are interested in some data at a given location in 3D space, and we must figure out how to convey its meaning visually.

For example, if we wanted to render cigarette smoke, we might use a volume rendering technique known as ray marching. We shoot a ray into our scene, and then we move slowly along the ray. At each step, we see how much smoke density there is at that particular position in 3D space based on some data set. From this density, we can choose how much opacity this sample contributes to the final pixel value.

In terms of game development, my experience tells me that volume rendering is rarely used. Dealing with three dimensional data sets and the algorithms used for getting good visual results are usually detrimental to real-time performance both in terms of memory and computational efficiency. The advantages of volume rendering come from their use in the scientific computing community and their ability to very accurately depict data in a visual way. There is a saying in computer graphics that "if something looks right, it is right". This saying gains criticism in the scientific visualization community where "if it is right, it is right".
> 4 votes

# Answer
Volume rendering is a general term that refers to any method of taking a 3D volume of data and projecting it to 2D (i.e. approximating the integration of rays cast into the volume). It's typically used to render transparent effects or data that happens to be stored as a 3D image, such as medical or scientific data.

**Volume Data**

The 3D data can be represented in a few ways:

* A block or regular grid of 3D voxel data.
* An implicit 3D function, e.g. f(x, y, z).
* An atlas consisting of indexed blocks (or bricks) of the original dataset, in the case that the dataset is too large to store completely.
* A point cloud, where the dataset consists of 3D position values with associated data value.

**Transfer Functions**

Each voxel or function value is often a scalar, although gradient values may be precomputed as well and stored alongside it. This value may represent some property of the underlying system or anatomy in the case of medical/scientific imaging, such as proton density in MRI. To be more useful in visualization, we need to map it to a color and opacity using a transfer function. The job of the transfer function is to highlight interesting features in the range of possible values. For example, bone or certain tissues distinguishable by scalar value could be mapped to high opacity, while air would typically be given zero opacity. Now that we have a means of obtaining color/opacity values, we can start to render the volume.

**Rendering**

One approach to rendering is called direct volume rendering, where the volume data itself is used without transforming it into a different form:

* Ray marching: This is an image-based method, where each pixel corresponds to a ray from the viewer into the scene containing the volume. Rendering consists of stepping along the ray and accumulating the color/opacity contribution from each point.
* Texture slicing: This method uses proxy geometry in the form of slices through the volume as a way to optimize the process of composition on modern graphics hardware tuned for blending large amounts of texture-mapped geometry.

Another approach is transforming the volume into a polygonal/mesh representation, often using the marching cubes algorithm. This is seen in a number of voxel-based games with 'smooth' geometry and can be done on the fly in modern hardware.
> 4 votes

---
Tags: rendering
---


title: Freeglut: Functions missing

text:
# Question
Title: Freeglut: Functions missing
I'm currently learning OpenGL (in class) and we're using freeglut 2.8.2, which works just fine (using Visual Studio 2012). As an additional learning resource I'm reading the "OpenGL Superbible, 5h Edition". However, I've noticed that there are some functions that aren't available using the freeglut library.

For example, gluGenerateMipmap or setting anisotropic filtering doesn't work:

```
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest);
void glGenerateMipmap(GLenum target);

```

It simply does not know these functions (glTexParameterf is known, GL\_TEXTURE\_MAX\_ANISOTROPY\_EXT is not). I've googled a bit but didn't really find anything. And since glGenerateMipmap seems to belong to the standard openGL Library (and not glu/glut), it should be available (I hope).

Is there anything I'm missing?

# Answer
`glGenerateMipmap` is an extension, unless you are using OpenGL 3 or above (I think). You probably want to use a library like GLEW to load it.

See OpenGL Extensions for more information about extensions in OpenGL. Many things that were extensions in 2.x were promoted to the core API in versions 3 and 4, but unless you upgrade to those versions, you'll have to use an extension loading library (or do it yourself, which is not really that fun or worthwhile).
> 3 votes

---
Tags: opengl, glut
---


# Question
Title: Is there any game engine capable of true binaural positional 3D audio?
I am by no means a game designer, so I apologise in advance if I fail to use the proper jargon. Feel free to correct my mistakes.

My understanding is that, at the moment, in most if not all first-person shooters (such as L4D2 or Bioshock), the "3D audio" is generated by taking the player's position and displacement within the game into account, but mainly by playing on

* balance (to indicate the direction to the source of a sound),
* amplitude (to indicate the distance between the player and the source of a sound).

However, for a psychology experiment, I'd like to make my subjects play a custom first-person shooter with true binaural positional 3D audio using head-related transfer functions (HRTFs). If you don't know what I'm talking about, I invite you to listen to the binaural recording at this URL.

I know of only one game using true binaural positional 3D audio: Papa Sangre, but it's not an FPS.

My questions (all related) are:

1. Can any currently available game engine (Valve's Source?) be used to design such an FPS game?
2. If the answer to 1. is yes, do you have any useful links?
3. If the answer to 1. is no, has a game engine capable of such marvels been announced yet?
4. Are there signs that true binaural positional 3D audio will find its way soon in future FPS games? (I certainly hope so!)

# Answer
**For 1**.: Papaengine, was used to make the game you've linked (Papa Sangre). The engine claims it's *"the only true real-time binaural audio engine for iOS!"*, so they seem to be rather limited. Though, I wouldn't think iOS would be the best choice for a FPS.

There is this article from GarageGames that claims that FMOD is available for the Torque engine. Where FMOD claims:

> The software mixer even has a 'HRTF' (Head-Related Transfer Function) mode to provide 3D realism through headphones!

Further, there's this paper that describes using Blender game engine and CLAM to get HRTFs.

**For 2**: I'm not going to recommend one, I've not used any of them for development, and this question is already borderline "Which technology to use".

**For 4**: There are signs, given the various research papers and implementations I found, it looks like some people are interested.
> 3 votes

---
Tags: 3d, audio, first-person-shooter, sound-effects
---


# Question
Title: Python mini RPG enemy movement. (how to have two infinite loops running at the same time)
I have a problem with my RPG.

I want enemies to wander randomly. So I put:

```
enx_speed = random.randint(-2, 2)
eny_speed = random.randint(-2, 2)

```

in the main loop (`while true:`). However, that loops every 20 milliseconds (it's what I use to redraw, find key presses, etc).

How can I have two infinite loops running at the same time with different loop times?

# Answer
I managed to solve this myself and the method I used was probably not the best but it was really really easy.

First I define "enloop" outside of the main loop.

```
enloop = 0

```

Then inside the loop every time the loop runs:

```
if enloop < 10:
    enloop = enloop + 1
else:
enloop = 0

```

And later also in the loop:

```
if enloop == 10:
    enx_speed = random.randint(-2, 2)
    eny_speed = random.randint(-2, 2)

```

Thanks for responding and let me know if this is wrong somehow.
> -1 votes

# Answer
Don't know python, but here is a basic arbitrary-language example.

You should only have one game loop that updates all other entities. You can determine how much time has passed between each running of the loop and pass that information on to the entities who can use this information. For Example:

```
main() {
    lastSystemTime = currentSystemTime;
    while (true) {
         //Time passed since last loop in milliseconds
         int delta = currentSystemTime - lastSystemTime;
         lastSystemTime = currentSystemTime;

         //Loop through all interested parties and update them with time passed
         for all sub-entities {
             entity.update(delta);
         }
    }
}

```

Then in the entity

```
constant int WAIT_TIME = 200; //200 milliseconds to wait after actions performed
int timer = 0; //How much time to wait before performing actions

update(int delta) {
    if (timer <= 0) {
        //Perform the actions, then set the wait timer.
        doStuff();
        timer += WAIT_TIME; // Add the wait time to the timer
    }
    else {
        timer -= delta; //Decrease current time to wait by how much time has passed
    }
}

```
> 5 votes

# Answer
You only need one infinite loop running very fast to do what you're after. Inside the loop you calculate time elapsed since last run. If it's greater than X, then you call function1. If it's greater than Y, then you call function2.
> 1 votes

---
Tags: python, rpg, pygame
---


title: Calling glGetError() in release builds?

text:
# Question
Title: Calling glGetError() in release builds?
Currently, I'm calling glGetError() after each OpenGL function call in order to be able to detect and report bugs.

I've been reading that glGetError() calls should be reduced to once per frame in release builds. But if I do this and something does not work properly I won't be able to report where the code is failing, I would get an exception report saying that something related to OpenGL is not working properly but I wouldn't be able to detect where the code is failing.

What are the most common aproaches to report errors related to OpenGL? Should I keep all the glGetError() calls or should I call glGetError() just once per frame?

# Answer
> 2 votes
glGetError is slow on Android and should be avoided. Something you can do is create a LoggerInterface, which is called for each method call. Put a dummy implementation that does nothing in you release code, and a real one in your lab (which calls glGetError). In release code, check glGetError once per frame, and activate the real LoggerInterface for the next frame if an error is found (And save the log somewhere you can send it back to you).

# Answer
> 1 votes
I assume you're talking about running the code on the end user's machine, not just for testing.

You definitely should not call glGetError after every GL function call. You cannot know how it is implemented in certain drivers or how it will be implemented in the future. As a practical example, on NaCL (and possibly anywhere using Google's WebGL implementation on Windows) it's terribly slow as it halts some kind of multithreaded execution.

Ideally, of course, you shouldn't need to call it in release mode ever, because there shouldn't be any bugs in your code, and all dynamic input should be validated upon loading. Are you sure you cannot guarantee this? Remember that having a graphics error is about as likely as having any other kind of programming error, yet you don't attempt to run some kind of debugger in release mode.

If you absolutely need to call it, you could call it once per frame, and if you catch one, call it once per GL call and see if you can pinpoint the error. But honestly this method may fail anyway. Alternatively you could have the end user decide to run in "error report mode" or whatever you may want to call it.

---
Tags: opengl, opengl-es, opengl-es2
---


title: Does Java support OpenGL by itself?

text:
# Question
Title: Does Java support OpenGL by itself?
Note: This is long but I explaining everything that you need to know. Don't read half way through it and say "What's the question?". It's simple but long and I need help as soon as possible.

So I asked a question not long ago that was similar but it wasn't my best work. What I'm trying to do is make a small jar with no other files but the jar (maybe natives if needed) that handles a window and graphics for games. I'm making this for some people I know who don't want to get into advanced graphics and stuff to make games, plus I figure it would be easier to stick everything they need into one jar that they know how to use. Anyway I found JOGL but after like the past 3 hours or so all I got with JOGL was the memory to never use it because it's a pain to install (at least for me) and everyone says a different way to install it and I need like 100 files along with my jar to get it to work. So since I'm not dealing with JOGL i figured that it's best to try and find something else. So does anyway know any way to get OpenGL into java without libraries that add more files and if so just like 1 file? I'm trying to get it so it's just that jar and nothing else. I just want this done but I'm very confused. I would also like it to be able to run on Windows, Linux and Mac. I only have a Windows machine although I can get Linux to test it on and I know someone who has a Mac but keep in mind I'm building it on a Windows machine. So my question really is how would I be able to stick OpenGL (I would like OpenAL and maybe OpenCL too) in a single jar and nothing else? I have a few exceptions such as I'm kinda ok if I need a few natives but I don't want 10 jars and 50 natives and I need it to work on all kind of machines, and also I would like to be able to use swing to handle the window.

# Answer
No, OpenGL is a library written in C. You will need some binary file for each platform to interface correctly with OpenGL. There has to be some platform specific part because the JavaVM does not virtualize the OpenGL device for you.

However when developing with Java you can use Maven which is a sort of advanced build system, like Ant but done right I heard people call it (I never used Ant though). You can just pull JOGL into Maven and it will use the correct binaries for each platform when building or releasing.

Here are the entries in the POM file I use to use JOGL with Maven:

```
<repositories>
     <repository>
        <id>jogamp-remote</id>
        <name>jogamp test mirror</name>
        <url>http://www.jogamp.org/deployment/maven/</url>
        <layout>default</layout>
      </repository>
  </repositories>

 <dependency>
     <groupId>org.jogamp.gluegen</groupId>
     <artifactId>gluegen-rt-main</artifactId>
     <version>2.0-rc9</version>
   </dependency>

   <dependency>
     <groupId>org.jogamp.jogl</groupId>
     <artifactId>jogl-all-main</artifactId>
     <version>2.0-rc9</version>
   </dependency>

```

(Note: I totally feel your pain when using JOGL without an automated system to do it for you, men their documentation is worthless I usually end up just placing all the natives in the same file as the JAR and hoping it works)
> 7 votes

# Answer
An alternative to JOGL is LWJGL. It really is "lightweight", as the name suggests, both in terms of installation and in terms of provided functionality - it's a pure wrapper to the C functions, with some additional (and really helpful) checkers.

The documentation is certainly sufficient for me to install it on Windows, Linux and Mac; however, while 32-bit Windows is basically straightforward, adding 64-bit Java on Windows is a bit more of a hassle. And Linux is, as always, a bit harder for it's own reasons.

I'm not sure if you can into one single .jar and run it on any platform; however it's possible to make a single download that would work anywhere.
> 5 votes

# Answer
I'm adding this by way of expansion on a comment I made to a previous answer. This question in itself shows a fundamental misunderstanding of what OpenGL *is* so I believe it's necessary to say more.

**OpenGL is not software**

OpenGL is "a software interface to graphics hardware" (page 1 of the OpenGL specification until the ARB changed the terminology a little recently). From this you may glean some important things:

* The graphics hardware is what actually does all the work; all that OpenGL does is provide a means for your program to talk to the hardware.
* As an interface, it can be read from two sides: (1) how your program sees it, and (2) how the graphics hardware sees it.
* As a standard, the "how your program sees it" side is consistent for all hardware (barring obvious factors such as different GL\_VERSIONs).
* Because different hardware is different, the "how the graphics hardware sees it" side will be different for different graphics hardware.
* Because different hardware is different, an OpenGL implementation that works for one hardware vendor **WILL NOT** work for a different hardware vendor.
* Because each vendor has different hardware generations, an OpenGL implementation that works for one hardware generation **MAY NOT** even work for a different hardware generation from the same vendor.

From all of that, you'll see that it's quite *impossible* for *any* language to support OpenGL by itself. OpenGL is not provided by a language; it *cannot* be provided by a language; it *must* be provided by the hardware vendor. Don't think of OpenGL as a library; think of it as a device driver (which is not too far off the truth). It's quite low level, it's very hardware-dependent.

So what would it mean for OpenGL to be natively supported by a language? It would mean that the parts of OpenGL that are hardware dependent (i.e. the interface as it's seen from the hardware side) *could not exist*. It would mean that *something else* would be needed to sit between the program and the hardware. But that "something else" would not be OpenGL, because OpenGL already clearly defines what it *is*, and it's *not* that "something else".

(All of this is deliberately ignoring pure software implementations - like Mesa3D - which you *don't* want to use as they are *slow* \- I don't mean "slow" like 50% or 25% of the performance of a hardware implementation; I mean "slow" as in "you're lucky if you get 1 frame per second.)
> 2 votes

# Answer
This answers the main question: "So my question really is how would I be able to stick OpenGL (I would like OpenAL and maybe OpenCL too) in a single jar and nothing else?"

You may choose to place all the JogAmp JOGL 2.0 JARs inside your main JAR when you export your application using Eclipse. Use the "Package required libraries into generated JAR" in the Eclipse Runnable JAR export dialogue. By exporting like this will create a single jar file that will run on all platforms. http://forum.jogamp.org/Exporting-tp4029053p4029054.html
> 1 votes

# Answer
You can use LWJGL which is just one jar file (and natives) like you requested.

LWJGL is easy to install and includes openGL. It also includes openAL and openCl ( I think).
> 0 votes

---
Tags: opengl, java, game-design, swing
---


# Question
Title: How to reduce image size without pixelation?
I see lots of games with smooth edges characters and high res images, however when I try to reduce images to say 64x64 for my character I just get a pixelated mess. even if I start with a 64x64 canvas I get pixelated edges.

Should I be scaling with OpenGL? or is there some technique perhaps with photoshop or pixen that I am unaware of?

# Answer
Sounds like the scaling algorithm you're using isn't interpolating pixels.

Pictures are best explained with pictures:

It's the Major, first in full, then scaled down with Lanczos (left) and nearest-pixel (a.k.a. no interpolation) (right) to two sizes.

The same comparison, in 3x magnified:

Make sure the scaling you're using is resampling sensibly. For example, ImageMagick has a `-filter Lanczos` option.

It doesn't even need to be fancy Lanczos, in case your tools can't do it; cubic (leftmost) looks the same to me:
> 27 votes

---
Tags: opengl, android, textures, assets, scale
---


# Question
Title: How to pack the game files into one without using any file compressor?
Well, one example is this file of the game The Sims 2 for PS2: quickdat.arc. The file contains this .arc extension, but it's no one an archive file and it contains some data of the game inside. How can I do this? Put so many files in one?

How to do something like this? All the game files inside one without using a file compressor?

# Answer
The process to create such an archive file is fairly straightforward. You'll want to read in the raw bytes of every input file, writing them to a single in-memory output buffer as you go.

You will also need to keep track of where in the output buffer you begin to write each file. Without this "table of contents" information, it will be very difficult to get the individual file bytes out of the archive later.

Once you've copied all the input files into the buffer, open the final output file and write the table-of-contents information into it. Then write the output buffer that contains the raw file bytes.

Then, to read data from the archive file later, you can open it and read the table-of-contents chunk. That will give you the offsets (relative to the end of the table-of-contents) of each file in the archive.

The above will get you a basic implementation. There are, of course, many variations you can make on this theme, for example by storing more file metadata, or providing support for buffering the I/O operations in some fashion, or precomputing the table of contents data based on just the file sizes so you can stream the archive output to disk instead of requiring it to all exist in memory at once. Whether or not these are relevant to you depend on your specific needs.

Some very straightforward and naive pseudo-code in a C#-like language might be:

```
var archive = new List<byte>();
var contents = new Dictionary<string, int>()

var files = /* a list of all input files that will be in the archive */

foreach (var file in files) {
    var bytes = ReadAllBytes(file);

    // We're about to write the file to the archive, so store the offset.
    contents[file] = archive.Count;

    // Write the actual bytes.
    archive.AddRange(bytes);
}

// Now write the final archive.
var output = /* name of the output file */
foreach (var pair in contents) {
    WriteToFile(output, pair.Key);
    WriteToFile(output, pair.Value);
}

WriteToFile(output, archive);

```
> 4 votes

# Answer
Very simply Files are a collection of bytes that can be interpreted anyway you choose (but will only be interpreted correctly following the proper steps for each individual file). The extension is used as a tip for how you should go about interpreting this file. When a developer makes a file-type you've never heard of it's because it's his/her own custom file-type that suits his/her own purposes, or he/she just doesn't want you to know what file-type it is at all by making a random extension.

You can do something like this by reading the byte data of files, and writing it back into a larger one. Nothing is stopping you from writing the file data of several files into one larger one as long as you know how to read the individual file data back to suit your own needs.

This is how compression works. It takes the original file data and runs algorithms to create new condensed file data that can be reworked using similar techniques into the original file. For example a .zip extension just tells you that the file data is compressed data using the zip format, and will be pretty useless to you interpreted in any other way.

Read up on basic file input/output in your language of choice for the actual HOWTO of working with file data.
> 1 votes

---
Tags: file, compression
---


title: How to preload a vast amount of models?

text:
# Question
Title: How to preload a vast amount of models?
This is more a theoretical question,

during runtime, my game runs smooth without any hickups. But as standard game-objects, my game contains collectibles such as coins (which are rotating Models).

I can (again, during runtime) load 10 of those coins without getting any hickups. But as soon as I load 50 coins, the runtime freezes for some ticks and continues then.

How could I generally preload a 50-Coin case, so that the game has done all loading during load-time?

This is how I draw a single Coin (and every of those 50 get drawn like this)

```
public override void Draw(RenderContext renderContext)
{
    var transforms = new Matrix[_model.Bones.Count];
    _model.CopyAbsoluteBoneTransformsTo(transforms);
    foreach (ModelMesh mesh in _model.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
             effect.View = renderContext.Camera.View;
             effect.Projection = renderContext.Camera.Projection;
             effect.World = transforms[mesh.ParentBone.Index] * WorldMatrix;
        }
        mesh.Draw();
     }
     base.Draw(renderContext);
 }

```

How could I draw one Model in x: 10, x: 20 and x:30 (with the other values like Y,Z or scale untouched) for instance?

# Answer
Upon creation of a coin, do you load the model/texture from disk every time? This would make loading extremely slow. Creating a coin object without disk IO should generally be very, very fast. If that's not the case, try looking at object pools.

Wikipedia:

> A pool in computer science is a set of initialised resources that are kept ready to use, rather than allocated and destroyed on demand. A client of the pool will request an object from the pool and perform operations on the returned object. When the client has finished with an object (or resource), it returns it to the pool, rather than destroying it.

Create a coin pool upon loading a level/the game, then use and put coins back as necessary.

Edit: For a more thorough explanation, see this post.
> 4 votes

# Answer
You don't need 50 or 10 or even 2 copies of a model. You don't need to pool them, either (though pooling the objects they represent may be worthwhile).

You need one model, and you need 50 instances of it. For each mesh in your coin model, you draw that mesh at 50 locations. For simple, repeated models, it makes much more sense than drawing each mesh for each model location.

### The bounty for more details edit:

The reason you aren't getting sufficiently detailed answers is that the solution to your problem is too extensive for a single answer. Your posted code is the out-of-the-box, tutorial method for drawing a model, and it simply doesn't work for drawing a large number of models. As a matter of expert opinion, the `Model` class itself isn't good for drawing a lot of models (or anything else).

So you want to draw a lot of models anyway. Fine, but you need to drastically change your code. Here's a shortened list:

* Load the model differently
* Handle its meshes individually
* Manually store individual transforms that represent models
* Manage those transforms into batches of the correct size for your hardware (the sample below has compiler directives for the differences between the 360 and the PC)
* Make an extra graphics buffer to hold the transforms
* Create a shader to handle both buffers
* Draw your model in a completely different loop

Easy, right? NOPE! It's a complete overhaul; far beyond the scope of your current `Draw()` method. No one can give all that code in a detailed answer. But luckily for you, no one has to. You just have to download and study the example project below.

### End edit. Begin solution to drawing lots of models.

The XNA instancing example puts together the technical details of whole process. The purpose of this example is to demonstrate the terrible loss of performance from drawing one model at a time in XNA. The example can draw thousands of models at 60fps, or choke on only a few. Screenshot:
> 13 votes

---
Tags: xna, c#, rendering
---


# Question
Title: What do I need to do legally to protect my game with copyright?
I am in the process of writing a game and I'm wondering what the copyright laws about publishing this game are.

I do not (for now) intend to make money from this. The beginning of my code contains a comment with `# Copyright 2013, Collin Norwood`, but is that legally valid? Do I have to apply with some government for a trademark or such?

# Answer
(Stock caveat: I Am Not A Lawyer and this should not be construed as specific legal advice.)

If all you're concerned about is that your work is copyrighted to you, then you're in luck - that happens automatically upon creation of the work, and no explicit copyright mark is needed.

On the other hand, if you're concerned about the prospect of people infringing on your game's copyrights (and you're in the US - other agencies will be appropriate for different countries, of course), then probably the simplest route to take is registering your copyright via the US federal government's Electronic Copyright Office; this provides all the benefits of classic 'paper' registration for a relatively nominal fee (it looks like $35). This allows several benefits over the implicit copyright that's automatically granted to your work; for instance, you must register a copyright on your work before you can file a suit for infringement (though note that you don't have to register before learning of the infringement!), and having registered in advance of any suit both provides *prima facie* evidence of your copyright's validity and allows you to recover attorney's fees and statutory damages for the infringement. (For more details on this, I recommend ask.com's page on copyrights or the SFWA page on the benefits of copyright registration)

If you're *very* concerned about people infringing on your IP rights, or you want protections beyond just basic registered copyright protection (e.g. trademarks on certain expression elements or on a logo, etc), then the answer starts with 'Find An Intellectual Property Lawyer' — they'll be much more competent to advise you than anyone else here.

Separate from both of these matters, of course, is the issue of how much you should be concerned with copyright protection right now. I won't tell you **not** to be worried; that's an issue you can only resolve for yourself. But I will say that my gut instinct is that you should be much more worried with making your game first; having to be actively worried about people stealing your code falls into the Nice Problem To Have category. That's not to say that you *won't* have it eventually — just that IMHO it should be quite a ways down your list of concerns.
> 8 votes

# Answer
As long as you can prove ownership you're protected by copyright laws. (I.E. My work showed up on my portfolio site, before anyone else used it.) Of course, it is always a good idea to put copyright information on all work to remind people to contact you if they want to use it in any form.
> 4 votes

# Answer
Nothing is required to enact copyright over a work. That includes placing "Copyright" on the work in question. However, the more steps you take to formalize your copyright, the easier it will be to defend.

In order of easier to harder (and more expensive)

But, again, nothing is actually necessary to have legal copyright on any given work. One note, however, is that one cannot copyright ideas or methods (for example, the general design of a game or a method of enacting a mechanic).
> 3 votes

---
Tags: legal, copyright
---


title: PIX and Metro apps

text:
# Question
Title: PIX and Metro apps
I would like to use Pix on a Metro (Win 8) app. However, Pix wants the path to the application, something that Metro apps don't have. Has anybody been able to get Pix working with Metro?

# Answer
PIX isn't going to work with non-desktop apps. The new way to debug these is the graphical debugger built into Visual Studio 2012. I'm also not sure PIX works properly on Win 8 for desktop apps either.
> 4 votes

---
Tags: directx, windows-8, pix
---


# Question
Title: Pokémon character turning / facing: How is it achieved? Movement is already done though
You know that when the player playing Pokémon games want to change the facing of the main character, one would simply tap on the directional pad (D-pad) on the Game Boy (Color/Advanced/Advanced SP) or Nintendo DS systems, and the character would just turn towards the general direction the player wants to turn to.

As far as I know, the turning mechanics from Pokémon Gold/Silver/Crystal is also combined with the movement mechanics from Pokémon Red/Blue/Yellow, which the latter (movement mechanics) is successfully implemented in Java, shown below.

Movement mechanic:

```
package entity;

import level.BaseWorld;
import main.Keys;
import resources.Art;
import screen.BaseScreen;

public class TestEntity extends Entity {

    public Keys keys;
    int facing = 0;
    int turning = 0;
    int xPosition;
    int yPosition;

    int xAccel;
    int yAccel;

    boolean lockWalking;
    boolean lockTurning;
    int turningTick = 4;

    public TestEntity(Keys keys) {
        this.keys = keys;
    }

    @Override
    public void initialize(BaseWorld world) {
    }

    @Override
    public void tick() {
        if (!lockTurning) {
            if (keys.up.isDown) {
                turning = 2;
                lockTurning = true;
            }
            else if (keys.down.isDown) {
                turning = 0;
                lockTurning = true;
            }
            else if (keys.left.isDown) {
                turning = 1;
                lockTurning = true;
            }
            else if (keys.right.isDown) {
                turning = 3;
                lockTurning = true;
            }
        }
        if (!lockWalking && turningTick < 0) {
            if (keys.up.isDown) {
                facing = 2;
                yAccel--;
                lockWalking = true;
            }
            else if (keys.down.isDown) {
                facing = 0;
                yAccel++;
                lockWalking = true;
            }
            else if (keys.left.isDown) {
                facing = 1;
                xAccel--;
                lockWalking = true;
            }
            else if (keys.right.isDown) {
                facing = 3;
                xAccel++;
                lockWalking = true;
            }
            if (turningTick < -5)
                lockTurning = false;
        }
        handleMovement();
        turningTick--;
    }

    @Override
    public void render(BaseScreen screen) {
        screen.blit(Art.player[facing][0], xPosition, yPosition, 16, 16);
    }

    //-----------------------------------
    //Private methods

    private void handleMovement() {
        if (lockTurning) {
            facing = turning;
        }
        if (lockWalking) {
            xPosition += xAccel;
            yPosition += yAccel;
        }
        if (xPosition % 16 == 0 && yPosition % 16 == 0) {
            lockWalking = false;
            xAccel = 0;
            yAccel = 0;
        }
    }
}

```

The movement mechanics I have implemented as of now **DOES NOT** contain codes that rely on `System.currentTimeMillis()` or `System.nanoTime()`, which means it's not elapsed-time-based. Rather, it relies on current-states via fixed game ticks, which is prominent during the Game Boy era.

Unfortunately, it contains a side effect where if the player were to press multiple keys on the D-pad, it will cause the character to turn while it's moving. I can remove only the turning mechanics from the mixed mechanism above, and would obtain the movement mechanics that were used only in Pokémon Red / Blue, Generation 1 games.

However, I would like to use the **movement + turning mechanics** used from Pokémon Gold/Silver/Crystal, Generation 2 and above.

Could someone suggest an idea / tip / hint / solution for this problem?

You may also use the codes given above to your likings, just make sure to change stuffs a bit while you're at it.

# Answer
> 1 votes
Blame me for never having played any of these games, so I can just assume you want your character to turn around while walking rather than turning instantly (e.g. like in The Legend of Zelda games or most JRPGs).

If so, I'd simplify the whole thing using "steering":

* Store the current direction the player is facing as an integer. You can either use 4 or 8 directions.
* When tapping a directional key, you set a "target facing"; again as an integer with 4 or 8 possible values.
* Then, just increase/decrease that value (the current direction) each tick until both match.
* This way you should get a rather smooth turnaround, that shouldn't mess with actual movement, especially if you only move the character in the current direction.
* If you're not using pixel graphics/sprite Sheets, you might want to actually use some float/double values for even smoother turning.

---
Tags: java, game-mechanics, movement
---


# Question
Title: Animations not working on custom actor in LibGDX
I have this code for rendering a sprite, retrieved from a TextureAtlas

```
public class SpriteActor extends Actor {
private Sprite sprite;

public SpriteActor(TextureAtlas atlas, String spriteName) {
    sprite = atlas.createSprite(spriteName);
    this.setWidth(sprite.getWidth());
    this.setHeight(sprite.getHeight());
    this.setBounds(0, 0, this.getWidth(), this.getHeight());
}

@Override
public void act(float delta) {
    sprite.setPosition(this.getX(), this.getY());
    sprite.setOrigin(this.getOriginX(), this.getOriginY());
    sprite.setRotation(this.getRotation());
    sprite.setScale(this.getScaleX(), this.getScaleY());
}

@Override
public void draw(SpriteBatch batch, float parentAlpha) {
    Color color = new Color(this.getColor().r, this.getColor().g,
            this.getColor().b, this.getColor().a * parentAlpha);

    batch.setColor(color);
    sprite.setColor(color);

    sprite.draw(batch);

}

}

```

EDIT: Using actions with a Image actor in the same stage works, It's only my actor that doesn't

When I set the transparency like this : `actor.setColor(1, 1, 1, 0.5f);` I can see the sprite becoming half transparent; or, if I set the position manually (`actor.setPosition(0, 30);`) I see the sprite to the correct position; but if I try to use actions (`import static com.badlogic.gdx.scenes.scene2d.actions.Actions.*;` \[...\] `actor.addAction(fadeIn(3)` or `actor.addAction(forever(rotateBy(45), delay(1))`) they just do nothing.

Do I need to implement something to have predefined actions working on my code? Or what do I need to make this code work?

# Answer
This is just speculation:

Maybe you forgot to call `act()` on your Stage that has all the Actors. Actions are updated per frame through the `act()` method on each Actor which is called by Stage's `act()`.

```
public void render () {
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();
}

```

From https://code.google.com/p/libgdx/wiki/scene2d

**Edit**: Real problem was overriding act() without calling super.act() which updates list of Action as found in Actor class source.
> 2 votes

---
Tags: libgdx, sprites, texture-atlas, tweening
---


title: Modern shadow rendering techniques?

text:
# Question
Title: Modern shadow rendering techniques?
What is the state of the art in terms of shadow rendering? My target is OpenGL 3.2, using a deferred rendering pipeline, if that matters.

It's been years since I looked into shadow rendering, and at that time there were numerous techniques available, from stencils to the various shadow mapping methods. At that time, rendering shadows required separate rendering passes, controlled by the CPU. But then recently I saw a demo where a scene was rendered entirely on the GPU, including shadows. I have no idea how that would have been accomplished, or if it is even a reasonable thing to do (beyond a tech demo).

Given the large amount of old info on the internet, I'd like to learn what methods people are using these days, and how much of it can be pushed to the GPU (assuming my target OpenGL version supports it).

# Answer
> 10 votes
http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-16-shadow-mapping/ gives a nice overview over the basics. http://en.wikipedia.org/wiki/Shadow\_mapping links to a multitude of research papers describing different improvements and optimisations.

Shadow volumes have been 'the thing' a few years ago. http://en.wikipedia.org/wiki/Shadow\_volume nicely describes the technique.

Recently, ray tracing and path tracing based approaches have been used for lightning/shadowing (which have been around before, just not the hardware to utilize them). Though, the optimisations used (e.g. monte carlo rendering with limited iterations) tend to lead to noise/artifacts on camera movement (for an example of the effect, see e.g. http://www.youtube.com/watch?v=FJLy-ci-RyY).

---
Tags: opengl, shadows
---


# Question
Title: Do I need Texture Units when NOT using shaders?
Does calling `glActiveTexture()` even make sense when not using shaders?

I only have to switch the textures before drawing a buffer with `glBindTexture()`, right?

# Answer
Yes, you do need texture units when not using shaders; if you look at the evolution of graphics hardware this will be obvious as multitexturing predated the programmable pipeline.

The classic old-school use case is Quake-style lightmapping, and in fact if you look at the Quake source code you'll see that it used multitexturing (via the old GL\_SGIS\_multitexture extension) and most definitely did *not* use shaders.

For this use you have one texture representing the diffuse colour, one representing the light colour/intensity, and you modulate them together to get the final surface colour.

The exception to this rule is if you're not doing multitexturing, of course. If you're only ever applying a single texture to your geometry then you can quite happily forget that texture units ever existed (since the default active texture unit is texture unit 0).

There is, by the way, no excuse to not use shaders in 2013; the old "old hardware" excuse is not valid any more and hasn't been for many years. Everything supports shaders nowadays and using them will make your life a lot easier.
> 4 votes

---
Tags: opengl, shaders
---


# Question
Title: best structure to handle entities in an entity component based game engine
I am trying to develop a 2D entity component based game with multiple layers as tilemaps (front or back from the scene).

I currently handle the tilemap layers in a 3 dimension array\[z\]\[y\]\[x\]. Each tile from the map is an entity and have a positionComponent which define x, y and z. The array structure is very convenient to update and render only visibles entities (in the viewport).

I have also added an 1 dimension array to handle the ennemies and items. The problem is that I want to fusion the tilemap and ennemy array in one single structure (I want to update and render entities within a single strcture).

As the entities already have a positionComponent defining x, y and z, is there a good way to get rid of the 3 dimensions array without loosing performance?

Ideal will be to be able to do something like entities.get(z, y, x).

# Answer
What you describe is certainly a strange approach to a grid based game. Anyway, there's no way to optimally reference a particular range of your xyz cube of entities without a relational structure containing them such as a 3 dimensional grid array, or something like an octree. Otherwise you're stuck looping through all of them comparing their positions which is unacceptable with large lists of tiles / entities.

It is strange for you to want to combine tiles with entities in a single structure because they would have completely different operations performed on them. Entities would be changing position and state whereas tiles are often static and need to be accessed very quickly for their information. Also if your entities' sizes can span multiple tiles, then there is certainly no reason to try to combine their structures together.

A multi-dimensional array offers very fast lookup at the cost of some memory, and is always the way to go when storing something like grid-based tile data. Entities like moving characters are better stored in lists that you iterate through for small amounts of entities, and structures like quadtrees/octrees for large amounts.
> 3 votes

# Answer
Assuming your tiles / enemies / items all share a common base class, I don't see why this wouldn't work with a 1 dimensional array. You simply call each element as normal, except now you lose the ability to reference a tile by it's position easily. However, you can still do this pretty easily with the xyz components you mentioned.

If they do not have a common base class, then I'm not sure you could do this all in one array.
> 0 votes

---
Tags: java, component-based, entity-system, tilemap
---


# Question
Title: Event-driven vs state synchronizing networking model
I was going through the Tribes network model and the network model used in Quake3. What I understand is that Tribes is more of an event based model where as the Quake model uses game states and delta game states to sync clients. Is my understanding right?

What kind of games do these models favor? Also what are the drawbacks of one model compared to the other. I am currently developing a two player First Person maze solver game and trying to choose between the two models.

# Answer
Note that I'm not knowledgeable about those games specifically, so I can only answer in the general sense.

A lot of modern games do *both* game state synchronization and event delivery to some degree. Each approach has a different use-case, as Anomalous Underdog pointed out.

One advantage of the sync-the-world model is that you can reuse the general state sync code to allow new clients to jump into the game and know what's going on; the server just notes that the state delta is "everything" and sends the whole state down. With an event model, new clients must be specially handled to ensure that all necessary object-creation events are sent on connection in order to get the client up to the current game state.

Another advantage is that creation messages are less important and for some games destruction is unimportant. You don't need to send an explicit "create object X" message and ensure it is handled before any movement messages since I can just create the object when I get a movement message for it. Destruction is still a little complicated, since you need to know the difference between "object X is gone" and "object X has no more updates." Some games's gameplay requires a relatively small set of always-around synced objects so destruction is unimportant.

A pure event model is how many games are implemented at the low-level but some of those events are "here's some new state." Some sync individual object states rather than a whole game state. The advantage of this model is that it's just easier to do with partial ordering of states, non-state-based messages (like chat), control flow, and so on. With the game state model, it's important to have an additional means to send reliable events, so you're still implementing the entire event model *anyway*.

You can combine both methods, using state sync to handle objects that the server and client both know about, and using events for object creation, destruction, and non-state updates. This tends to be where many higher-end games go, as sending an individual state event for each object uses more bandwidth in event framing/headers, but events are needed no matter what. That rarely matters for smaller games or games that don't try really hard to fit into lower bandwidth requirements.

Note that pure state deltas in either model is a huge chore unless every update is ordererd and reliable (e.g. via TCP). The server needs to know which state the client has in order to calculate deltas appropriately. That gets hard because even if the client ACKs a packet a new state delta might be sent before the ACK is received so the client sees extra movement (once from the first packet and then that movement reapplied in the second). The server could keep a state sequence number that is sent with each update and the client can keep recent states for each sequence; the server sends which state sequence it thinks the client has and the client ignores updates if its state sequence doesn't match the packet but then you might needlessly drop some state updates that are accumulated together (eg if a packet has updates from state 5 to 7 but the client is on state 6 from a previous update whose ACK is delayed/lost then the new packet must be thrown away and the update to state 7 from 6 must be resent in another packet). That approach works for lock-step games but is still not ideal.

Using current state updates rather than deltas makes it so that missing intermediary states or duplicated state updates are irrelevant whether they come in the form of state syncs or individual events (you'll still need a proper retry and ordering mechanism for some events but not entire packets).

For a simple two-player game that has little going on besides maze navigation state sync might be easier. Just send the player's positions/orientations and the positions of any movable maze elements with each packet, append any reliable events like chat, and resend those events if their packet doesn't get ACK'd. With a pure event model you'll need to handle a lot more resend and flow-control logic for events and, if things are moving a lot, you'll just be sending an event for each object *anyway* so you're still doing a game state sync.

Or just use TCP; honesty for most hobbyist/student games or even AAA games that don't have a lot of real-timey requirements for action TCP is easier and works just fine (if you turn off Nagle). An increasing number of network-centric games these days use TCP (MMOs, RTSes, RPGs, etc.) but very twitchy/action-y games should still usually aim for UDP to have better latency control. Your game may will work perfectly fine with TCP which simplifies everything by making all messages reliable and ordered.
> 1 votes

# Answer
When you say state synchronization, it just always fires the latest values for those variables. For things that you don't care about their previous values, this is preferable.

Like 3d position for example, you don't care about dropped packets of old position values. You're more interested in where a character really should be right now, as opposed to where the client computer thought it should be. Usually you'd smooth out the difference (so-called "interpolation") so the effect won't be jarring.

For things that require being in order, events are preferable as they can be queued to clients in the proper order. Like chat messages for example. You wouldn't want it that you're hearing conversations backwards (e.g. see someone's answer before the question)!

Also stuff that don't need to be sent every so and so seconds, are preferable as events. Like an event where you accept a quest, or pick something up to put in your inventory.

Disclaimer: I'm no expert. Feel free to correct me if I'm wrong on anything.
> 1 votes

# Answer
The tribes and Q3 models are very similar, the core idea is exactly the same (unreliable delta sync), they only differ in implementation quite a bit.
> 0 votes

---
Tags: architecture, networking, quake3
---


# Question
Title: Winform + XNA (Microsoft Example) - Issues with Drawing Texture2D
Before I get started I would just like to say that I have been using the Microsoft Winform + Xna examples found here:

WinForms Series 1: Graphics Device

I think I somewhat understand how its working however I'm running into one major problem. I'm trying to draw a Texture2D image to the spriteFontControl's spriteBatch parameter, which is an object of the XNA SpriteBatch class, and when I do I get this red "X" on a white box that fills the entire spriteFontControl area. This is a screen shot of what it looks like:

As for the coding that I added to do this is pretty simple. I used the content parameter from the spriteFontControl to load the box.jpg image into the program. Then just called the following code inside the Draw() method for the spriteFontControl:

```
spriteBatch.Begin();
spriteBatch.Draw(box, new Vector2(0,0),Color.Black);
spriteBatch.End();

```

If anyone could please offer some help as to how to draw Texture2D images in the Winform + XNA example then that would be most helpful. I heard that it was made so that you could draw it just like you would in XNA but I think I'm still missing something.

Thanks in advance.

P.S. This is the code from the Draw() method of the spriteFontControl:

```
    const string message = "Hello, World!\n" +
                               "\n" +
                               "I'm an XNA Framework GraphicsDevice,\n" +
                               "running inside a WinForms application.\n" +
                               "\n" +
                               "This text is drawn using SpriteBatch,\n" +
                               "with a SpriteFont that was loaded\n" +
                               "through the ContentManager.\n" +
                               "\n" +
                               "The pane to my right contains a\n" +
                               "spinning 3D triangle.";

    GraphicsDevice.Clear(Color.CornflowerBlue);

    spriteBatch.Begin();
    spriteBatch.Draw(box, new Vector2(15, 15), Color.Black);
    spriteBatch.DrawString(font, message, new Vector2(23, 23), Color.White);
    spriteBatch.End();

```

# Answer
> 0 votes
you are throwing an exception...

you should ensure that "spritebatch" and "box" variables are not null.

# Answer
> 0 votes
Instead of creating a game in a form, create a form in a game.

In your initialize method:

```
using System.Windows.Forms;

/* ... other methods **/

protected override void Initialize()
{
    Application.EnableVisualStyles();
    Form form = (Form)Form.FromHandle(this.Window.Handle);
}

```

then simply add Controls to that form like:

```
Panel panel = new Panel() { Width = 200, Dock = DockStyle.Right };
form.Controls.Add(panel);

```

this way, you should have no problem loading anything without problems. It's simply a game that has controls. Much easier than the other way around, because you get no "game loop".

**EDIT:** You need to create a method that updates the viewport according to the controls when the window is resized (if it ever is) otherwise it will need to be run at least once. Otherwise if you create controls on the form that takes 50% of the viewport, the viewport will still be 100% and positioned wrongly. So, a good idea is to have each control have a "Dock" then you can increase X if it's docked to the left, decrease Width if it's docked to the right, increase Y if it's docked at the top and decrease height if it's docked to the bottom.

I've used this (created an automatic method that gets called everytime the window is resized and when it's initialized) and it sets the viewport correctly and works just fine.

I've only encountered errors while trying to get a Game work in a Windows Form. Much easier the other way around.

---
Tags: xna, c#, windows-forms
---


# Question
Title: Implementing vector based movement in a 2d environment
Good evening.

I apologize if the title is a bit vague, I really could not come up with anything better. I am currently reading a book called the nature of code and as a side project, I am working on a small 2d game in javascript.

One of the core concepts of this book states that a game object should incorporate three vectors, acceleration, velocity and location, where only acceleration is directly modified by the player. This translates to the following code;

```
    acceleration.add(0, 0.001);
    velocity.add(acceleration);
    location.add(velocity);

```

This works perfectly fine and so does the the .sub() method, when I want to move backwards. However, this requires two functions. Also, all vectors have to be positive. This is quite a pain because I now have to decide whether the applied vector is a positive or a negative one, thus requiring methods like applyForceNeg(vec) and applyForcePos(vec). I'd much rather have one method where I could pass any vector.

I have pasted some of the code here.

How would I implement this *without turning the code into a complete mess*?

Any help would be much appreciated.

EDIT:

I figured out what actually caused all this;

As you can see here, I initially wrote the if statement so that upon every run, acceleration gets incremented by 0.001. Then acceleration gets added to velocity, which in turn gets added to location. The problem was that I did not set acceleration back to zero. So in the first run, acceleration is set to 0.001, so is velocity and location. However, in the second run, acceleration increases by 0.001, yielding a total value of 0.002 which in turn gets added to velocity and location. Therefore we now have acceleration = 0.002, velocity = 0.003 and location = 0.003. After the third run, velocity and location are at 0.006 while acceleration is at 0.003.

Now, when I set acceleration to zero, it reduces the problem. Only if I also reset velocity, the problem is gone. However, I doubt this is the right way to do it...

# Answer
> 1 votes
First, you shouldn't be hard-coding numbers like your acceleration. Numbers like these, which need to be fine tuned, should be variables that can be easily tweaked, either in one-place or dynamically using a slider or somesuch during testing.

Second, from what I understand (of your comment to MagiSun), your problem with the acceleration giving you odd behavior is that your acceleration value is far too small.

Even at 60 updates per second, you're accelerating at 0.06/s, and unless your velocities and positions are also in similarly small measurements (which I assume they aren't by your description of the resultant behavior), this will result in a very slow deceleration.

If you're keeping the "Down" key pressed the entire time, by the time you reverse course (and travel in negative velocity), your negative acceleration will be very noticeable, giving you the "uncontrollable speeds".

Try raising your acceleration value, but take note that you might also want to increment acceleration at a slower rate than your updates-per-second/fps. Another concern is that you might want a maximum acceleration, even if it might be unrealistic, simply for the sake of a good "feel".

# Answer
> 1 votes
In regards to this comment by OP:

> The problem is the resulting behavior, where the object continues to move up for example, even if the down key is pressed. It eventually changes direction but by then it's at nearly uncontrollable speeds.

That is how velocity and acceleration work. You are simply providing the user with acceleration increments that are too large. Try reducing your acceleration increments to 1/4 of their present value, and report the results.

Because distance travelled varies as the square of applied acceleration, rather subtle changes in acceleration can affect the agent more than might be intuitively expected. Also check my answer to this post on simple equations of motion with constant acceleration.

**Update:**
Your turns should look like this, where the player can only set a = .001, or 0.000 or -0.001:

```
    a    v    l
 0.001 .001 .001
 0.001 .002 .003
 0.001 .003 .006
 0.001 .004 .010
 0.001 .005 .015 now motor turned off, so a = 0.000
 0.000 .005 .020
 0.000 .005 .025 now retro-rockets fired (ie braking applied)
-0.001 .004 .029
-0.001 .003 .032
-0.001 .002 .034
-0.001 .001 .035
-0.001 .000 .036 now motor turned off again
 0.000 .000 .036 etc.

```

When you increase the acceleration by .001 each time, you are in fact using **constant jerk**, as I suspected earlier.

# Answer
> 0 votes
Have you thought about adding negative velocity and using a ternary statement to decide what to add?

```
if(keys.up != keys.down) {
  acceleration.add(0, keys.up ? 0.001 : -0.001);
  velocity.add(acceleration);
  location.add(velocity);
}

```

EDIT: What platform are you using? I've never seen a vector class that couldn't go negative.

# Answer
> 0 votes
So, the .add method doesn't take negative numbers?

If it does, it's just a matter of adding a negative acceleration to velocity. Otherwise, you really have no choice but to check.

EDIT: I think I understand your problem now. Vectors can't be negative correct? If so, you'd probably be better off having acceleration be two scalars. This way, I assume they can be negative and you can just add each component.

# Answer
> 0 votes
I see several things wrong with your code. However, before trying to list them here, let me just show how I would rewrite your main loop:

```
// reset acceleration to default value
acceleration.set(0, 0);  // or, equivalently, acceleration.mult(0);

// adjust acceleration based on keys pressed
if (keys.up) {
    acceleration.add(0, 0.001);
}
if (keys.down) {
    acceleration.sub(0, 0.001);
}

// move ship according to Newton's laws
velocity.add(acceleration);
location.add(velocity);

ship.move(location.getX(), location.getY());

```

The main differences between this and your code are that:

1. The acceleration is not retained between update steps, but is reset to its default value (which I've assumed to be zero, but you could e.g. include gravity in that value) on every iteration. This default value is then modified based on the player's controls.
2. The velocity and location of the ship are updated on every iteration, not just when the player presses a key: in the absence of player interaction, the ship should continue on its inertial trajectory. Of course, since the default acceleration is zero, the velocity only changes if the player presses some keys (and thus the inertial trajectory is a straight line), but that would change if you included gravity.

Note that I've assumed that you want the ship to accelerate upwards when the up key is pressed and downwards if the down key is pressed, regardless of its orientation. Depending on what kind of game you're making, you may instead want to add or subtract the ship's heading vector (normalized and scaled by a constant) instead of the fixed vector `(0, 0.001)` to the acceleration.

---

Also, there are a couple of improvements you could make to you physics simulation (i.e. the lines `velocity.add(acceleration);` and `location.add(velocity);`). One is to account for the fact that the velocity has changed during the timestep in your location update, by taking the average of the old and new velocity:

```
// move ship according to Newton's laws...
velocity.add(acceleration);
location.add(velocity);
// ...including the correction for the gradual change in velocity
acceleration.mult(0.5);
location.sub(acceleration);

```

This makes the trajectories physically exact (under constant acceleration), and, in particular, ensures that, with appropriate scaling, they won't be affected by changes in the simulation time step. However, to really make use of this feature, you need to actually involve the timestep in the calculations. This would be easiest to do if your vector class included a multiply-and-add method:

```
// move ship according to Newton's laws...
velocity.muladd(acceleration, timestep);  // velocity += acceleration * timestep
location.muladd(velocity, timestep);      // location += velocity * timestep
// ...including the correction for the gradual change in velocity
location.muladd(acceleration, -timestep*timestep/2);

```

If not, you'll just have to do it by hand, e.g. like this:

```
// velocity += acceleration * timestep
acceleration.mult(timestep);
velocity.add(acceleration);

// location += (velocity - 0.5 * acceleration * timestep) * timestep
var displacement = velocity.clone();
acceleration.mult(0.5);
displacement.sub(acceleration);
displacement.mult(timestep);
location.add(displacement);

```

Note that this will mess up the acceleration vector (by multiplying it with 0.5 * timestep²), so you shouldn't use it for anything after this.

---
Tags: 2d, javascript, vector
---


title: Licensing of programs my Problem

text:
# Question
Title: Licensing of programs my Problem
I am to create a game / program but my problem is about licensing which are:

1. My IDE codeblock & Dev-C++ does **NOT** allow my created program to be release as closed-source.
2. I want to create a commercial/proprietary Program or Game so I can sell it.
3. What IDEs, libraries(GUI, Physics, etc) you can recommend to me based on my problem? Can you recommend websites which explains in layman terms the different kinds of licenses.
4. Also does LGPL license allow me this?
5. Comment any further information you want to share with me.

\*You can **IGNORE** question #3, if it's not appropriate in this site.

Thank you

# Answer
You are mistaken. Software development tools licensed under the GNU GPL can be used to create software under other licenses, even proprietary ones. The official FAQ about the GNU GPL reads:

> **Question:** Can I use GPL-covered editors to develop non-free programs? Can I use GPL-covered tools to compile them?
>
> **Answer:** Yes, because the copyright on the editors and tools does not cover the code you write. Using them does not place any restrictions, legally, on the license you use for your code.

But there are problems when you use GNU GPL libraries, because these must not be used for programs under different licenses. Fortunately the libstdc++ (The C++ standard library which ships with Code::Blocks and Dev-C++) is not licensed under the GPL but under the LGPL. That means you may link programs against it and license them under any license you want (as long as you aren't modifying the libstdc++ itself, but even when you would be crazy enough to do that, you would only have to license your modified library under the LGPL, not the game you made with it).
> 6 votes

---
Tags: licensing, ide
---


# Question
Title: Are there any open-source Direct X code-bases that I can look at to learn from as a beginning Direct X and graphics programming student?
I'm a third-year university student and I've recently begun studying Direct X 11. Mostly I've been following the samples from the SDK and reading a lot out of the MSDN. Although I have a decent conceptualization of the pipeline in general, I have no exposure to how various steps are broken down organizationally in an actual large production code-base. I understand that finding an open-sourced Direct X code-base, preferably version 11, is probably a lot to ask, considering it's only supported on a closed-source platform, but I was hoping I might get lucky.

Cheers, Joseph

# Answer
There are plenty of open source rendering engines that implement direct3d as part of their pipeline. Whether or not it is directx 11 isn't terrible significant, as the rendering architecture overall is what is important, not the specific API calls. Irrlicht and Ogre are just a couple of the rendering engines you can look at. The API is insignificant from a learning perspective, in fact, you may get more out of it by referencing an implementation that uses one API, while actually writing your own using an alternate.
> 0 votes

---
Tags: directx, directx11
---


# Question
Title: Heightmap implementation in javascript question, a 2D water heightmap
I have a **height map function** from GPU Gems 2 Chapter 18, where they're generating a set of B/W pixels from this equation:  *H(x,y,t) = Σi=0N h ( Axi x + Bxi, Ayi y + Byi, Ati x + Bti )*

The article suggests using 4 height maps to generate the final height map, so that's N = 4. I understand it's using 3 equations of a line to describe the 2D plotting of a 1D B/W pixel. So, I have to iterate through a set of points, say from (0,0) to (100,100):

* \[ x0 \- x100**,** y0 \- y100**,**, t0 \- t100 \]

So that's a "for loop" of 100 x 100 x 100 and with the 4 times that's 100 x 100 x 100 x 4 loops, the number of A's,B's and T's, i.e. the data I would need to provide would be:

* \[ A0x**,** A0y**,** A0t \] , \[ B0x**,** B0y**,** B0t \]
* \[ A1x**,** A1y**,** A1t \] , \[ B1x**,** B1y**,** B1t \]
* \[ A2x**,** A2y**,** A2t \] , \[ B2x**,** B2y**,** B2t \]
* \[ A3x**,** A3y**,** A3t \] , \[ B3x**,** B3y**,** B3t \]

My question is, is this correct? Are my for loops correct? Did I interpret the equation OK so that its just 4 for loops of 4x100x100x100 and the 24 pieces of data are all I need to generate this map?

I'm implementing this in javascript, using a plot pixel function.

Edit: I have another problem, how do I output the data? If I have say a 100x100 pixel height map, how do I "keep" only the data that applies to that area, do I just "throw away" the rest of the data in a conditional if statement that only does within that range?

Edit: also it was my understanding that x and y were the plots for the u and v of the height map and t was that alpha channel? I think I'm misunderstanding that part if the equation

# Answer
> 1 votes
Your understanding of the article seems correct, it is explaining a process of superimposing 4 separate height maps onto each other to represent surface displacement with water. You could write it as four separate loops if you wanted, but why not condense it into a single loop that accesses each of the four height maps each iteration?

---
Tags: mathematics, heightmap
---


title: State propagation in modern OpenGL

text:
# Question
Title: State propagation in modern OpenGL
When last I dabbled in game development, I managed my geometry in a tree. Every node would call the render method on it's children, prior to resetting it's transformations, thus allowing the transforms to propagate. (The typical illustration of how this works is a radar dish spinning, on top of a vehicle that moves. The radar is a child of a autorotator node, which is a child of the vehicle.)

Now I'm at it again, and I learn that transformations are supposed to be done with shaders. Fair enough. What I can't wrap my head around is how to inherit transformations between objects.

Perhaps I´m over thinking it. Is it just a matter of passing the M, V and P matrices down the tree yourself and multiplying them prior to sending them to the shader?

In any case I'd like to hear how other have dealt with this. There is not much out there on this topic.

# Answer
Model, View and Projection matrices are passed as uniforms to the vertex shader, which uses them to transform vertex coordinates and normals. Typically projection matrix is constant between frames, view matrix is calculated once per frame and model matrix is unique for each object. Model matrix is in world space. This is of course not the only way to do transformations, but I think it's the simplest to understand.

For hierarchical scene graph, objects can have local transformation relative to their parent. As you guessed correctly, the matrices are multiplied on CPU prior passing them to the shader. It's possible to do it similar to the legacy OpenGL by having your own matrix stack and multiplying the matrices in the render function. However it's often better to calculate the world matrices in a separate (also recursive) function and store the results in the objects themself. After that you can render the objects in any order you want, e.g. group them by shader / textures to minimize switching or render all translucent objects after solid ones. Also if you render the scene multiple times per frame e.g. due to reflections, the matrices need to be calculated only once. In addition you can use the world matrices for other purposes such as for physics calculations.
> 2 votes

# Answer
> Perhaps I´m over thinking it.

Yes, you are. Transformation being done in shaders is meant to be literal. "Transformation" in this case being the application of some transform to the various per-vertex attributes. Where that *particular* transformation comes from is generally irrelevant to the shader. It is given a transformation, and it applies it to the vertex data for the object.
> 3 votes

---
Tags: opengl, shaders, scene, graph
---


# Question
Title: How can I place my Enchant.js game into a DIV in a fully-designed web site?
Following the Enchant.js tutorial I cannot find a way to define the place the game is rendered in the page. It either takes the maximum possible area or limits itself to the given size (using game.scale = 1).

# Answer
There are two possible ways to do this.

The "fast" hack is to call your game's html page from an iframe. This is not recommended because of the iframe implications and cross-browser differences regarding attributes and, more important, you **will not be able to capture input from keyboard**.

The best way is to create the div and give it the id 'enchant-stage'. It's direct, 100% cross-browser compliant and lets you capture keyboard input.

```
<div id="enchant-stage"></div>

```
> 6 votes

---
Tags: javascript, html5, enchant.js
---


# Question
Title: Books on layout and space sequencing in game design
I'm currently looking into level design books. So far I've read two, *The How's And Why's of Level Design* and *the Ultimate Level Design Guide*.

While both were useful they did not discuss layout and space sequencing as much as I was looking for. I'm looking for stuff like this:

I couldn't find books that pertain to this specific subject. Do you happen to know any?

# Answer
> 1 votes
The word you're looking for is "Pacing" for space sequencing.

I don't think that you're going to find much more than blogs by designers and the occasional post mortem with a design section.

Have you tried looking up syllabuses that include environment and level design to see what their reading list looks like?

However, 100% of the designers I know learned their patterns from tearing apart and studying existing games. When someone asks "how do I become a designer" and all the answers come back "play games" they really mean "play games and dissect everything they do."

To summarize: play a lot of games, find if the designer/company has a development blog.

And check this out: David Perry's Design Challenge

---
Tags: 3d, level-design, books
---


# Question
Title: Pygame: circular motion with Bresenham's algorithm
I'm trying to figure out a way to move an object in a circular path. I read about Bresenham's circle algorithm, but all the codes available online draw an entire circle.

For my game, I want it so that when the ball enters a region, it'll begin to move in a circular path and when it leaves the region, it'll go back into moving in a straight path from its tangential velocity.

As of right now, I'm trying to figure out the algorithm to include in my game loop. I have the object updating its position every iteration. I use Bresenham's algorithm to decide whether to go right or go diagonal. I want it to draw the upper left portion of a circle

This is what I get:

Here is my code at the moment:

```
# Drawing Curves with Midpt Circle Theorem
import pygame, sys, random, math
from pygame.locals import *

class Game(object):
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((400,400))

        self.screen.fill((255, 255, 255))
        self.jom = pygame.Rect(100,100,2,2)

    def run(self):

        running = True

        while running:
            for event in pygame.event.get():
                if event.type == QUIT:
                    running = False
                elif event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        running = False

            pygame.draw.rect(self.screen, (0,0,0), self.jom)

            ## Center of Curvature
            centercurv = (104,103)

            ## Update Position
                ## eqn of circle (x-104)**2 + (y-103)**2 - r**2 = 0, r == 5
            #circleeqn = (self.jom.x-centercurv[0])**2 + (self.jom.y-centercurv[1])**2
            #goright = (self.jom.x+1
            eR = -2*self.jom.x+2*centercurv[0]+1
            eD1 = -2*self.jom.x - 2*self.jom.y + 2*centercurv[0] + 2*centercurv[1] + 2
            print(eR,eD1)
            if abs(eR)-abs(eD1) > 0:
                #self.jom.x += 2
                self.jom.y -= 1
                print('1')
            elif abs(eR)-abs(eD1) < 0:
                #self.jom.x+=2
                print('2')
            else:
                if eR < 0 and eD1 < 0:
                    #self.jom.x+=2
                    print('3')
                elif eR > 0 and eD1 > 0:
                    self.jom.y -= 1
                    print('4')
            self.jom.x += 1

            pygame.display.flip()

        print('Quitting')
        pygame.quit()
        sys.exit()

if __name__ == '__main__':
game = Game()
game.run()

```

# Answer
Bresenham's algorithm is specifically built to draw circles with fixed-point mathematics; that is, to *rasterize* circles. For what you're doing you're almost certainly better off with a much more abstract representation of your circular motion — that is, you want to keep track of your character's *angular velocity* and to simply move it with constant angular velocity about the center point of the circle. This decouples the *representation* of your ball's physical state (position and velocity) from the *display* of that state, which is a Very Good Idea. Abstractly, this would look something like:

```
while (not in containing region) {
  ball.Position += deltaTime*ball.Velocity;
}
if ( entering containing region ) {
  Vector RelativePosition = ball.Position - region.CircleCenter;
  float AngularVelocity = length(ball.Velocity)/length(RelativePosition);
}
while ( in containing region ) {
  float s = sin(AngularVelocity*deltaTime);
  float c = cos(AngularVelocity*deltaTime);
  Vector newRelativePos;
  newRelativePos.x = c*ball.RelativePosition.x - s*ball.RelativePosition.y;
  newRelativePos.y = s*ball.RelativePosition.x + c*ball.RelativePosition.y;
  RelativePosition = newRelativePos;
  ball.Position = region.CircleCenter + RelativePosition;
}
if ( leaving containing region ) {
  Vector normalizedPosition = RelativePosition.normalize();
  // linear velocity is orthogonal to normalized position
  ball.Velocity.x = -AngularVelocity*normalizedPosition.y;
  ball.Velocity.y = AngularVelocity*normalizedPosition.x;
}

```

This essentially says 'while the ball is in free motion, just update by the usual Pnew = Pold+V\*dt rule, but when the ball is contained, update the position using constant angular velocity by saying θnew = θold+ω\*dt and then P = Pcenter+(RelativeP rotated by θ), where RelativeP is Pentry-Pcenter — the relative position on entry to the volume.
> 3 votes

---
Tags: algorithm, game-mechanics, python, pygame
---


title: Job finding algorithm

text:
# Question
Title: Job finding algorithm
My issue seems simple enough to me, but I can't break it down the the bare essentials to be able to program it into my game.

First of all different professions requires different skills, these skills are contained inside the class `Person`. I have a `world map` where I can ask for all empty buildings, thereby finding all available jobs.

With this information I want to calculate from some weights that the player can modify on each profession to how important it is to be fill a certain position.

so my current approach would be something like this pseudo code:

```
    Job findJob(wm : WorldMap) {
      Queue priority <- empty;
      for each building {
        queue.add(skill * need);
      }
      return prority.max();
    }

```

Does that sound inefficient stupid or do you see any special cases that you think I should be aware of?

# Answer
1. Inefficient is fine if it's not using much cpu relative to other parts of your game. :) Start with the simple implementation and then go back and improve it later, only if needed.
2. Your pseudocode uses a queue but you don't really need the entire queue; you only need the max.
3. If you have lots of workers and lots of buildings, with your algorithm you may end up with lots of workers ending up in the same building. If you're trying to find the best assignment where no building gets more than one worker, you may find the Munkres-Kuhn algorithm to be useful. However I'd advise starting with the simplest algorithm (what you posted) first, and Munkres-Kuhn is not the simplest.
> 3 votes

# Answer
You might also want to take a look in other algorithms described in maximum weighted matching in bi-partite graphs.

In your case, all the people looking for the job should be placed in same group, and all the jobs should be placed in the other. Obviously there is no edge between vertices in the same group, and for person-job edge, it's weight would be equal to how much that person is needed for that job `weight(Person,Job) = person.skill * job.need`
> 2 votes

---
Tags: algorithm, search
---


title: Analysis of Mario game Physics

text:
# Question
Title: Analysis of Mario game Physics
I know there's a breakdown of Sonic the Hedgehog physics found here, and I was wondering, does there exist a breakdown of any of the Mario games? Something similar to this but for Mario is what I'm interested in!

# Answer
> 16 votes
found a detailed breakdown of Mario Physics:

http://forums.mfgg.net/viewtopic.php?p=346301 https://web.archive.org/web/20130807122227/http://i276.photobucket.com/albums/kk21/jdaster64/smb\_playerphysics.png

# Answer
> 7 votes
I don't know about a breakdown of the physics, but there are commented disassemblies floating around the internet. Romhacking.net, nesdev.parodius.com, Acmlm Board2, SMWCentral and their respective forums would probably be the best places to get that kind of information. The document sections of those sites have enough information to compile your own guide.

# Answer
> 6 votes
Well, I know this question is kind of old but since I found this site was higher ranked in google than the actual answer I thought I'd post a link to this description of the basic falling physics of multiple Mario games

# Answer
> 2 votes
I was told by Claude Comair (Founder of Digipen sponsored by Nintendo ) that basically the senior programmer and senior game designer sat down and adjusted magic numbers until the game designer was happy.

# Answer
> 2 votes
Gamasutra did a feature on the physics of Super Mario Galaxy some years back ... probably not what you're after if you're more interested in the 2d versions. Link here: http://www.gamasutra.com/view/feature/3593/games\_demystified\_super\_mario\_.php

# Answer
> 1 votes
There is a Flash clone of Super Mario called "Super Mario crossover", whos developer put a lot of effort into cloning the actual physics. Flash code should be easily reverse engineerable, so you could get the actual physics code (or maybe just ask the developer).

---
Tags: physics
---


# Question
Title: Using GraphicsDevice.Viewport.Project with a small farPlaneDistance
I am using "GraphicsDevice.Viewport.Project()" to create a "3D" waypoint system like so;

I have a farPlaneDistance of 5000 in my camera;

```
objProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), flAspectRatio, 1.0f, 5000.0f);

```

Obviously when the waypoint is farther than 5000, it cant find it within the viewport and bugs out. Is there another way to display waypoints on screen (within a 3D world) without using GraphicsDevice.Viewport.Project()?

Or, is increasing my z buffer out to 100,000 not that big of an issue (i find this hard to believe)?

Learning as I go, Thanks in advance!

Linuxx

# Answer
> 2 votes
The problem with a large farPlaneDistance is floating point errors. This can cause things to draw in the wrong order because multiple verts are getting are falling withing the values that a float can re-present.

I recommend doing something like the below to lock the object a certain distance from the camera if it is too far away.

```
var location = Vector3.Subtract(object.Vector3, camera.Vector3);
if (location.length > 5000) {
    location.normalize();
    location.Multiply(5000)
    object.Vector3 = Vector3.Addition(camera.Vector3 + location);
}

```

Another common solution is to use point sprites but they are not supported in XNA 4.0.

---
Tags: xna
---


title: How to achieve realistic engine sound?

text:
# Question
Title: How to achieve realistic engine sound?
I am aiming to achieve a believable engine sound for a car. The vehicles are simplified versions of their real-world counterparts, with simpler steering behaviors and acceleration, etc.

This seems like a fairly complicated topic to me, which I must not take lightly. So, how would I find/capture sounds of a car's engine, properly segmented in a way they can be used inside a game?

Also, what kind of format do I need the sound files in? How do I separate the sounds in multiple files so they can be used by such an algorithm?

I'm not sure this is even the way to go about it, but my wild guess would be to create an algorithm that would take as input the car's shift, current velocity and other engine parameters and output the correct sound at the correct time. How would you do such a thing?

# Answer
> -2 votes
Maybe you could record the sound instead of buying a stock sound from a website. You could possibly spend less money that way.

---
Tags: audio, car
---


title: Solidworks (3D model) import help

text:
# Question
Title: Solidworks (3D model) import help
Hey guys, I'm not sure if this is the right place to ask, but I'm also not sure where else to ask. I have a 3D model in Solidworks that is imported from a STL file. Solidworks imports the file multiple triangular faces and as either a solid, or a surface. See pic below:

What I need to do is take the model and have it be hollow but with a thickness, not that big. Also it would help to have the surface be one smooth surface since I will be imported it to another program, ADINA. Any ideas or suggestions?

# Answer
> 2 votes
That's a nice teapot :)

Not sure about details of Solidworks, but you could go about it like:

1. Duplicate the mesh
2. Scale down the copy
3. Subtract the space of the smaller model from the larger model

If you can't figure out #3 do a search for 'solidworks boolean operations'.

I'd probably optimize the model before I subtracted it too, as scaling down can lead to too much detail in some areas.

You might find more specific help on a dedicated 3d modelling or solidworks forum, here's one I found on google.

# Answer
> 1 votes
I don't know what sort of interface you have available, but my guess is that you want to...

Copy all of the faces and vertices. Flip the copied faces' normals. Move the copied verts (and/or the original verts) along their normals, as far as you need to get the thickness that you desire.

Otherwise I can't think of what you mean by "thickness" and "hollow," as presumably this triangle mesh only represents the object's surface and there are no vertices/edges/faces in the interior.

# Answer
> 1 votes
If you open the object in a proper polygonal editor, you can *extrude faces* by a negative amount to turn it hollow. The main idea is to have a smaller copy sitting inside the larger and have all faces reversed. You could even do it by hand, though that is impractically tedious.

You can try Blender, Cheetah3D, Hexagon, Wings3D, Silo, Nvil, 3ds Max, or Maya.

***Warning**: The less sphere-like the original shape is, the thinner the walls have to be without generating a malformed object.*

---
Tags: 3d, models
---


# Question
Title: XNA's SetData in a SharpDX Texture2D object in DirectX 11?
I'm trying to load a texture given a swap chain, and then populate that texture with data. I already have some bitmap data (although not sure if it is in the correct format) that I want to populate the texture with.

However, XNA's `SetData` method of the `Texture2D` object is obviously not present in SharpDX. What do I do to populate my texture with data? I load the texture using the following code.

```
var texture = Resource.FromSwapChain<Texture2D>(swapChain, 0);

```

# Answer
Use Device.UpdateSubresource (requires texture to be declared with Usage.Default) or Map/UnMap (requires texture to be declared Usage.Dynamic).In the case of the swapchain, I guess that only UpdateSubresource will work.

Keep in mind that you are refering to the low level Direct3D11 API in SharpDX, so there can't be any high level methods like "SetData". If you want to have XNA equivalent API, you have to use the Toolkit which is available from the 2.5 dev package. If you want to stick with plain Direct3D11, you will have to dig into all the details about how Direct3D11 is working.
> 2 votes

---
Tags: xna, sharpdx
---


title: Using Unity3D from within Eclipse

text:
# Question
Title: Using Unity3D from within Eclipse
Is it possible to use Unity3D from within Eclipse? I've seen that I can import a Unity3D project into Eclipse, but I cannot seem to be able to access classes such as Terrain or Ray. I don't know if that's because I haven't imported the correct libraries or if that's a limitation and that data can only be accessed by methods within Unity3D. I am designing an Android game within Eclipse and would prefer to use Eclipse than Unity3D, even if that means my game will only be available for Android.

The only real reason I'm using Unity3d is for use of the 3D terrain and to hopefully help in getting the data, such as slope, terrain type, collisions, etc.

# Answer
Unity is an engine, Eclipse is an IDE. They're fundamentally different things. In particular, Unity expects you to write most of your code in their scripting languages.

The exception to that rule that Unity provides is their plugin architecture. It's supported in Unity Pro. You can find more documentation on that here: http://docs.unity3d.com/Documentation/Manual/PluginsForAndroid.html but it's kind of backwards from what you're thinking. You'd be using Eclipse-written plugins from within Unity.
> 2 votes

---
Tags: android, unity, eclipse
---