# Question
Title: How does one optimize an HTML5 Canvas and JavaScript web application for Mobile Safari?
I've created an HTML5 Canvas and JS game that runs great on a desktop or laptop in Chrome (30fps), but on mobile Safari I only get around 8 fps. Are there any simple tips or tricks to increase the framerate?

# Answer
Unfortunately, the answer is to draw less. I've found the bottleneck with canvas based applications (on any platform, really) is the time it takes to actually draw pixels.

Here are some things to try:

1. Use several canvas layers. Draw your background to one layer while drawing your objects to another layer (absolutely positioned on top of the background layer). (Note: I haven't tried this on mobile safari, but it can help on other platforms)
2. Only redraw sprites that have changed. This is tricky but definitely increases performance. The idea is to store whether or not a sprite needs to be redrawn and redraw only sprites that need it along with the background behind them. (This also needs to cascade to other objects that sprite might be overlapping.)

The thing with developing on Chrome is that a) its JavaScript engine (V8) is fast as hell and b) the newest versions (7,8,9) all have some GPU acceleration when it comes to canvas rendering. That coupled with the fact that mobile hardware just isn't as powerful as your desktop/laptop means that it'll be really difficult to get anywhere near the same performance on mobile safari.

I think, for the time being, the best approach might be to target your game at mobile safari from the get go and try and build a game that's not as redraw intensive.
> 14 votes

# Answer
This is a bit of a long shot, but can your game operate on DIV sprites with CSS transforms instead? I say this because I'm getting some wonderful performance with moving things around on iOS devices with CSS transforms and transitions.

These appear to be properly hardware accelerated, with the bizarre caveat that you must use the 3D form for the transforms (i.e. translate3D, rather than translate) for the acceleration to kick in. It's really really buttery smooth, and the iOS browser implementation supports the form where you just set a 16 element float matrix directly, which is very convenient for me.

I'm so impressed with how smooth it ends up being, that I've been meaning to try a simple game project written this way.
> 4 votes

# Answer
In case of line drawing, combine as many lineTo commands before calling stroke.

This and some other tips: http://dt.deviantart.com/blog/38471599/
> 4 votes

# Answer
everything @Gosub said plus:

look at whatever math you're doing, see if there's anyway to use more efficient algorithms.

use smaller images. try making the dimensions of the image powers of 2

see if you can get rid of alpha blending on the canvas or dont use CSS opacity property.

please post back your results. would be interesting to know what things helped most.
> 3 votes

# Answer
I'd hate to add an answer to an old thread - but I'm surprised nobody mentioned this.

When you're writing your first games, just write them how you would expect them to work performance wise. The techniques above are good starting points to keeping performance high - but the real trick is the profiler. If you profile your application in Chrome or Firefox (hint: use lots of methods so you can see exact bottlenecks; so you don't have to move stuff later - you should be doing this anyway.), you get the added benefit of seeing exact timing results. In my case, I saw constantly redrawing the background took 80% of the browser time. After I moved that out of the way, I saw other calls taking up 40% and more respectively. After an hour or two, I saw a substantial FPS gain.
> 3 votes

# Answer
I would also like to hear from your results. I've been trying to do the same thing. I found that doing lots of math is fine but soon as you put a canvas in there its goes mental and frame rates fall.

I had an foreground overlay that displayed effects. It was a very high quality image but the alpha stuff slowed it down so much that I dropped it completely in return for more frames per second.

Another thing I did was to use PHP to work out some of the heavy maths. I had large datasets but rather than get JavaScript to compute and show the data, i decided to let PHP do the work and let JavaScript show results. This didn't save much time because JavaScript is "sehr gut " with maths.

I take it your whole site is in HTML5 so try playing with the background worker.

Hope I helped and please share your results.
> 1 votes

---
Tags: optimization, javascript, html5, mobile
---


# Question
Title: Android OpenGL textures sometimes corrupted
Just trying to get some sprites (textured squares) to draw from a texture atlas and 50% of the time after the application is first launched/ reorientated/ brought from sleep these various graphical glitches seem to occur.

Here is what is supposed to be displayed.
https://i.stack.imgur.com/o9Mu7.jpg

Here is an example of what goes wrong (it varies)
https://i.stack.imgur.com/oIX6w.jpg

Here is the code for my Renderer

```
package com.krazy.androidopengl;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.GLUtils;
import android.opengl.Matrix;
import android.os.SystemClock;
import android.util.Log;

public class GameRenderer implements GLSurfaceView.Renderer
{
    public int spriteWidth, spriteHeight;
    private int spriteRows,spriteColumns;

public int width,height;

private Bitmap atlas =null;

private float mScale;

private float[] spritePositionData = new float[12];
private float[] cubeTextureCoordinateData = new float[12];

/** Used for debug logs. */
private static final String TAG = "LessonFourRenderer";

private final Context mActivityContext;

/**
 * Store the model matrix. This matrix is used to move models from object space (where each model can be thought
 * of being located at the center of the universe) to world space.
 */
private float[] mModelMatrix = new float[16];

/**
 * Store the view matrix. This can be thought of as our camera. This matrix transforms world space to eye space;
 * it positions things relative to our eye.
 */
private float[] mViewMatrix = new float[16];

/** Store the projection matrix. This is used to project the scene onto a 2D viewport. */
private float[] mProjectionMatrix = new float[16];

/** Allocate storage for the final combined matrix. This will be passed into the shader program. */
private float[] mMVPMatrix = new float[16];

/** Store our model data in a float buffer. */
private FloatBuffer mCubePositions;
private FloatBuffer mCubeTextureCoordinates;

/** This will be used to pass in the transformation matrix. */
private int mMVPMatrixHandle;

/** This will be used to pass in the modelview matrix. */
private int mMVMatrixHandle;

/** This will be used to pass in the texture. */
private int mTextureUniformHandle;

/** This will be used to pass in model position information. */
private int mPositionHandle;

/** This will be used to pass in model texture coordinate information. */
private int mTextureCoordinateHandle;

/** How many bytes per float. */
private final int mBytesPerFloat = 4;

/** Size of the position data in elements. */
private final int mPositionDataSize = 3;

/** Size of the texture coordinate data in elements. */
private final int mTextureCoordinateDataSize = 2;

/** This is a handle to our cube shading program. */
private int mProgramHandle;

/** This is a handle to our texture data. */
private int mTextureDataHandle;

/**
 * Initialize the model data.
 */

private Drawer drawer;

public GameRenderer(final Context activityContext, Drawer d)
{
    mActivityContext = activityContext;

    drawer = d;

}

@Override
public void onSurfaceCreated(GL10
        glUnused, EGLConfig config)
{
    Log.v("krazy", "surfaceCreate");
    // Set the background clear color to black.
    GLES20.glClearColor(0.1f, 0.2f, 0.5f, 0.0f);

    // CHECK OUT WHAT THESE DO/ WHY?
    // Use culling to remove back faces.
    GLES20.glEnable(GLES20.GL_CULL_FACE);

    // Enable depth testing
    GLES20.glEnable(GLES20.GL_DEPTH_TEST);

    // Enable texture mapping
    GLES20.glEnable(GLES20.GL_TEXTURE_2D);

    // Position the eye in front of the origin.
    final float eyeX = 0.0f;
    final float eyeY = 0.0f;
    final float eyeZ = -0.5f;

    // Facing negative because of anti clockwise triangles are only visible in that direction
    // We are looking toward the distance
    final float lookX = 0.0f;
    final float lookY = 0.0f;
    final float lookZ = -1.0f;

    // Set our up vector. This is where our head would be pointing were we holding the camera.
    final float upX = 0.0f;
    final float upY = 1.0f;
    final float upZ = 0.0f;

    // Set the view matrix. This matrix can be said to represent the camera position.
    // NOTE: In OpenGL 1, a ModelView matrix is used, which is a combination of a model and
    // view matrix. In OpenGL 2, we can keep track of these matrices separately if we choose.
    Matrix.setLookAtM(mViewMatrix, 0, eyeX, eyeY, eyeZ, lookX, lookY, lookZ, upX, upY, upZ);

    final String vertexShader = getVertexShader();
    final String fragmentShader = getFragmentShader();

    final int vertexShaderHandle = ShaderHelper.compileShader(GLES20.GL_VERTEX_SHADER, vertexShader);
    final int fragmentShaderHandle = ShaderHelper.compileShader(GLES20.GL_FRAGMENT_SHADER, fragmentShader);

    mProgramHandle = ShaderHelper.createAndLinkProgram(vertexShaderHandle, fragmentShaderHandle,
            new String[] {"a_Position",  "a_Color", "a_Normal", "a_TexCoordinate"});

    // Load the texture
        mTextureDataHandle = loadTexture(atlas);

}

@Override
public void onSurfaceChanged(GL10 glUnused, int width, int height)
{
    Log.v("krazy", "surfaceChanged");
    // Set the OpenGL viewport to the same size as the surface.
    GLES20.glViewport(0, 0, width, height);

    this.width = width;
    this.height = height;

    // Create a new perspective projection matrix. The height will stay the same
    // while the width will vary as per aspect ratio.
    final float left = 0f;
    final float right = width;
    final float bottom = 0f;
    final float top = height;
    final float near = 0f;
    final float far = 10.0f;
    Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);

}

public void setAtlas(int w, int h, float scale, Bitmap b)
{
    atlas = b;
    spriteWidth = w;
    spriteHeight = h;
    spriteRows = atlas.getHeight()/spriteHeight;
    spriteColumns = atlas.getWidth()/spriteWidth;
    mScale = scale;

    spritePositionData = spriteCoords(spriteWidth * scale,spriteHeight * scale);

    // Initialize the buffer.
    mCubePositions = ByteBuffer.allocateDirect(spritePositionData.length * mBytesPerFloat)
            .order(ByteOrder.nativeOrder()).asFloatBuffer();
    mCubePositions.put(spritePositionData).position(0);

    // Initialize the texture buffer.
    mCubeTextureCoordinates = ByteBuffer.allocateDirect(12 * mBytesPerFloat)
            .order(ByteOrder.nativeOrder()).asFloatBuffer();
}

@Override
public void onDrawFrame(GL10 glUnused)
{
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);

    // Set our per-vertex lighting program.
    GLES20.glUseProgram(mProgramHandle);

    // Set program handles for drawing.
    mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgramHandle, "u_MVPMatrix");
    mMVMatrixHandle = GLES20.glGetUniformLocation(mProgramHandle, "u_MVMatrix");
    mTextureUniformHandle = GLES20.glGetUniformLocation(mProgramHandle, "u_Texture");
    mPositionHandle = GLES20.glGetAttribLocation(mProgramHandle, "a_Position");
    mTextureCoordinateHandle = GLES20.glGetAttribLocation(mProgramHandle, "a_TexCoordinate");

    // Set the active texture unit to texture unit 0.
    GLES20.glActiveTexture(GLES20.GL_TEXTURE0);

    // Bind the texture to this unit.
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureDataHandle);

    // Tell the texture uniform sampler to use this texture in the shader by binding to texture unit 0.
    GLES20.glUniform1i(mTextureUniformHandle, 0);

    // Pass on drawing to Drawer
    drawer.onDrawFrame(this);
}

/**
 * Draws a cube.
 */
public void drawSprite(float x, float y, int t, float scale)
{
    if(Math.abs(scale-1f) > 0.00001)
    {
        spritePositionData = spriteCoords(spriteWidth * scale,spriteHeight * scale);
        mCubePositions.put(spritePositionData).position(0);
    }
    else
    {
        spritePositionData = spriteCoords(spriteWidth * mScale,spriteHeight * mScale);
        mCubePositions.put(spritePositionData).position(0);
    }
    int row = t/(spriteColumns+1);
    int column = (t-1)%spriteColumns;

    float rowHeight = 1f/spriteRows;
    float columnWidth = 1f/spriteColumns;

    cubeTextureCoordinateData[0] = column*columnWidth;
    cubeTextureCoordinateData[1] = row*rowHeight;
    cubeTextureCoordinateData[2] = column*columnWidth;
    cubeTextureCoordinateData[3] =(row+1)*rowHeight;
    cubeTextureCoordinateData[4] =(column+1)*columnWidth;
    cubeTextureCoordinateData[5] = row*rowHeight;
    cubeTextureCoordinateData[6] =column*columnWidth;
    cubeTextureCoordinateData[7] = (row+1)*rowHeight;
    cubeTextureCoordinateData[8] = (column+1)*columnWidth;
    cubeTextureCoordinateData[9] = (row+1)*rowHeight;
    cubeTextureCoordinateData[10] =(column+1)*columnWidth;
    cubeTextureCoordinateData[11] = row*rowHeight;

    mCubeTextureCoordinates.put(cubeTextureCoordinateData).position(0);

    // Translate/ Rotate
    Matrix.setIdentityM(mModelMatrix, 0);
    Matrix.translateM(mModelMatrix, 0, x, y, -1f);

    // Pass in the position information
    mCubePositions.position(0);
    GLES20.glVertexAttribPointer(mPositionHandle, mPositionDataSize, GLES20.GL_FLOAT, false,
            0, mCubePositions);

    GLES20.glEnableVertexAttribArray(mPositionHandle);

    // Pass in the texture coordinate information
    mCubeTextureCoordinates.position(0);
    GLES20.glVertexAttribPointer(mTextureCoordinateHandle, mTextureCoordinateDataSize, GLES20.GL_FLOAT, false,
            0, mCubeTextureCoordinates);

    GLES20.glEnableVertexAttribArray(mTextureCoordinateHandle);

    // This multiplies the view matrix by the model matrix, and stores the result in the MVP matrix
    // (which currently contains model * view).
    Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);

    // Pass in the modelview matrix.
    GLES20.glUniformMatrix4fv(mMVMatrixHandle, 1, false, mMVPMatrix, 0);

    // This multiplies the modelview matrix by the projection matrix, and stores the result in the MVP matrix
    // (which now contains model * view * projection).
    Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0);

    // Pass in the combined matrix.
    GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0);

    // Draw the cube.
    GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 36);
}

public static int loadTexture(Bitmap bitmap)
{
    final int[] textureHandle = new int[1];

    GLES20.glGenTextures(1, textureHandle, 0);

    if (textureHandle[0] != 0)
    {
        // Bind to the texture in OpenGL
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureHandle[0]);

        // Set filtering
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);

        // Load the bitmap into the bound texture.
        GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);

        // Recycle the bitmap, since its data has been loaded into OpenGL.
        //bitmap.recycle();
    }

    if (textureHandle[0] == 0)
    {
        throw new RuntimeException("Error loading texture.");
    }

    return textureHandle[0];
}

private float[] spriteCoords(float x, float y)
{
    x /= 2;
    y /= 2;
    final float[] spritePositionData =
        {
            // In OpenGL counter-clockwise winding is default. This means that when we look at a triangle,
            // if the points are counter-clockwise we are looking at the "front". If not we are looking at
            // the back. OpenGL has an optimization where all back-facing triangles are culled, since they
            // usually represent the backside of an object and aren't visible anyways.

            -x, y, -1f,
            -x, -y, -1f,
            x, y, -1f,
            -x, -y, -1f,
            x, -y, -1f,
            x, y,-1f,
        };

    return spritePositionData;
}

protected String getVertexShader()
{
    return RawResourceReader.readTextFileFromRawResource(mActivityContext, R.raw.per_pixel_vertex_shader);
}

protected String getFragmentShader()
{
    return RawResourceReader.readTextFileFromRawResource(mActivityContext, R.raw.per_pixel_fragment_shader);
}
}

```

Any help would be greatly appreciated.

# Answer
You may have to reload your textures after waking. On many platforms, GPU resources will be released as needed if the app becomes inactive. I'd check with OpenGL to verify that your handles are still valid when your app is reactivated, or you may need to reset the texture buffer contents.

Note that I haven't played with Android, but I've seen this on Windows with both DirectX and OpenGL, usually when waking or returning from a screen saver. I suspect that behavior is up to the video driver but I'm not sure how the driver model, if any, works on Android.
> 4 votes

# Answer
Found the problem! I was still using GLES20.glDrawArrays(GLES20.GL\_TRIANGLES, 0, 36); which was for cubes, all the error was in the 36 vertices where I was actually only drawing 6.
> 1 votes

---
Tags: android, textures, opengl-es
---


# Question
Title: What algorithm is mostly used to interpolate animations?
Because DCC tools supports very many options, we resample the animation curve splines, but I think it still need to be interpolated. I think there's some de facto standard for this animation interpolation. Or no interpolation. Can I know what's the mostly used interpolation method?

# Answer
The most common form of interpolation is linear interpolation.

However, in the case of animating curve splines, another common one is spline interpolation.
> 3 votes

# Answer
In general, you should have an interpolation function f of any kind that satisfies: f(0) = 0; f(1) = 1; f(x) is continuous for all 0 \< x \< 1 (this can obviously be relaxed if you want jumps); 0 \<= f(x) \<= 1; and f(x) increasing for 0 \< x \< 1 (unless you want goofy effects).

Ones that are computationally easier to do are preferred. For example, one may use f(x) = 3x^2 - 2x^3 instead of f(x) = sin(pi x). Both of these have roughly the same shape over the unit interval.

Once you decide on your interpolation function, then simply compute A * f(x) + B * (1 - f(x)) to interpolate between the two values.
> 2 votes

---
Tags: algorithm, animation, interpolation, standards
---


# Question
Title: Fades in older games. Need some help figuring out how the algorithm was derived
Sorry, this question is a bit esoteric, but I just can't get it out of my head!

I'm looking at the fade algorithm used in the arcade game DoDonPachi (as well as many other older games):

I wrote a python script to pick out a few pixels and track them for the duration of the fade. Here's a representative sample of the results. The first row of each group is the starting color value, while each subsequent row is the difference between the the color value of the current frame and the color value of the previous frame.

```
Starting Value: (132, 66, 189)
Frame 1:    [9, 9, 8]
Frame 2:    [8, 8, 8]
Frame 3:    [8, 8, 8]
Frame 4:    [8, 8, 9]
Frame 5:    [9, 9, 8]
Frame 6:    [8, 8, 8]
Frame 7:    [8, 8, 8]
Frame 8:    [8, 8, 9]
Frame 9:    [9, 0, 8]
Frame 10:   [8, 0, 8]
Frame 11:   [8, 0, 8]
Frame 12:   [8, 0, 9]
Frame 13:   [9, 0, 8]
Frame 14:   [8, 0, 8]
Frame 15:   [8, 0, 8]
Frame 16:   [8, 0, 9]
Frame 17:   [0, 0, 8]
Frame 18:   [0, 0, 8]
Frame 19:   [0, 0, 8]
Frame 20:   [0, 0, 9]
Frame 21:   [0, 0, 8]
Frame 22:   [0, 0, 8]
Frame 23:   [0, 0, 8]
Frame 24:   [0, 0, 0]
Frame 25:   [0, 0, 0]
Frame 26:   [0, 0, 0]
Frame 27:   [0, 0, 0]
Frame 28:   [0, 0, 0]
Frame 29:   [0, 0, 0]

Starting Value: (132, 0, 0)
Frame 1:    [9, 0, 0]
Frame 2:    [8, 0, 0]
Frame 3:    [8, 0, 0]
Frame 4:    [8, 0, 0]
Frame 5:    [9, 0, 0]
Frame 6:    [8, 0, 0]
Frame 7:    [8, 0, 0]
Frame 8:    [8, 0, 0]
Frame 9:    [9, 0, 0]
Frame 10:   [8, 0, 0]
Frame 11:   [8, 0, 0]
Frame 12:   [8, 0, 0]
Frame 13:   [9, 0, 0]
Frame 14:   [8, 0, 0]
Frame 15:   [8, 0, 0]
Frame 16:   [8, 0, 0]
Frame 17:   [0, 0, 0]
Frame 18:   [0, 0, 0]
Frame 19:   [0, 0, 0]
Frame 20:   [0, 0, 0]
Frame 21:   [0, 0, 0]
Frame 22:   [0, 0, 0]
Frame 23:   [0, 0, 0]
Frame 24:   [0, 0, 0]
Frame 25:   [0, 0, 0]
Frame 26:   [0, 0, 0]
Frame 27:   [0, 0, 0]
Frame 28:   [0, 0, 0]
Frame 29:   [0, 0, 0]

Starting Value: (165, 156, 222)
Frame 1:    [9, 8, 8]
Frame 2:    [8, 8, 8]
Frame 3:    [8, 8, 8]
Frame 4:    [8, 9, 9]
Frame 5:    [9, 8, 8]
Frame 6:    [8, 8, 8]
Frame 7:    [8, 8, 8]
Frame 8:    [8, 9, 9]
Frame 9:    [9, 8, 8]
Frame 10:   [8, 8, 8]
Frame 11:   [8, 8, 8]
Frame 12:   [8, 9, 9]
Frame 13:   [9, 8, 8]
Frame 14:   [8, 8, 8]
Frame 15:   [8, 8, 8]
Frame 16:   [8, 9, 9]
Frame 17:   [9, 8, 8]
Frame 18:   [8, 8, 8]
Frame 19:   [8, 8, 8]
Frame 20:   [8, 0, 9]
Frame 21:   [0, 0, 8]
Frame 22:   [0, 0, 8]
Frame 23:   [0, 0, 8]
Frame 24:   [0, 0, 9]
Frame 25:   [0, 0, 8]
Frame 26:   [0, 0, 8]
Frame 27:   [0, 0, 8]
Frame 28:   [0, 0, 0]
Frame 29:   [0, 0, 0]

Starting Value: (156, 90, 206)
Frame 1:    [8, 8, 8]
Frame 2:    [8, 8, 9]
Frame 3:    [8, 8, 8]
Frame 4:    [9, 9, 8]
Frame 5:    [8, 8, 8]
Frame 6:    [8, 8, 9]
Frame 7:    [8, 8, 8]
Frame 8:    [9, 9, 8]
Frame 9:    [8, 8, 8]
Frame 10:   [8, 8, 9]
Frame 11:   [8, 8, 8]
Frame 12:   [9, 0, 8]
Frame 13:   [8, 0, 8]
Frame 14:   [8, 0, 9]
Frame 15:   [8, 0, 8]
Frame 16:   [9, 0, 8]
Frame 17:   [8, 0, 8]
Frame 18:   [8, 0, 9]
Frame 19:   [8, 0, 8]
Frame 20:   [0, 0, 8]
Frame 21:   [0, 0, 8]
Frame 22:   [0, 0, 9]
Frame 23:   [0, 0, 8]
Frame 24:   [0, 0, 8]
Frame 25:   [0, 0, 8]
Frame 26:   [0, 0, 0]
Frame 27:   [0, 0, 0]
Frame 28:   [0, 0, 0]
Frame 29:   [0, 0, 0]

```

As you can see, either an 8 or a 9 is subtracted from each color component in each frame. Furthermore, a 9 always appears three frames after an 8, even though the starting subtracted value is different for each color component. Note also that each color component reaches 0 (that is, black) with a difference of either 8 or 9, not some arbitrary remainder. This means that the subtracted value cycle of 8,8,8,9 is never broken! (This algorithm was probably written to ensure that the last frame of the fade was as smooth as the others.)

Now, this puzzles me. According to my calculations, if you reverse the process -- that is, take the 8,8,8,9 cycle and sum it up to find all the possible combinations in 29 frames -- you only get 52 unique numbers. But as it so happens, each color component is a member of this set! This means that either the colors were picked specifically for this fade algorithm (unlikely), or that the fade algorithm was designed around the color palette of the game. But how on earth could somebody have figured out that if you take 8,8,8,9, shift the cycle appropriately, and keep subtracting the numbers from each color component in your palette, you'll eventually reach 0 for every single color?! There's gotta be some mathematical trick that I'm missing. What is it?

# Answer
> 20 votes
Actually, there's a simple logic behind the 8-8-8-9 pattern. It arises naturally if you use only 32 intensity levels (5 bits per component), but want to render that on an 8-bit-per-component display.

Consider if you have a 5-bit intensity level and want to extend it to 8 bits. The simplest thing to do would be to just shift-left and leave the low three bits zero. The trouble is, then it doesn't go all the way to pure white. The highest intensity level you can reach is 11111000, or 248. So you're not using the full intensity range of the 8-bit display.

Really, what you'd want to do is a calculation like `intensity8 = round(intensity5 * 255.0 / 31.0)`, to rescale the \[0, 31\] range to \[0, 255\]. However, there's a neat trick to accomplish this without any floating-point math or divides: set the low three bits equal to the high three bits. That is, to convert intensity from 5-bit to 8-bit you'd do

```
intensity8 = (intensity5 << 3) | (intensity5 >> 2);

```

Then an intensity of 11111 will map to 11111111 (31 maps to 255), and intermediate results will do something sane as well, e.g. 10000 -\> 10000100 (16 -\> 132).

This set of numbers is exactly what you have. Taking the red component of your first example, you have:

```
132    10000100
123    01111011
115    01110011
107    01101011
 99    01100011
 90    01011010
 82    01010010
 74    01001010

```

Note how the low three bits are always equal to the top three bits. The difference of 9 occurs when both bit 0 and bit 3 flip at the same time.

I'm uncertain why 5-bit intensity levels would have been used in this situation; perhaps that was the limit of the hardware of the arcade machine? It's notable that a 5-bit RGB value is 15 bits, which fits nicely into a 16-bit word. In any case, that explains the odd 8-8-8-9 pattern.

# Answer
> 0 votes
You should look into mode 13h, or 256 color palette fading. Back then, you had that many colors and what you did, was messing around with the whole palette, since you couldn't calculate new colors that weren't in it.

---
Tags: algorithm, arcade
---


# Question
Title: Creating maps and tileset for a 2d java game
I'm not a completly beginner to java, so I decided to write a map loader and a tileset loader myself instead of using a tilemap editor like Tiled. I'm using Slick & LWJGL for my game.

The plan was to load every map and tileset from external files. When creating a new map, you'd be able to assign tilesets to your map which define the tiles used to paint the map.

I've already written a tileset loader which creates tiles from an external file. For example:

> 0|floor|tiles/floor.png;

is a tile where id=0, floor means the player in the game would be able to walk on that tile, tiles/floor.png is the texture of the tile.

The tiles are stored in an array in the tileset class.

But I don't know how to create the map loader. Example for a map:

> 1, 1, 1, 1, 1;
>
> 1, 0, 0, 0, 1;
>
> 1, 0, 2, 0, 1;

etc. The numbers symbolize the id's of the tiles.

Is there any way to realize my plans? Or is there a better way?

Thanks in advance.

PS: Sorry for my english, I'm no native speaker.

---

My current solution:

```
public void createTiles() {
    for(int y = 0; y < map.length; y++) {
        for(int x = 0; x < map[y].length; x++) {
            for(int i = 0; i < tileSets.length; i++) {
                for(int j = 0; j < tileSets[i].tiles.length; j++) {
                    if(map[y][x] == j) {
                        Tile tile = new Tile(tileSets[i].tiles[j].texture, x, y, xOff, yOff, tileSets[i].tiles[j].isWall);
                        tileList.add(tile);
                    }
                }
            }
        }
    }
}

```

# Answer
Usually you use a 2D array of map tiles for this; and simply you assign them an ID. Then you can simply iterate over the tiles and draw the specific tile.

Usually, you can compute this similarly as such: x = tileID % tilesetWidth y = tileID / tilesetWidth;

Then, your source rectangle is simply (x, y, tileWidth, tileHeight)
> 1 votes

# Answer
You're on the right track! You'd want to iterate through your map (which is almost aways a 2D `Array`) and for each tile in the 2D `Array` do something similar to the pseudocode below;

```
for (int tileY = 0; tileY < map.length; ++tileY) {
    for (int tileX = 0; tileX < map[tileY].length; ++tileX) {
        switch (map[tileX][tileY]) {
            case 0:
                tile.setImage(someTileImage1.png);
                tile.setSomeOtherProperty(true);
                break;
            case 1:
                tile.setImage(someTileImage2.png);
                tile.setSomeOtherProperty(true);
                break;
            etc...
            default
                break;
        }
    }
}

```

the case statements representing each type of tile you can have in your map.

That said, it's sometimes good to be lazy (I mean that in a good way :) ). Why not make use of a great tile editor like Tiled and just setup a map loader to parse the Tiled generated XML or JSON file? You know the old saying, don't reinvent the wheel, but I can respect if you'd really like to know how exactly that wheel is created!
> 0 votes

---
Tags: 2d, java, maps, slick
---


# Question
Title: android basic Movement for array-objects
I was adviced to start a seperate question for this so here I go. Been stuck so long with this do if you can help, please do.

Lets get to it! Im trying to set the speed for my bullets, but since Im moving my sprite using a joystick Im finding it really hard. Ive tried about a hundred things but nothing rly works. Ill post code with comments below.

code for my controls:

```
        if (dragging) {

        // get the pos
        touchingPoint.x = (int) event.getX();
        touchingPoint.y = (int) event.getY();

        angle = Math.atan2(touchingPoint.y - inity,
                touchingPoint.x - initx) / (Math.PI / 180);
        spriteAngle = Math.atan2(touchingPoint.y - inity,
                touchingPoint.x - initx) / (Math.PI / 2) + 2;

        bulletSpeedX = (Math.sin(angle * (Math.PI / 180)) * 5);
        bulletSpeedY = (Math.cos(angle * (Math.PI / 180)) * 5);

        pointerPosition.y += Math.sin(angle * (Math.PI / 180)) //my Sprites position, gets update when Im dragging joystick, works fine.
                * (touchingPoint.y / 90);
        pointerPosition.x += Math.cos(angle * (Math.PI / 180))
                * (touchingPoint.y / 90);
        bulletPos.y = pointerPosition.y; //Since this updates every time Im dragging that means that the bullets that are alrdy shot stop moving when I drag, but I need this position.
        bulletPos.x = pointerPosition.x;

        }

    else if (!dragging) {
        touchingPoint.x = (int) initx;
        touchingPoint.y = (int) inity;
    }

    if (event.getAction() == MotionEvent.ACTION_DOWN && (int) event.getX() > 650 && (int) event.getX() < 750
            && (int) event.getY() > 300 && (int) event.getY() < 400){

        shooting = true; //when I press my button shooting turns on
    }

```

Some problems with this code: if you read the comment about my bulletPos-variable you will see a problem. Also, If I set shooting to false when I stop pressing this button, then all my bullets dissapear, do I need some sort of exists-boolean for each object in my array, that turns false when my bullets reaches one of the borders of my world/hits an enemy?

Code for my bullet:

```
    public Bullets(Bitmap bitmap, int x, int y) {
    this.bitmap=bitmap;
    this.X=x;
    this.Y=y;

}

public void draw(Canvas canvas){
    canvas.drawBitmap(bitmap, X, Y, null);
}

```

problem with this code: Obviously I need some sort of update method for my position here, but if I want that I have to import and initialize my controls-class here, and if I do that the game crashes after a while for some reason.

Code for my drawing:

```
    private void shootingControl(Canvas canvas){ //gets called in onDraw()-method
    if(controls.getShooting() == true){
        if(System.currentTimeMillis() - lastShot > delay){
         lastShot=System.currentTimeMillis();
         bullets.add(new Bullets(bullet, controls.bulletPos.x, controls.bulletPos.y)); //adds a bullet in my arraylist at the position of my sprite
        }
         }

    for(int i = 0; i < bullets.size(); i++){
        bullets.get(i).draw(canvas);
        updateBullet();
    }

}
public void updateBullet(){ //this was one of my attempts at setting speed for each bullet, didnt work out to well
    for(int i = 0; i < bullets.size(); i++){
        bullets.get(i).setX((int)controls.getBulletSpeedX());
        bullets.get(i).setY((int)controls.getBulletSpeedY());
        if(i==bullets.size()){
            i=0;
        }
    }
}

```

problems with this code: I tried putting my update method here instead of in my bullet-class since the game crashes if I import my controls into that one. But I cant get it to work anyway so..

As I understand it you get movement like this:

```
    newPosition = oldPosition + (speed * delta)

```

But since my bulletPosition gets updated everytime I drag I cant get that to work, cus whenever do it like the pseudo-code above the bullets thats alrdy been shot stops moving when my bulletPosition gets updated.

Im sorry for the long post but I rly want to be clear since Ive been stuck here for so so long, and I cant find anything on the webs that describes my problem, just similar problems, and Obviously cant get those to work so..

Ill add a link to a video of my game, so you can see how my sprite moves, just so I can get a clear answer, cus all this is very new to me, video: http://www.youtube.com/watch?v=nejaMtug09A&feature=youtube\_gdata .

Thanks for your time!

# Answer
> 1 votes
You shouldn't calculate the delta time within the player itself( I think it's the player because it isn't clear on where the pieces reside). The delta time should be passed on from the main loop onto your objects. This way every object receives an equal delta value.

You could move the movement to the bullet class Just for a simple illustration:

---

Your bullet class

```
public class Bullet{
        private float x; // x position
    private float y; //y position

        private float velX; // velocity X
        private float velY; // velocity Y
        private Bitmap bitmap;

         public Bullet(Bitmap bitmap, float x, float y,float velX, float velY){
            this.bitmap = bitmap;
            this.x = x;
            this.y = y;
            this.velX = velY;
            this.velY = velY;
        }

        public void update(float deltaTime){
            x += velX*deltaTime; //Makes sure that we move velX pixels per second
            y += velY*deltaTime; //Makes sure that we move velY pixels per second
        }

          public void draw(Canvas canvas){
                canvas.drawBitmap(bitmap, x, y, null);
          }
}

```

---

```
//Somewhere where you update your bullets
for(int i = 0; i < bulletList.size(); i++){
    bulletList[i].update(deltaTime); //where deltaTime is your calculated delta.
}
//Afterwards draw them by calling the draw method.

```

The idea here is simple. The bullet class handles the movement internally. You just need to create one, set it's position and velocity. When the update method is called the velocity is added to the position. Afterwards when you call the draw function. The x and y of the calculated position are passed as the drawing position. Have a central point where delta time is calculated and passed on to the objects that need it.

So in your case:

```
bullets.add(new Bullets(bullet, controls.bulletPos.x, controls.bulletPos.y,controls.bulletSpeedX,controls.bulletSpeedY)); //adds a bullet in my arraylist at the position of my sprite

```

Funny thing is you have already been doing it with pointerPosition in a way. Look at it. You use the gamepads position to move the players position by adding to it.

I suggest looking at libgdx, as it provides a sophisticated library for gamedevelopment on Android.

---
Tags: 2d, android, physics, movement, objects
---


# Question
Title: What's the difference between a game engine and a physics engine?
What's the difference between a *game engine* and a *physics engine*? How do they work together, and what's the meeting point between them?

# Answer
> 9 votes
As far what physics engines do, I wrote an apparently decent post here: How does a collision engine work?

A game engine is software that is intended to make it easy to develop a game without needing to invest in a great deal of additional technology. In other words, it implements all the basic technologies of games like graphics, physics, networking, input, AI, etc. in such a way that they are easy to tie together with game-specific logic.

Some game engines are very specific to a certain genre or otherwise impose a lot of assumptions on the games being made with them. In exchange, they are almost complete out of the box solutions for those target games. Other game engines are much more generic, but require engineers to spend more time implementing genre-specific code.

A physics engine had the sole purpose of moving objects around in a simulated world. They take the physics properties of objects, such as mass, shape, material, current trajectory, etc. and then calculate a new position and state for all those objects.

The line between game engine and physics engine is relatively clear. In many cases, they are completely separate libraries, such as an Unreal Engine game using the PhysX physics library.

In general, the game engine feeds initial state data to the physics engine, and the respones to physics engine responses. For example, the game engine loads a level and tells the physics engine that there are 10 objects in the scene at given positions. The physics engine then process updates to those obects' states, as the game engine asks the physics engine to update the objects and report on their changes. Graphics data is often synced up to changes from physics, so that changes made by physics show up on the player's screen.

The game engine may respond to events from the physics engine. The physics engine might raise an event when two objects collide, or when two objects that were touching separate. The game engine will forward these events on to game logic code, which might respond by applying health damage to objects or adding points or so on.

Game logic may also influence the physics simulation. Game logics may decide that gravity is suddenly inverted because of a power up, or that the player's character gets a vertical force applied because the player hit the jump key, or so on. This is often accomplished by creating a new object as defined by the physics API in use, where the objects represents a force or such.

Game engines will typically try to unify all their systems behind a common API and object model. For example, a component-based game engine will typically have a ColliderComponent and a BodyComponent. The former will register a shape with the physics library (which also handles detection of colliding shapes without any physical response), and the later provides information to the physics library about how to handle collisions, forces, etc. An object in such an engine may only have a Collider if it is just looking to find out if objects collided (like a trigger).

Many games do not have a "game engine" per se. Smaller games typically have their game logic and their supporting code all merged together. Which is just fine: enforcing a strict separation increases complexity and wastes time if the code is not going to be reused for multiple titles in different genres.

Likewise, many "physics engines" are not generic and are integrated directly with the game engine. This is especially common in platformers, and many 2D games in general. Some games require such specific physics requirements that a general purpose physics engine simply makes little sense to use. Mario games, for instance, don't model anything in a physically accurate way, and the game behavior is almost entirely based on very specific physics behavior quite different than what a general physics simulator handles, so a general 2D physics library like Box2D is entirely illfitted to the game.

# Answer
> 3 votes
Well, *Game engine* is a generic term, *Physics engine* is more specific, the "problem" is that the functionalities that a game engine provides are up to the developers that have coded that particular game engine.

There are very basic game engine that have no physic support or they expect you to add to it manually, and game engine that support physics and fractures in real time.

Your view shouldn't be about how they work together in the first place, just look at what a game engine offers and if you need a physics engine add it to your code.

There are also some engines that mimic the physic with pre-baked collision and explosions, there are several approach to this, depending on what you have, what you want to achieve and what is your target machine, you better look to the features and how they are implemented, only the name "physics engine" can't tell you what you are dealing with.

---
Tags: physics-engine, terminology
---


title: Which software licenses cover my needs?

text:
# Question
Title: Which software licenses cover my needs?
I want to license my game, to protect my intellectual property, but I also want to make it open-source, and sell it.

I have an engine that I'd like to open-source, but I'd like to be the only one with rights to distribute it in that form. I'd like people to be able to distribute it however they wish, if it is their modified version. I'd like games made with the engine to be able to be sold, but not re-distribute the engine, and they must credit it if they do use it.

I'm not a legal expert, and I have no experience as of yet with licensing. Which licenses will allow me to do this?

# Answer
> 10 votes
You should talk to a lawyer. Check out the comparison of open source licenses available to you (Or this one). Ultimately it's up to you and your lawyer to decide which one suits you best.

**EDIT**

To address your additional requirements. If you don't have the money to hire a lawyer to review the available licenses and match them with your requirements, you're not going to have the money to enforce any violations of the license you choose. All you can really do is *ask* for what you want and trust people will follow the rules you ask of them.

I recommend you do exactly that, simply add your request to the top of each of your source files. You don't need to get fancy with legal documents. Just tell people, in your own words, how you want your code used. Can you really see yourself trying to enforce the rules anyway? Going into court to defend your open source code from misuse? I find that highly unlikely.

Would it upset you if you found out someone was using your engine source code against your wishes? Sure, but the likelihood of you ever finding that out is just about nil. Same as if you had a "professional" license attached to the source.

# Answer
> 2 votes
Your needs sounds like you'll want more than one license. The engine and tech can be released under an Open license and the content can be released under a restrictive license.

If you want to ensure that the tech cannot be used for serious commercial competition ( if you think your tech is really that special) you can use something like the GPL or a CC-NC license.

This is what id does, for instance.

# Answer
> 1 votes
I'm going to simplify here, and also I'm not a lawyer etc etc etc. You should actually read these licenses if you're going to use them, and talking to a lawyer doesn't help either.

I'm assuming this is code you write yourself, and you will keep the copyright for it. When you use an open source license, you irrevocably grant other people the right to distribute your work possibly with certain strings attached, but for the licenses I'm familiar with, this does not take away the rights that you already have under copyright law. (ref: https://www.gnu.org/licenses/gpl-faq.html#DeveloperViolate)

Of course, if you incorporate code from third parties, you'll have to comply with the associated licensing terms.

The licenses I'm familiar with (mainly MIT, LGPL, and GPL) also do not prevent others from selling the code. GPL makes it difficult because the GPL would obligate anyone selling it to also offer source code and the rights to modify/redistribute it (and thus undercut the seller). LGPL has a weaker version of that, and MIT is a public domain equivalent license (i.e. give everyone all rights under copyright).

If you want to prevent others from redistributing your code (and making money from it), you can release the source code with your game but not offer any license to distribute it. Jason Rohrer did this with Inside a Star-filled Sky (ref: http://insideastarfilledsky.net/). If you just want to prevent other people from making money from it, Creative Commons BY-NC is good for that.

It really depends on what your goals are in releasing the source, and exactly what you want to allow people to do.

# Answer
> 0 votes
I think that you are approaching this on the wrong side.

Question: what you need to license, the source code or a compiled software?

In the first scenario you probably want to stick with something like the GPL, BSD or MIT licenses, in the second case you probably just need an EULA.

You also can mix this 2 requirements but i don't think that you *need* to give a license for your source code in your case, the user will never see your source code; you also appear to not being interested in patents, and patents are the only way to prove that you own a particular asset of your software or you own the rights for an UI, a file format, or some other pieces of your code including the design and its own implementations.

---
Tags: licensing
---


# Question
Title: Fast Updating of Large Amounts of OpenGL data
I'm seeking advice, suggestions, and ideas on how to handle the updating of large amounts of data in OpenGL and c++.

My partner and I have gone through two methods.

The first is vertex by vertex rendering. Right away, this was crossed off the table; it's super slow! When using it, the simulation ran at 3 FPS. All it was rendering was just some untextured cubes composing a flat landscape. Imagine adding some animals to that, or even a full blown world! This method is definitely not an option.

The second method is VBOs. The problem with VBOs is that they don't like having vertice added or removed (though removing can be accomplished with a hack of setting data to null). We could just create a new VBO every time something changes in this way, but the 3D data is likely to change often, if not every frame. Thus that would also be very inefficient, and VBOs are not an option either since, we can't add vertices/faces and can only dirty-hack remove existing vertices/faces.

What, then, would be the best method for us to use? Would we be able to use a shader or something to create a custom datatype on the graphics card, upload the 3D data to it initially, and then afterwards, only send the transformation details (such as a transformation matrix or what have you) and what faces/vertice have been removed/added? Even if the above method is a possibility, how else could I go about doing this, and what is its pros and cons? Perhaps one of those would better serve my needs.

**Edit**: Here is what I mean by "large amounts of data". It shall be known that the project that requires this fast updating of "large amounts" of OpenGL data is a simulator that attempts to simulate its own world. World being defined as an entire existence, which may include multiple universes, dimensions, galaxies, solar systems, planets, etc, such that it is not limited to a single "planet", which is a common definition of the term "world". **Thus, this "large amount of data" is the portion of the world that is visible to the player**.

As this is a world simulator, all the data of the world is procedurally generated. This means 3D models are NOT being loaded. The "3d models", if you wish to call them that, are generated from the 3D data of the objects in the world, such as a house, tree, car, flower, cat, or cup.

In short, the world simulation aims to simulate the world as detailed as possible (the limit being set by the resources of the computer running it). For the purpose of this question, let us assume that the simulation is being run on a computer that allows for every object to possess very high polygon counts which we will say, for the purpose of this question, exceeds 100k for a cat.

That in itself is not a problem; just initially place the data in a VBO. However, what happens as the cat grows? New vertices and faces would be added and removed. The case extends to actions the cat does such as walking around the world (**Animations are not explicitly defined and used in the code. They are, rather, a byproduct of the simulation, in which the 3D data itself is updated, creating the effect of an animation**). That is where the problem lays. Creating a new VBO for every frame of the 'animation' (keep in mind the above statement on animations), or for every time the cat grows, is not an option due to performance concerns. It'd more or less achieve the same results as vertices by vertices rendering, but with more overhead, and the only performance gains seen being when no new vertices and faces are added or removed.

**In conclusion,** large amounts of data, such as 100k polygons per model, will be seen. The specific edits that will be done to this data results from the growing, or otherwise shrinking, of objects in the world and the simulation of these objects (See the note I made earlier on animations.)

Edit2: To clarify confusion, this is how the data is changed:
1. The position of each vertices is updated relative to the camera. Eg, a dog walking away from the camera.
2. Vertices are added and removed from the model. Thus faces are also changed, removed, or created.
Changes #1 and #2 are expected to occur at least once a second for every object in the world, excluding terrain, rocks and other inanimate objects.
I do not see how patterns of changes can be predicted, as the data can change in unimaginable ways.
Examples of changes that will occur:
1. The simplest case, an apple falling from the sky. This is easily be done by simply applying a transformation matrice. The rest that follow are more complex.
2. A sword lopping off the arm of a soldier. In this example, vertices are removed from one model and put into a new model. VBOs do not explicitly support this, but a dirty hack exists to work around it.
3. An engineer welding two pieces of metal together. In this example, vertices are removed from one model, and added to the next. VBOs do not support this. In this specific case, that problem can be worked around by simply retaining the individual VBOs and only do the merger of data in the world simulation code.
4. A chemical reaction. Such examples of this would be an acid eating away a material or mixing liquid detergent and hydrogen peroxide reference video)
5. A physical reaction, such as ice melting into water.
6. Liquids. The most complex case, as their surface dynamically changes in countless ways.

Edit 3:
A wave of inspiration swept over me and I've come up with two ideas on how to solve this problem. I'm now working with my partner towards implementing both. In short, one method creates a custom data structure similar to VBOs, that has the in-built feature of adding and removing vertices, while the other is a hack using VBOs, destroying the old one whenever vertices are added or removed and recreating it, but doing it on the GPU so that data is not transferred all the time, which is the source of the nightmarish slow performance of vertex by vertex rendering. More details to come.

# Answer
> 3 votes
You have a couple different problems here.

First, the transformation of the data and getting those changes to the GPU. If at all possible, you should aim for moving the transformations themselves to the GPU. This might very well require using OpenCL/DirectCompute/CUDA, as the standard shader stages don't really do what you need for most non-trivial transformations. In general, if you're trying to process hundreds of thousands of vertices moving around, the GPU is going to do a better job than the CPU, unless your particular deformation algorithms happen to be one of the (many) sorts of algorithms that don't work well on GPUs. You haven't provided enough details to tell.

Second, you have lots of vertices on your models. A problem that you're assuming you have -- but which you probably don't -- is how to draw a 100k vertex model. The question you should be asking is whether you need to draw a 100k vertex model. At a few dozen meters distance, odds are that model is going to be indistinguishable from a simplified 10k vertex model. At a few hundred meters, it'll look the same as a simplified 1k model. At large distances, it'll look just fine as a billboard sprite. This is basic LOD (level of detail) work for a standard pre-made 3D model. For your procedural models, it may be a bit trickier; however, it's still almost certainly possible, and if you're worried about rendering performance and GPU bandwidth is absolutely the path you want to go down.

Second part deux the third, you possibly have a lot of models if this is a complex simulation. Just as you want to reduce the visual complexity of your models to avoid processing things the user can't see, you're going to want to use visibility culling to avoid processing entire models (or sub-sections of models) the user can't see. If you've got a dozen 100k models but they're all behind the camera, there's no reason to even think about how to render them, so just don't. There are many great data structures for spatial scene management to help with this. Likewise, for large and complex models, you can use similar (or even the same) data structures to split your models up and avoid any rendering overhead for parts that aren't visible. If you have a large cat model that is spatially separable between its head, body, legs, and tail, and the user is zoomed up close on the cat's head, you may be able to determine that the legs are not visible at all and thus simply not need to worry about drawing them. This works well with the previous paragraph, since you'll likely either be zoomed in to a single object (and you can cull most everything else) or you'll be looking at a larger scene where all the objects are smaller in perspective (and hence you only need to render simplified versions of them).

The specific algorithms that are available and which are the best to use for your specific data and needs will vary. If your meshes are very deformable then you'll probably want to use a very different algorithm than if they only scale. A good first cut might be basic kd-trees. Going from there, you should look into the research done on voxel engines (real voxel engines, not the Minecraft clones) as they generally deal with the same kind of high-detail models you are. I am unfortunately not versed in that topic nor do I have any good resources to point you to, but maybe knowing what to look for will help you find an answer. (And if you do find one elsewhere, please post it here!)

---
Tags: c++, opengl, 3d, simulations
---


# Question
Title: How to convert mouse coordinates to isometric indexes?
I draw isometric map with tile **64x32**:

```
const Offset = 160;
int X, Y;

for (int a=0; a < 6; a++)
  for (int b=0; b < 6; b++) {
    X = a * 32 - b * 32 + Offset;
    Y = a * 16 + b * 16;
    DrawTile(X, Y, tile);
  }

```

Image, illustrating this code:

Dear professionals, please, help with a formula of transformation of mouse coordinates in isometric indexes of a cell. Example: (105; 100) -\> \[1; 4\].

# Answer
> 25 votes
You need to **determine the transformation matrix** from tile-space coordinates to screen-space coordinates, then **calculate the inverse matrix** for this, which when applied to screen-space coordinates transforms them to tile-space ones.

> By the way: Your offset is actually pointing to a place which would be (0.0, 1.0) in any sane coordinate system, but that's not a big problem, just something to keep in mind. This means that the offset of the origin of your transformed coordinate system is at (Offset + 32, 0).

---

## Specific case

What you are basically doing for transforming tile-space (a, b) coordinates into screen-space (x, y) coordinates is to run it through the following transformation matrix:

Definitions: *a* and *b* for the tile (0, 0) are in the range \[0.0, 1.0) with (0.0, 0.0) being the upper corner, (1.0, 1.0) the lower corner, (0.0, 1.0) the left corner and (1.0, 0.0) the right corner in screen space.

We extend the coordinate definitions by a constant third coordinate (it's always exactly 1) to be able to incorporate the translation into the matrix.

Now you can create the inverse matrix for this transformation. The basic formula is:

... with **C** being the matrix of cofactors for **A**.

In your case, the determinant |**A**| is always 1024, no matter the offset, so the inverse matrix is:

---

## Example calculation

Now, for your example data ...

Put your number for offset in the formula, and you get:

Multiplying (105, 100, 1) (the screen coordinates) with the matrix gets you:

Since the third coordinate is always 1, we don't have to calculate it. Round down to the nearest whole number, and you get (1, 4) as your tile space coordinates, as expected.

---

## General dimetric projection matrices

If you have a perspective like this with each tile being 2 *w* in width (64 in the example, so *w* = 32) and 2 *h* in height (32 in the example, so *h* = 16), and the offset of the origin point in screen space being fx and fy for the horizontal and vertical axis respectively (192 and 0 in the example), the matrices look like follows.

**Tile space to screen space**

**Screen space to tile space**

---
Tags: mathematics, algorithm, isometric
---


# Question
Title: Are there any frameworks that allow me to write games in C# on Linux?
I'm looking for something like an alternative to XNA - I don't care whether it's a 2D or 3D engine. It's not because I dislike Windows or am anti-Microsoft; it's because I like running Linux, code in Linux completely (for C# I use Mono, obviously), and by no means have any hardware to actually support programming in XNA, simply because my video card is 6 years old. I also don't have a Windows 7/Vista CD for DirectX 10.

Thus, for game development I'm kind of stuck in the stone age. Yet, I like C# very much and would hate to have to drop it as a language due to this.

Is there anything I can do?

# Answer
I'm afraid there is no such thing as a complete alternative to XNA in the world of C#-based cross-platform frameworks. Monoxna is long dead, and very few other cross-platform tools use C# as their language of choice.

However, this soon-to-be port of XNA on iOS and Android looks very promising: ExEn. Don't know about requirements though.

Since you've used word "engine" you may want something more complex. I can remember only one cheap full-fledged C# engine that can run on Linux and has pretty forgiving hardware requirements: NeoAxis.

However, if your primary target is 2D games, then you may check out this little cross-platform game library: AgateLib. Two years ago it was nice to use yet somewhat buggy, maybe now things are better.

Anyway, if anything else fails, you can always use OpenGL with SDL via OpenTK or SDL.Net.
> 9 votes

# Answer
Why seek an alternative when you can use a port?

"MonoGame is a free OpenGL implementation of the XNA 4.0 Framework. It is built upon the excellent range of Mono compilers and is compatible with MonoTouch (iOS), Mono for Android (Android), MonoMac (Mac OS X), Mono for Windows and now Linux!

Our goal is to allow XNA developers on Windows & Windows Phone 7 to port of their games to the iOS / Android / Mac OS X / Windows / Linux and visa versa, with minimal hassle."

MonoGame website.

MonoGame repository
> 20 votes

# Answer
2 libraries good for software rendering:

1. SDL (C/C++) or SDL.NET, since they are built for *OLD* hardware and can optionally use OpenGL, if you want to upgrade your hardware later. SDL's totally cross-platform for desktop systems.
2. Allegro is another old-school library good for pushing pixels individually without the need for special graphics hardware.

I fing Allegro more powerful from a pixel pushing standpoint, but I do not think it sees the same level of activity that SDL does, and while SDL is kept up to date by its author, I think this is much less the case with Allegro.
> 2 votes

# Answer
You may want to check out ANX:

*The ANX.Framework is a framework which is source compatible with Microsoft's XNA framework 4.0. Source compatibility means, that you can "translate" a XNA game project to be a ANX game project by simply replacing all namespaces from Microsoft.XNA.Framework to ANX.Framework. The advantage of ANX is simply that you are able to swap the RenderSystem, the InputSystem and the AudioSystem. By swapping this systems you are no more limited to run your game using DirectX9 which XNA is using. ANX comes with a DirectX10 RenderSystem as a default. A DirectX 11, DirectX 11.1 and a OpenGL 3 RenderSystem is currently in development. This will make it possible to run your games on Linux and other plattforms which are supported by OpenGL etc. simply by swapping the namespaces.*

~ Codeplex site: http://anxframework.codeplex.com/

It is still under heavy development but most of the basic XNA features are implemented.
> 1 votes

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


# Question
Title: game-state update structure and distribution in MMO?
I'm developing an MMO, which has to maintain a global game-state.

Now I want to distribute the updates, which the players make to this state, to players which can see those updates (area of interest etc.)

Is there a common structure/format for these updates and for a global game-state?

Like, every action a player sends to the server has to include a type, the coordinates etc.

And are the updates, which gets distributed from the server to the players in the same format or are they different?

Also should I include timestamps or use the receive-time from the server to check which action came first and which sencond etc.?

And what should I send back to the player if he send an invalid action?

# Answer
> 7 votes
I recommend checking out already existing documentation on network protocol of games like Unreal, Quake, Tribes. For example here is a document for tribes:

http://www.pingz.com/wordpress/wp-content/uploads/2009/11/tribes\_networking\_model.pdf

You may want to separate your updates into the following categories :

reliable - things that the player has to know about unreliable - things that the player should know about, but no big deal if it is missed from time to time local - things that do not impact other players

For reliable messages (you can send multiple messages in a batch as well), you will most likely need some sequence numbers so that all updates are applied in chronological order and that both client and server are always kept in sync. If the player is trying to loot something, then the player would send a reliable message, if the server does not ack the reliable message (packet loss) then player has to resend the request (or timeout). Neither the player, not the server change their state until ack is received (for reliable messages).

Unreliable messages are things that can be missed once in a while, like players movement, the direction where the player is looking, the appearance etc. If the player loses these packets, at the next update, this information may be resent later, no big deal. If no ack is received, then the server will eventuall resend the unreliable update, if ack is received for unreliable message at some point then the server will stop sending the unreliable updates. Also if the player changes position, there is no need to resend the old position, just resend the latest state until player acks it.

Local updates are things that each player may see differently but have no impact on the game, like animation of trees, weather effects, things for which a global state does not need to be kept.

Some other things worth considering :

Do not flood the network:

You do not want to send unreliable updates every time a player moves (ie packet per move), that will just flood the network, you want to send them at a certain interval (like having fps and sending the update every 10-15 frames). Also if you send every unreliable event, you will slow down the performance of your server, so you may want to filter out how many unreliable events you send. If there are 500 players in the room, moving around, you may not want to increase the refresh interval and or prioritize which state updates are more important.

Path prediction:

The client should have a prediction built in for the movement so at frame 0 you can say the player is moving towards this coordinate and at frame 10 you can say that the player has changed position and direction, the client has to interpolate what happens between frame 0 and frame 10.

Timestamp:

Ideally you want to use sequence numbers for tracking game state, every time you send any messages there should be a sequence number (for resending purposes), reliable messages should have another sequence number on top of your packet sequence numbers. You can also include timestamp (simulation time) every few packets.

Protocol/structures:

You want to pack your data as much as possible (so that you can send more information in less time). Use tricks like bitvectors to store flags. Instead of strings send string ids (unless its chat). You will most likely have large switch statements for encoding/decoding, you may want to build a tool to autogenerate these or use something like google protobuf.

Error handling:

If the player sends a reliable request, then the player can either get a valid reply or an error reply (or timeout and disconnect), for example if the player wants to purchase an item, he can either get a reply saying item is purchased or an error that the item is not available or has already been bought by somebody else, until any of the possible responses is received, the player should do nothing (no state update).

# Answer
> 4 votes
The basic networking strategy looks like follows:

Every action the player does should be sent to the server with as much data as needed for the functioning of the game, but not more, to ease on the network traffic. Every data needs to be **verified** by the server to be a valid action. Invalid actions are logged for review, since they indicate bugs or cheating attempts.

The one overarching rule is to never trust the client with anything of importance: **The client is in the hands of the enemy.** This includes the time stamp, where the server should always dictate it (and thus the order of actions). What the packets should have is a serial number, so that the server can detect network problems easier and so that actions of a client happen in the same order as the client requested it. Two packets with the same serial number but different content also indicate a hacking or cheating attempt and should be marked as invalid and logged as above.

The state updates on the server have to happen atomically, though in practice this requirement is hard to fulfil without severe performance penalties, so most games opt for "locally atomic" instead (updates which happen "far away" and can't influence the state of the actor don't need to by synchronised with actions of the actor). This is a consistency/performance trade-off. Problems related to it have been a source of exploits like duplication bugs even in major games in the past.

The server then gathers the updates for each client into a per-client queue (usually the size of your networking data window, so something on the order of 1.5kb) and sends them after either a specified timeout or when the queue is full. The updates are bundled together in one packet - your system needs to be aware of it and handle multi-update packets. The server *never* sends client packets unfiltered to a client, not even to the same client. In particular, any text has to be filtered to include only the "safe" character sequences and any updates which the other client shouldn't be aware of aren't sent at all. Any actions which failed, for whatever reason including an invalid action, get a "failed action with serial number *XXXX*" notification sent along with the updates to the client which originated it.

---
Tags: mmo, browser-based-games
---


# Question
Title: What game design/game theory resources should I watch for a "TCG-like" game?
Me and my friend are building a "simple" trading card game - in the beginning we would have 20 cards and two resources, mana and health. This, along with a working multi-player is the minimum viable programm. The programming and graphics are not a problem - not of course literally, but since we're in the design state, we have other questions before coming to this two topics. Currently we have 10 cards, some basic mechanics and a short draft of ideas/comments/etc that I call the Design document. What I'm unsure now is how to continue developing the game, so I guess what I need are resources for game theory/game development so we at least don't reinvent everything.

Edit: To answer the questions below and keep them more visible:

This is the game in it's current form (made for iPad but works on Desktop computer if you use A S D J K L): http://app.planetofsnail.com/game.html As you can see, this is not a trading card game (or anything more than the bare skeleton of the idea :) The reason I called it a TCG is because of the way you play the game: you tap combinations to create magic symbols that translate into spells. When you break it down, it's like playing Magic the gathering, but instead of collecting and tapping lands, you make some hand gestures :) You have spells and monsters and two mana cast cost translates into two cast combinations (not exactly, but this is good enough without going into unnecessary details).

So to sum it up, from M:TG it uses literally spell names, mana costs and the fact two players play the game. The actual mechanic is different (you don't collect lands, every turn you have a fixed amount of mana that replenishes etc.)

BerndBrots' link to a game balancing article and actually the whole series is what I'm looking for - how to design a game (preferably TCG since TCG is the closes to what we're doing).

# Answer
> 3 votes
This is a really broad question that does not allow for a single specific answer. Also, I don't know of any TCG specific game design resources. Let me still suggest three things that might be helpful to you:

* Is your TCG based on something, like a concept to explore (honor, survival, priorities in life), a setting (wizard duel, political campaign, city building), or a specific franchise (Pokémon, Game of Thrones)? If so, try to deduct as many of the game mechanics from this basis (or these bases) as possible. Don't just copy the mechanics of another game and force them on top of whatever your TCG is based on.
* Define win conditions based on your core concepts, setting, or theme, and then try to use cyclical imbalances to your advantage. Cyclical imbalance means that some cards or tactics work well against certain other cards or tactics, while being vulnerable to others. If done right, this ensures that your game does not become stale, as there will be a meta-game evolving around it. Even if you want to produce a prototype as quickly as possible, I'd say that it is important to design that prototype in such a way that there is some space left from a mechanics point of view to add more complex cyclical imbalances later on.
* The makers of Magic: the Gathering have defined what they call a "Jedi curve", which specifies, for each spell color, how strong a creature without abilities can be depending on its mana cost. They also defined multipliers for keywords such as "flying" or "first strike". The rule is that each creature has to be within +/- 15% of that power value. That ensures different creatures are comparable in their cost/benefit ratio. It's an easy balancing tool that you can use as well.

---
Tags: game-design, game-mechanics
---


title: Expiring timed actions a good idea?

text:
# Question
Title: Expiring timed actions a good idea?
We have an online game where players sometimes have to wait a while (say 30 minutes) before a process they intiated completes. This encourages them to come back later. An example of this is growing crops in Farmville or basically any action in the Sims Play4Free.

Now, however, there is the idea to let these processes expire, so if the player doesn't 'reap' them in time (e.g. within 4 hours) they are aborted. I'm a bit sceptical about this. How will this make players come back more often? Is not the reward of reaping the process enough for that? Can we expect players to fit their daily schedule around our game, maybe even set the alarm clock at night? Won't this just cause players to give up on starting these processes in the first place?

I realise this may be too subjective for this site, so I'll end with a concrete question: Do (m)any other online free-to-play games employ this technique?

# Answer
I don't know the ratio of games that use expiring rewards on timed actions. Whatever the numbers might be, I would strongly discourage you from using that sort of mechanic:

* It forces players to return to the game when they might not want to, or -- worse -- when doing so they would neglect their real life duties.
* Even if it works, it drives players back to your game not because it's fun to play the game, but because they are punished for not doing so.
* It does not offer any reward for active players, as those are collecting their rewards on a regular basis anyway. (This is why I disagree with csiz's answer: Even if your business model resolves around in-game purchases, you win nothing with this mechanic.)
* All in all, it is just a blatant and aggressive attempt to force your players to return to the game regularly and frequently. This is about as bad a design decision as I can think of.

TL/DR: Don't use crude Skinner mechanics to keep your players engaged!
> 5 votes

# Answer
Well it will make the few determined players return, as they would anyway. But it will annoy the hell out of the casual gamer. (especially if the window is so small, maybe you can get away with it nicely if it were 1 or 2 days) Basically it will force the player to make the decision of either devoting to your game or leaving it altogether.

Either way has its advantages though. If you're going for in-game purchases, then keeping the devoted players would be a good choice. If you're looking at ads, this may reduce unique visitors.
> 2 votes

---
Tags: game-design, free-to-play, quests
---


# Question
Title: How do I cheaply place a watermark over what's rendered in OpenGL 3.0+?
I would like some insight about how to place an image with an alpha, and a certain amount of opacity, on the top of everything that is rendered. What's the cheapest way to do that?

I use C++ with a programmable OpenGL pipeline.

# Answer
> 10 votes
After you've rendered your normal bits and pieces:

* Disable depth testing.
* Prepare an orthographic matrix to get a screen-aligned coordinate system you can reason about, taking care to honor your aspect ratio.
* Enable blending with blend modes of your choice.
* Generate a quad and draw it with a simple fragment shader sampling from your texture.

# Answer
> 4 votes
One way is with overlays. It should be fast/cheap enough.

*UPDATE*: As Lars Viklund's comment explanations go, these *overlays* do not refer to the older concept that predates the programmable pipeline. The older way to add overlays (or underlays for that matter of fact) had to do with creating special render context planes like described here.

# Answer
> 3 votes
Depending on what your current pipeline is, it could be really easy to add it in a post process step.

Assuming you already have a post-process chain where you can render to a certain target to apply some extra processing to your scene, adding the watermark could be a post-process where you just render your final scene texture and then add your watermark texture. Obviously you can "factorize" this step into other if you don't want to add a new step and even come up with fancy effects for your watermark. Also with this method it could be extremely simple to remove your watermark step later.

---
Tags: c++, opengl, pipeline
---


# Question
Title: How do I increase the size of a buffered image to the left and upwards?
I need to know how to increase the size of my buffered image to the left and up, not just the right and down.

```
bI = new BufferedImage(yMax*size*5, xMax*size*5, BufferedImage.TYPE_INT_RGB);

```

# Answer
> 1 votes
The "direction" of expansion would only matter if you already had data contained in the buffer. If you have a buffered image already, then want to make a larger one, you'll need to copy the data into the new larger buffer. When you copy the data into the new buffer you simply place the existing data at the bottom right corner. Like this:

Where `x,y` are the width,height of the old buffer and `x2,y2` are the width,height of the new buffer.

So copying the data in I would get the old buffered data with getRGB then place that in the new buffer with setRGB.

---
Tags: java, image
---


# Question
Title: How to approach dual skills in an rpg game
I am developing an rpg-sort of game. My question is how a dual-tech system would work (like snes chrono trigger game had). I already have coded how to use a single skill.

Probably not the best way to do it, but here is how i have it working right now:

I have a Skill class and in my level, I define a `Skill currentSkill` When a skill is activated, the level starts rendering everything at half-speed except for the skill caster and the skill target.

Now what i am not really sure how to do is, how to structure my dual-skill class, and how to make this one's animation (which would include animating the 2 skill casters + skill targets) affect the initial skill cast.

The dual skill should be activated after a single skill is activated, eg. Character A casts skill a, which can be combined with character B skill b to produce skill c.

If that was somehow clear to you (think I complicated it) could you please provide some pseudo code / idea / example on how to achieve it?

EDIT:

I realize after reading the comments (and re-reading my question) that i was not clear on what I want to achieve, so I'll try to re-word myself (non native english speaker, so sorry for the lack of grammar)

Some considerations :

* It's not a multiplayer game so I will refer to the characters (or "players") you can use as units.
* Its some kind of rpg battle game ( it's pretty much a clone of the mobile game battlehearts but with dual-skills added, if you have seen that, you can get a pretty good idea on what game i'm working on).

basic idea:

1. Unit A casts skill a.
2. Unit B checks that he can combine its skill b with skill a.
3. Unit B casts skill b.
4. Unit A skill gets canceled
5. Unit B skill gets canceled
6. Unit A and B cast skill c.

here's some example:

* Unit A is swordman (with a single-target critical-hit skill called Bash)
* Unit B is mage (with a skill called air strike).
* bash + air strike = air slash ( skill that pierces and damages all enemies in a line, for example)

.asd

1. swordman uses bash
2. mage "realizes" he can combine it with air strike
3. on mage, skill air slash gets enabled.
4. when used, air strike consumes bash's and air stryke's cooldown, but executes a different skill (im talking about a different animation here, not sync'ing bash and air strike animations)

question is, how would you structure the code to achieve the above behavior? what kind of datastructure would you use to store information about dual-skills?

# Answer
> 1 votes
I think I get the idea. You want to combine 2 skills into 1 combined skill, or do you mean a combine effect based off of the two skills. Like if hit with a two fire spells in a row, you are prone to more fire damage and get a fire debuff? If not, it's just as another said, your wording.

A couple things. I am not sure how you can activate a dual-skill off of a single skill if the dual skill requires Character A's skill choice and Character B's skill choice to produce skill C.

I take it it is something turn-based like Chrono-Trigger? You select skills for the characters and then they do them in order of selection based on some sort of initiative timer. If I were doing this, I would possibly have some sort of checker for a bunch of spell flags that can produce the combined effect. You wouldn't need to check this until after the second class's ability is chosen, and then the third. If this is real-time, it's going to be more difficult as you need to set an amount of time that you allot to let the player select multiple skills to cause an effect, if this is something you even want to worry about.

Guild Wars 2 has something like this. Thieves and Necromancers can put down a Ground Target AOE that lets spells, arrows, rocks, etc, to absorb the effect. So, if an arrow that is normal goes through the effect, it adds poison damage.

I would do it with, off the top of my head, enum states possibly. Though this probably isn't the best way to do it.

This is my best answer/recommendation based on your question.

# Answer
> 0 votes
Try an event based design:

1) Define a class SkillActivatedEvent that stores a Skill object, a Unit object, and some other properties like the area in which the skill is active

2) Raise a SkillActivatedEvent whenever a skill is used

3a) Let skills that are already in effect react to SkillActivatedEvents by changing the behavior of the new skill, by changing their own behavior, or by unregistering both itself and the new skill in favor of a new skill. If you take this route, information about dual skills is stored in or accessed by your skill objects

3b) Alternatively, let your game controller react to SkillActivatedEvents by going through all the active skills and looking for any combos to apply. In this case, information about dual skills is stored in or accessed by your game controller object.

As for data structures:

* You can hard-code the combinations in the form of if-statements, either in your Skill or game controller class.
* You can also use a table-like association between a tuple of skills and a combo skill that either your skill objects or game controller object accesses. " =\> air slash" could be stored in a simple database table, an XML file, or whatever storage system you want to use.

Factors that make hard-coding combos more viable include:

* You only have a small number of combos
* Interactions between combo skills and their "ingredient" skills is unlikely to change
* Combo skills have parameters that depend on the parameters of their ingredient skills, and these dependencies are unique in most cases

(The negation of these factors make the tuble-combo association datastructures more viable.)

---
Tags: game-design
---


# Question
Title: Is XNA a suitable platform for indie games for Windows?
I'm new to game development and want to implement a few ideas I've had as a hobby over the next few months. I want to use only C# as the development language for 2D and very light weight 3D games.

What are the disadvantages of using XNA to develop games for Windows?

Most of the resources for XNA seem to revolve around XBOX or Windows Phone. I have successfully built some prototypes for Windows but am not sure what the limitations are in terms of distribution, etc.

# Answer
Yes. It certainly is, despite naysaying advocates of Linux, Mac, OpenGL, and C++. They tend to ignore the main criterion of your question: "on Windows".

I would recommend trying out those resources that seem to only applicable to windows phone or xbox. Nearly all the xbox example projects provide pc versions, all of which have liscensing open to free use. Look at this search list: http://xbox.create.msdn.com/en-US/education/catalog/?contenttype=4&devarea=0&platform=0&sort=2. Also, XNA generally performs better on the PC than on the xbox, because the second stage of the CLI peforms inlining. (And the infinitely better garbage collector doesn't hurt, either.)

Especially as a hobbyist developing for yourself, if you want to develop games in managed code, C# and XNA will serve you very well. You will be able to accomplish everything that you could at a baser level of coding, and you will save countless headaches.
> 5 votes

# Answer
no limitations that i'm aware of although you will need to access MonoGame if you want to sell on the windows 8 store

lookup the successes of XNA (Bastion, Magicka etc)
> 1 votes

# Answer
You may want to check out ANX, it wont let you publih on WindowsPhone and XBOX360, but it opens Linux, MacOS, PSVita and Widonw8Metro (or ModernUIStyle) to you. Good thing is you may use XNA documentation and samples to get yourself started.

*The ANX.Framework is a framework which is source compatible with Microsoft's XNA framework 4.0. Source compatibility means, that you can "translate" a XNA game project to be a ANX game project by simply replacing all namespaces from Microsoft.XNA.Framework to ANX.Framework. The advantage of ANX is simply that you are able to swap the RenderSystem, the InputSystem and the AudioSystem. By swapping this systems you are no more limited to run your game using DirectX9 which XNA is using. ANX comes with a DirectX10 RenderSystem as a default. A DirectX 11, DirectX 11.1 and a OpenGL 3 RenderSystem is currently in development. This will make it possible to run your games on Linux and other plattforms which are supported by OpenGL etc. simply by swapping the namespaces.*

~ Codeplex site: http://anxframework.codeplex.com/

It is still under heavy development but most of the basic XNA features are implemented.
> 1 votes

# Answer
I suppose that XNA vs the world ( aka OpenGL and DirectX as real alternatives ) can easily look like a religious question especially when targeting a new developer, but i find that the right adjective for XNA is *simplified* and not *powerful*.

XNA is a subset, someone can argue that, but in the end is just a subset of DirectX, this framework is well suited for small project and not for serious gaming.

You have also to consider one aspect both C# and XNA ( or DirectX ) are technologies that are available only on Microsoft platform, this is important to stress, my point is that today Microsoft is not a big player in the industry, if you consider on how many platform you can make games, including desktop and mobile, you will easily realize that Microsoft is simply struggling in the market and more and more Microsoft will see its own market share resizing to a smaller size.

I personally believe that C# and DirectX/XNA will have a really hard future, i think that during the lifetime cycle of Windows 8 many many people will realize how bad their choice was about the language to adopt as main language, C++ is much more suitable for the performance, for the business and for cross-platform compatibility.

I do not want to influence anyone, just propose my idea, my points are:

* Microsoft will become a small player in the future, even smaller than it actually is ( even Bill Gates has been selling a huge part of its own Microsoft shares before the Windows 8 launch, we are talking about 20.000.000$ in shares and this is only what was happening in July, just in 1 month(!) )
* The gaming on MAC and Linux is not a rare thing anymore, even Steam will launch its service for Linux by the end of the year
* C# is a weird creature, and without spending too much words about this, is just for Microsoft platforms and doesn't offer cutting edge performance honestly, i don't see the point about adopting a language that is for 2-3 devices and doesn't even have a real edge on performance
* if you choose C++ you will program almost anywhere, desktop and mobile, also the real developers just use C++ for the biggest part, you can also program on the platform where C# is available, Xbox, PC and Windows Phone 8 ( from WP8 Microsoft will support C++ on their phones ).
* Microsoft has one of the worst royalties system ever, most of the times you don't even have a chance to know how much you are selling.

If you ask me the language for you is the C++ because learning C# or C++ is the same thing for a newbie, it's always a new language, but what the C++ can offer the C# can only dream about it; you also will develop a real know-how that you can spent on as many platform as you want and on all levels, from small games to serious development.

The last part about what framework you are supposed to learn, again, i will go for the most business friendly and the best choice as an investment these days is OpenGL with a programmable pipeline approach and this means OpenGL 3.0 and above.

I should also remark the fact that OpenGL is a rendering technology when DirectX is a complete framework oriented to all the main aspect about multimedia, but the thing is that today there are frameworks available for every purpose that you have in mind, most of them are free and really well tested, with an history of several years of testing and they are really reliable, they are also cross-platform and with a really *good license* most of times if not in every case.

As soon as the OEMs will stop installing Windows on their machines, and most of them already do that in practice, just see the market share percentage of Windows Phone, the entire Microsoft ecosystem will collapse and just looking at what is now, it's not that good anymore. Look at the marketplace, Microsoft has a marketplace by years until now and there is absolutely nothing, it's empty compared to what you can find on the marketplaces of the competitors. Look at the technologies, C# lives thanks to the web development, if it was for Windows Phone 8 development it were dead by years; Silverlight is a big flop, find 1 technology that Microsoft has introduced recently and see how good is performing on the market, even Internet Explorer have lost its throne.

I know that most of the people that will read this, especially advanced and senior developers, will get this as a ranting against Microsoft, but when even the founder doesn't believe in its own Corporation that is performing so badly before an important launch, that is losing important assets and presence on the market on every field, i think that you just have to consider the facts.

recap: go for C++ and OpenGL 3.0+ and you can code anywhere.
> -11 votes

---
Tags: xna
---


# Question
Title: Design Pattern for Social Game Mission Mechanics
When we want to design a mission sub-system like in the The Ville or Sims Social, what kind of design pattern / idea would fit the best? There may be relation between missions (first do this then this etc...) or not. What do you think sims social or the ville or any other social games is using for this?

I'm looking for a best-practise method to contruct a mission framework for tha game. How the well-known game firms do this stuff for their large scale social facebook games?

* Giving missions to the players and wait players to complete them. when they finished the missions, providing a method to catch this mission complete events considering large user database by not using server-side not so much to prevent high-traffic / resource consumption.

how should i design the database and server-client communication to achive this design condidering this trade-off.

# Answer
> 2 votes
There is not one silver bullet. You can use an event driven paradigm:

* Whenever something happens in your game that can be relevant for a quest, raise an event.
* Define classes for your quests with event listeners to react to these events.
* Store the currently active quests (and their status and parameters) in a database
* When initializing your game state, also initialize quest objects for each active quest of the player
* Register the quest objects' event listeners at your game state object

For example:

```
class Character {
    function heal(amount) {
        this->hp += amount;
        event = new HealingEvent(this, amount);
        raise event;
    }
}

class PracticeYourHealingSpellQuest extends Quest (extends ActiveRecordBaseClass) {
    // property healingDone is provided by a database record
    function reactToHealingEvent(event) {
        this->healingDone += amount;
        if(this->healingDone > 1000) {
            this->state = completed;
        }
        this->update();
    }
    function registerAtCharacter(character) {
        character->onHealingEvent = this->reactToHealingEvent
    }
}

class GameController {
    function init() {
        character = DB->findMeACharacter
        quests = DB->findMeActiveQuests(character->id)
        foreach(quests as quest) {
            quest->registerAtCharacter(character);
        }
    }
}

```

Don't worry about database performance. Your facebook app will never have enough users playing at the same time to make this approach unviable with MySQL. (If it does, you can still use caching techniques, parallel database servers, etc.) The most important thing is to have a quest system that is flexible and that has all the quest-related code where it belongs, namely in quest classes.

# Answer
> 0 votes
Your question is general enough that there's probably no definitive answer to it. I think you could find the answer in the book Game Coding Complete though. It describes a process manager that allows you to chain processes together, so that once you achieve a step in a mission the next one would automatically activate. They discuss how you could even make a C# tool that would let you drag and drop to create mission trees in this manner. Might be the kind of architecture you're looking for.

---
Tags: game-design, flash, actionscript, social
---


title: How do I play music at half speed?

text:
# Question
Title: How do I play music at half speed?
I'd like to slowdown music playback, say at half speed. I'm currently using SDLmixer. I assume I'd need to tell SDL that I have a 44KHz music and want to stream it at 22KHz, but when I pass in 22Khz it seems it re-samples my audio and plays at normal speed.

Does anyone know how to do that, or any lib that supports it? I'm looking for free libs that allow me a commercial license (so no FMOD)

Thanks in advance.

# Answer
> 2 votes
The approach chosen would depend on whether you want to retain pitch or not, but I'd probably go for a third party library with an acceptable license like SoundTouch (LGPL v2.1) to apply a tempo adjustment to your input signal.

That'd allow you to have a bit more choice in the exact tempo you want instead of "double" or "half". It also seems like it is capable of doing both tempo and pitch adjustments independently if you want to play around with pitch as well.

---
Tags: c++, sdl, audio, music
---


title: How are 8/16 bit sprites created?

text:
# Question
Title: How are 8/16 bit sprites created?
I already found this question, but it only talks about the kind of software used - not the actual methods. Were they drawn at a high resolution first and then shrunk down? Or did you just zoom way in? Do you do a vague outline first, then make it more detailed? How was the coloring done? And when you have to do long animations, do you hand draw each frame, or are there tools to help automate the process? Or do you just copy paste the basic sprite and only change the moving parts?

Etc.

# Answer
Pixel art is its very own art form. There are several tutorials on the net about it, but basically you plot one pixel at a time.

Here's a few tutorials, but I'm sure you can google for more:

There are some tools for sprite animation creation, but those are relatively recent; back then people just drew the animation frames with deluxe paint (or similar).
> 10 votes

# Answer
Gas13 has some guides to drawing classic pixel art written down. These are really general theory stuff- he's not going to hold you by the hand in step-by-step tutorials, but instead explain the principles on what makes a good game sprite.

I would start with this following page:

http://gas13.ru/v3/tutorials/sywtbapa\_almighty\_grass\_tile.php

Even something as mundane as creating a grass tile can be improved in detail, and then you can learn how to move on draw more complex objects with depth and definition, using a limited color palette.
> 2 votes

---
Tags: graphics, sprites, art
---