# Question
Title: Why does switching to fullscreen produce this graphical glitch?
I followed this tutorial and things were looking good. However, when switching to Fullscreen from 800x600 using alt-enter, I noticed an error in debug output:

```
DXGI WARNING: IDXGISwapChain::Present: Fullscreen presentation inefficiencies incurred due to application not using IDXGISwapChain::ResizeBuffers appropriately, specifying a DXGI_MODE_DESC not available in IDXGIOutput::GetDisplayModeList, or not using DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH

```

So I followed MSDN's article about DXGI and fullscreen. I noticed a few things:

1. Implementing the MSDN article's code as is did not remove the error. `WM_SIZE` was being called in the function ran through with no errors thrown.
2. Reading more, I added a section at the end (after viewport) to include `swapChain->ResizeTarget`. This didn't help.
3. Normally, my `swapChainDesc.flags` is set to 0. I tried setting it to `DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH` as the error suggests, but then `WM_SIZE` is *never* sent to my application (with alt-enter), so the function to resizebuffers is never called.
4. Implementing the MSDN code also caused switching to fullscreen to throw off my depth buffer(...I think). What happens is all models are drawn regardless of whether or not they are behind another model. Upon switching back to windowed mode via alt-enter, this behavior remains.

I've spent around 20 hours over the course of the week trying to figure out this fullscreen transition to no avail. I realize I could just run the `Initialize()` function for the D3D class of Rastertek's and toggle the `fullscreen` value, but that seems inefficient.

My code (I tried condensing it by removing error handling):

```
bool D3D::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hWnd, bool fullscreen, float screenDepth, float screenNear)
{
    HRESULT result;
    IDXGIFactory* factory;
    IDXGIAdapter* adapter;
    IDXGIOutput* adapterOutput;
    unsigned int numerator, denominator;
    int error;
    DXGI_SWAP_CHAIN_DESC swapChainDesc;
    D3D_FEATURE_LEVEL featureLevel;
    ID3D11Texture2D* backBufferPtr;
    D3D11_TEXTURE2D_DESC depthBufferDesc;
    D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
    D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;
    D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
    D3D11_RASTERIZER_DESC rasterDesc;
    D3D11_VIEWPORT viewport;
    float fieldOfView, screenAspect;
    D3D11_BLEND_DESC blendStateDesc;

    // Enumerate Display Modes and choose appropriate Refresh Rate
    CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
    factory->EnumAdapters(0, &adapter);
    adapter->EnumOutputs(0, &adapterOutput);
    adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
    displayModeList = new DXGI_MODE_DESC[numModes];
    adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);

    // Iterate through Display Modes. displayModeList is a member variable for later use.
    GetRefreshRate(screenWidth, screenHeight, numerator, denominator);

    adapterOutput->Release();
    adapterOutput = 0;

    adapter->Release();
    adapter = 0;

    factory->Release();
    factory = 0;

    // Swap Chain Description
    ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));
    swapChainDesc.BufferCount = 1;
    swapChainDesc.BufferDesc.Width = screenWidth;
    swapChainDesc.BufferDesc.Height = screenHeight;
    swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

    // I'm going to assume VSYNC is enable for now
    swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
    swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;

    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    swapChainDesc.OutputWindow = hWnd;
    swapChainDesc.SampleDesc.Count = 1;
    swapChainDesc.SampleDesc.Quality = 0;
    swapChainDesc.Windowed = true;
    swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
    swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

    // Regarding Flags, I've mentioned above that when not set to 0, WM_SIZE is not called when ALT-ENTER is pressed.
    //swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
    swapChainDesc.Flags = 0;

    featureLevel = D3D_FEATURE_LEVEL_11_0;

    // Create Swap Chain, D3D Device and Device Context
    D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &swapChain, &device, NULL, &deviceContext);
    swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
    device->CreateRenderTargetView(backBufferPtr, NULL, &renderTargetView);
    backBufferPtr->Release();
    backBufferPtr = 0;

    // Set up Depth and Stencil Buffers
    ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
    depthBufferDesc.Width = screenWidth;
    depthBufferDesc.Height = screenHeight;
    depthBufferDesc.MipLevels = 1;
    depthBufferDesc.ArraySize = 1;
    depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    depthBufferDesc.SampleDesc.Count = 1;
    depthBufferDesc.SampleDesc.Quality = 0;
    depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
    depthBufferDesc.CPUAccessFlags = 0;
    depthBufferDesc.MiscFlags = 0;

    // Create Depth/Stencil Buffer using description
    device->CreateTexture2D(&depthBufferDesc, NULL, &depthStencilBuffer);

    // Create Stencil State
    ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
    depthStencilDesc.DepthEnable = true;
    depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
    depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
    depthStencilDesc.StencilEnable = true;
    depthStencilDesc.StencilReadMask = 0xFF;
    depthStencilDesc.StencilWriteMask = 0xFF;

    // Stencil operation if Pixel is Front-Facing
    depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
    depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

    // Stencil operation if Pixel is Back-Facing
    depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
    depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

    // Create the Depth Stencil State
    device->CreateDepthStencilState(&depthStencilDesc, &depthStencilState);
    deviceContext->OMSetDepthStencilState(depthStencilState, 1);

    // Similar steps for Disabled Depth Stencil State - Omitted

    // Create Blend State - Omitted

    // Depth Stencil View Description and Creation - Omitted
    // Bind Depth Stencil and Render Target View to the Output Render Pipeline
    deviceContext->OMSetRenderTargets(1, &renderTargetView, depthStencilView);

    // Configure Rasterizer
    rasterDesc.AntialiasedLineEnable = false;
    rasterDesc.CullMode = D3D11_CULL_BACK;
    rasterDesc.DepthBias = 0;
    rasterDesc.DepthBiasClamp = 0.0f;
    rasterDesc.DepthClipEnable = true;
    rasterDesc.FillMode = D3D11_FILL_SOLID;
    rasterDesc.FrontCounterClockwise = false;
    rasterDesc.MultisampleEnable = false;
    rasterDesc.ScissorEnable = false;
    rasterDesc.SlopeScaledDepthBias = 0.0f;

    device->CreateRasterizerState(&rasterDesc, &rasterState);
    deviceContext->RSSetState(rasterState);

    // Setup and Create Viewport
    viewport.Width = (float)screenWidth;
    viewport.Height = (float)screenHeight;
    viewport.MinDepth = 0.0f;
    viewport.MaxDepth = 1.0f;
    viewport.TopLeftX = 0.0f;
    viewport.TopLeftY = 0.0f;

    deviceContext->RSSetViewports(1, &viewport);

    // Create various Matrices
}

```

And the `ToggleFullscreen` function (`WM_SIZE` calls this, sending `LPARAM`):

```
bool D3D::ToggleFullscreen(LPARAM lParam)
{
    if (swapChain)
    {
        unsigned int numerator, denominator;

        OutputDebugString(TEXT("Resizing\n"));

        deviceContext->OMSetRenderTargets(0, 0, 0);
        renderTargetView->Release();

        swapChain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0);

        ID3D11Texture2D* backBufferPtr;

        swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&backBufferPtr);

        device->CreateRenderTargetView(backBufferPtr, NULL, &renderTargetView);

        backBufferPtr->Release();
        backBufferPtr = 0;

        // MSDN list a 0 for depthStencilview, so I figured it would make sense to call this the same way that I originally initialize.
        // With a 0, models are drawn when switched to Fullscreen, but the depth buffer seems foobarred. With depthStencilView (member pointer, not freed until Shutdown()), NOTHING displays
        // in Fullscreen, but when ALT-Enter to return to windowed, things are displaying properly.
        deviceContext->OMSetRenderTargets(1, &renderTargetView, depthStencilView);

        D3D11_VIEWPORT vp;
        vp.Width = LOWORD(lParam);
        vp.Height = HIWORD(lParam);
        vp.MinDepth = 0.0f;
        vp.MaxDepth = 1.0f;
        vp.TopLeftX = 0;
        vp.TopLeftY = 0;

        deviceContext->RSSetViewports(1, &vp);

        // This whole last section was added because I thought perhaps the correct Refresh Rates were not apparent the SwapChain, as the program is initialized in Windowed mode
        // numerator/denominator are passed By Ref
        GetRefreshRate(LOWORD(lParam), HIWORD(lParam), numerator, denominator);

        DXGI_SWAP_CHAIN_DESC dscd;
        DXGI_MODE_DESC dmd;

        swapChain->GetDesc(&dscd);
        dmd = dscd.BufferDesc;

        dmd.RefreshRate.Numerator = numerator;
        dmd.RefreshRate.Denominator = denominator;

        swapChain->ResizeTarget(&dmd);
    }

    return true;
}

```

# Answer
> 2 votes
The problem with the models overlapping after `ToggleFullscreen()` is that the Depth Stencil View also needs to be recreated when the back buffer is resized. I made these modifications to `ToggleFullscreen()`:

```
...
D3D11_TEXTURE2D_DESC depthBufferDesc;
D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;

depthStencilView->Release();
depthStencilBuffer->Release();

ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
depthBufferDesc.Width = LOWORD(lParam);
depthBufferDesc.Height = HIWORD(lParam);
depthBufferDesc.MipLevels = 1;
depthBufferDesc.ArraySize = 1;
depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthBufferDesc.SampleDesc.Count = 1;
depthBufferDesc.SampleDesc.Quality = 0;
depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthBufferDesc.CPUAccessFlags = 0;
depthBufferDesc.MiscFlags = 0;

// Create Depth/Stencil Buffer using description
device->CreateTexture2D(&depthBufferDesc, NULL, &depthStencilBuffer);

ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
depthStencilViewDesc.Texture2D.MipSlice = 0;

device->CreateDepthStencilView(depthStencilBuffer, &depthStencilViewDesc, &depthStencilView);

deviceContext->OMSetRenderTargets(1, &renderTargetView, depthStencilView);

// Set up Viewport as above

```

I still get the DXGI Error above, but as Tordin mentioned, it may just be a non-issue error, as I filled the window with models until my Frame Rate lowered to something acceptable, then switched to FullScreen and didn't notice any difference.

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


# Question
Title: Should I be using Reach or HiDef profile if I have large spritesheets?
I'm working on a platformer in monogame, that I want to use a large number of sprites for making up items and objects in the background.

The main spritesheet I've created is 4095x3734, when I tried to convert it into xmb using XNA Content Compiler, I received an error that Reach Profile only supports 2048x2048.

I've read that I can use HiDef which will support 4096x4096, which will be sufficient for my requirements, but I am a bit concerned about what the potential pitfalls will be - will less graphics cards support the game? What about Mac/Linux? Does monogame fully support HiDef?

In short, I would like to know if there are any cons of using HiDef and if using multiple 2048x2048 spritesheets would perhaps be better - and how much of a performance hit it would be.

# Answer
> 0 votes
You've pretty much hit on the major cons, I think. Platform availability would be the major one (the documentation describes the kind of hit you'd be taking).

If you need any of the platforms that you'd be losing by using the higher-powered profile, splitting your textures into multiple smaller options is a good way to stay on the lower-end profile.

It will result in more texture state changes, which have a negative performance impact, but it might also result in better use of GPU memory since you aren't loading such massive textures all the time, potentially. It's not very clear cut how the performance changes will fall out, and it's going to depend heavily on the rest of what your game does.

However, it certainly won't be debilitating so I would recommend you split the textures into smaller ones and continue to use the low-end profile, unless you really don't care about the devices you'll lose otherwise.

---
Tags: xna, sprites, monogame, spritesheet
---


# Question
Title: How can I list files in a folder from JavaScript in cocos2d-x?
I need to list all the files in the `res` folder from a JavaScript script in cocos2d-x. What would be the most efficient way to do this?

To keep compatibility with Cocos2d-html5 a JavaScript-only solution is most desirable.

# Answer
> 1 votes
Javascript doesn't have access to the filesystem. This is for security purposes.

However, HTML5 does allow access to a sandbox filesystem. Cocos2D has an implementation of this sandbox access, but it doesn't appear to be official support. It's not too likely that utilizing this sandbox will be something that's cross platform. In this situation, you'll likely have to create platform specific code.

# Answer
> 0 votes
Not sure if this will help, but in the following this file: http://cocos2djs.org/demos/tile-maps I found this construct:

```
var map = new TMXTiledMap(
    { file: path.join(__dirname, '../resources/TileMaps/iso-test.tmx')})

```

The github site also has tutorials on using javascript for cocos2d

---
Tags: javascript, cocos2d-x, cocos2d-x-js
---


# Question
Title: How do I ensure that perspective and orthographic projection matricies show objects at the same size on the screen?
I am working on a 3d scene editor and would like to show the scene in orthographic projection. My current problem is that I am not sure how to calculate the orthographic projection matrix such that the objects do not appear at a completely different size on the screen.

I currently have the following 2 functions for calculating the camera projection matrix.

```
Matrix4.createPerspective = function(fov, aspect, near, far, result) {
    if (typeof result === 'undefined') {
        result = new Matrix4();
    }

    var ymax = near * Math.tan(fov * Math.PI / 360);
    var ymin = - ymax;
    var xmin = ymin * aspect;
    var xmax = ymax * aspect;

    Matrix4.createFrustum(xmin, xmax, ymin, ymax, near, far, /*out*/ result);

    return result;
};

Matrix4.createOrthographic = function(left, right, top, bottom, near, far, result) {
    if (typeof result === 'undefined') {
        result = new Matrix4();
    }

    var re = result.elements;
    var w = right - left;
    var h = top - bottom;
    var p = far - near;

    var x = ( right + left ) / w;
    var y = ( top + bottom ) / h;
    var z = ( far + near ) / p;

    re[0] =2/w;  re[4] = 0;   re[8]  = 0;   re[12] =-x;
    re[1] = 0;   re[5] =2/h;  re[9]  = 0;   re[13] =-y;
    re[2] = 0;   re[6] = 0;   re[10] =-2/p; re[14] =-z;
    re[3] = 0;   re[7] = 0;   re[11] = 0;   re[15] = 1;

    return result;
};

```

And this is how they are being used:

```
    updateProjectionMatrix: function(entity) {
        var camera = entity.getComponent('Camera');
        if (camera.isDirty()) {
            camera.aspect = camera.width / camera.height;
            if (camera.isOrthographic()){
                Matrix4.createOrthographic(
                    0,
                    camera.width,
                    0,
                    camera.height,
                    camera.near,
                    camera.far,
            /*out*/ camera._projectionMatrix);
            } else {
                Matrix4.createPerspective(
                    camera.fov,
                    camera.aspect,
                    camera.near,
                    camera.far,
            /*out*/ camera._projectionMatrix);
            }
        }
    },

```

Here is an example of what I am trying to accomplish inside Blender (F5 toggles between Ortho and Perspective). Note that both cubes appear to be about the same size on the viewports:

# Answer
First of all, your `createPerspective` function doesn't look quite right - compare the formulas used for `gluPerspective`.

If you want to use the same view matrix for both cameras, then when you set up the orthographic matrix, instead of using `0, camera.width, 0, camera.height` you probably want `-0.5*camera.width, 0.5*camera.width, -0.5*camera.height, 0.5*camera.height`. This will keep the view centered around the camera position, instead of putting lower-left corner of the view at the camera position.

You may also need to use different near/far values for the ortho camera, depending on whether you want the ortho view to show geometry behind the camera (which would require a negative near plane value).

Then, what you need to do next is calculate `camera.width` and `camera.height` based on the currently selected/focused object when you switch to orthographic mode. You want those values to represent the width and height of the frustum at the depth (distance along camera space z-axis) of the selected object.

If you use a `gluPerspective`-style perspective matrix, then the \[0, 0\] and \[1, 1\] components of the matrix represent 2/width and 2/height respectively, at a depth of 1.0 units from the camera. The width and height of the frustum scale linearly with depth, so all you would need to do is multiply them by the depth of the focused object:

```
objectDepth = dot(objectPos - cameraPos, cameraViewVector);
camera.width = (2.0 / perspectiveMatrix[0]) * objectDepth;
camera.height = (2.0 / perspectiveMatrix[5]) * objectDepth;

```

Of course, you can also recompute the perspective matrix components using the FOV and aspect ratio if necessary.
> 4 votes

---
Tags: camera, projection, viewport
---


title: Spherical / Relative Gravity

text:
# Question
Title: Spherical / Relative Gravity
I'm working on an Ogre3D + Bullet project that involves planets in a solar system. For all intents and purposes, I'm looking to give each planet it's own gravity sphere.

So far, all I've found are ways to change the "general" gravity `Vector3` for the entire scene, but that's it.

While I'd hope to add air friction and other physics later on, for now I just want "prioritized" gravity, like in this video.

You'll note that the floor in the video has gravity, but when he jumps near the sphere, he is attracted to it sphere instead. That's exactly what I'm going for.

The video is very low quality and doesn't explain how any of it is working, besides the fact that it uses Ogre3D and Bullet.

The planets themselves are on pre-generated paths around the Sun - I'm not looking to apply "real" physics to the solar system itself; just for the planets themselves and eventually "generated gravity" for ships in space.

# Answer
Well I don't think that Bullet physics support multiple attractors out of the box, even though in bullet you can set the gravity per object, Bullet still assumes the objects are being simulated under a global gravity value set for the entire scene, in other words it assumes that the objects gravitational force is neglected in comparison to the planet/surface they dwell on, which is clearly not the case of real planets.

### The Solution

Never the less, I can recommend you set the global gravity to 0.0 and simulate planets' gravity using Newton's law of universal gravitation based on each planet's mass, now when any planet is within the other planets gravitational distance you can calculate the force, which can be done using a `btSphereShape` collider.

After you calculate the gravitational force for each planet you can apply it's gravity on other planets using `btRigidBody::applyForce`.

### The problem though...

Well if you ever heard of the **three-body problem** you will know that calculating gravitational force between three planets is particularly unsolvable (or hard to solve?) , quoting from Wikipedia:

> In its traditional sense, the three-body problem is the problem of taking an initial set of data that specifies the positions, masses and velocities of three bodies for some particular point in time and then determining the motions of the three bodies, in accordance with the laws of classical mechanics (Newton's laws of motion and of universal gravitation).

This will make you approximate the actual motion of the planets rather than calculate the exact one. By reducing the problem to one static body, and calculating the motion of the other body. Then you will find that the motion of a body under gravity is an ellipse.

But that's not a huge problem, since you will get a fine approximation, quoting from this article

> But even with just mechanical pencil and paper there are cheats. For example, although there are more than three bodies in the solar system (the Sun, eight planets, dozens of moons, and millions of asteroids and comets), almost everything behaves, roughly, as though it were in a two body system. Basically, this is due to the pronounced size differences between things. As far as each planet is concerned, the only important body in the rest of the universe is the Sun. To get some idea of why; the Sun pulls on the Earth about 200 times harder than the Moon, and about 20,000 times harder than Jupiter. Nothing else even deserves a mention. So, if you want to calculate the orbits of all the planets, a “2-body approximation” will get you more than 99% of the way to the right answer.
> 3 votes

# Answer
One way you can do this is to setup a sphere ghost collider and detect when something collides with it. Then you can change the gravity vector to point towards the centroid of your planet for anything that collides with it that you want gravity to affect.

A much harder way to do this would be to concoct your own constraint. The constraint would be very similar to a soft distance constraint so the jacobian and implementation would be very similar to a standard distance constraint. However, the error correction would have to be calculated differently.

A standard distance constraint uses the distance from center as an error, instead you would want a distance from the affect horizon (the spherical boundary of where gravity stops affecting things). You would probably also have to increase the frequency of the oscillator as the error grows larger to mimic actual gravitation equations.

The benefit of the "harder" way would be you can probably get rid of the need to do a lot of collision detection, which is awesome. The easier way (ghost collider) will have the issue of tons of things being attracted to a large planet. This is a nightmare for the dynamic AABB broadphase, as the objects all piling towards the target centroid will create a closer and closer to N^2 broadphase lookup the closer they get to each other.
> 4 votes

---
Tags: ogre, bullet-physics
---


# Question
Title: breakout game, computing optimal ricochet angle of a ball to get to a certain point
perhaps the title isn't clear so here is an explanation with a picture to better express my question

Consider the following breakout clone game

<sub>(source: ludumdare.com)</sub>

where the game is rigged to change the ricochet angle according to some parameters

Suppose the ball was to hit one of these blue bricks, finding the angle at which the ball should ricochet to go toward any point below the bricks using trigonometry should be trivial and easy.

My question however, is if we have the following setup

How would I got about finding the optimal angle to ricochet from the collision point (circled in red) to get to a certain location (green dot for example)

The path should ricochet off of multiple points to get there, obviously, I'm just not sure how to go about it.

Any math guru who can help me out? Thanks!

# Answer
Depending on how often you can have a "rigged" bounce, an incremental solution might be possible.

For this example, I'll assume that:

* Collisions with the playing field boundary are always normal (angle in = angle out)
* Collisions with blocks can be 100% rigged whenever needed (angle out = arbitrary)

Then each time you collide with a block, check whether you have an unimpeded path to the target point without touching another block (but collisions with the boundaries are permitted). If such a path exists, bounce that way.

A fast way to check this is to mirror your playing field and look for a straight-line path to any of the target point's reflections:

In the example you've given, there's no such path - even the best option hits the green row.

So, as a fallback, we just aim for a block that gets us a better view and let the simulation proceed. When we hit that block, this code runs again, and hopefully finds a path directly to the target. If not, it gets incrementally closer each time.

This way you don't need to account for the erosion of the playing field in your algorithm, since you're only ever looking one block impact ahead.

There are a lot of metrics you could use to select this fallback target. You could...

* ...use the mirroring trick above to identify all blocks reachable from both the source point and the target point, and pick a block from the intersection of those two sets. (Guaranteed to reach your target after hitting this block, if the intersection is non-empty)
* ...select the block visible from the current one that is closest to the target point.
* ...continue bouncing normally (angle in = angle out) waiting for one that permits a boundary-bounce-only path. (Makes rigged bouncing less obvious, but not guaranteed to succeed)
* ...always just bounce toward the reflection of the target point that's closest to lying on the normal bounce vector (angle in = angle out), whether it gets you there or not. This applies a mild bias to all block bounces so it's consistent, and should usually prevent the ball from doing something obviously rigged like reversing course. ;)
> 4 votes

# Answer
You could do Raytracing. Just send a number of rays in all directions and choose the ray that reaches your target. As parameters, you should think of the reasonable number of rays to shoot, the maximum distance that a ray should travel before discarded as not adequate and the addition of some little randomness to the starting angles of the rays, so you can restart if no ray reaches the target location. To get the best numbers you should profile and test your application. It is important to note that all rays can be computed in parallel.

The path of modelling this problem mathematically is harsh, since the restrictions of the problem change depending on the bounces that are imposed to the ray.
> 1 votes

# Answer
Just do it backwards.

Assuming you don't care about "realistic bounces" (you said *rigged*), do the following:

* Pick # bounces to use. (Here I've used 6 bounces and 7 line segments)
* pick wall hit order (here i picked BLTRLT(Goal))

Then:

```
For each wall hit in the hit order:
    pick a random spot on the wall
    find the line segment from current ball pos to that goal pos
    travel along that line segment

```

If you construct a travel path based on this, you can reach any final destination point.

The game will be really wonky if the bouncing doesn't happen in some logical order, but hey.
> 0 votes

---
Tags: mathematics, trigonometry
---


# Question
Title: Keep Mini map static after rotating / zooming with camera
Hi I am making a 2D game, where the Camera is able to rotate / zoom in or out on the camera focus (the player usually).

However my game also contains a mini-map, and so far whenever I have to rotate / zoom my camera the mini-map rotates and zooms accordingly. This behaviour was expected, but now I am a little stuck on "un-doing" the changes the view transformation has on my mini-map. What I want to happen is to essentially keep my mini-map statically in the same position throughout the game no matter how the camera rotates or zooms.

I am extremely rusty with my linear algebra / 3D transformations but I have tried the following...

My first thought was, I thought all I had to do was to transform the mini-map origin point with the view matrix, then undo the scaling of the zoom against the mini-map width / height. The zooming was fixed, but the mini-map still rotated so this did not work.

My second try, I remembered to undo the change of a matrix, I would have to multiply the transform by its inverse. So I tried to calculate the inverse matrix, however the determinant of the view matrix was 0, so I could not find an inverse.

Ok... well I guess I'll just see if I can get the rotation down, since I got the zoom to work... So I transformed my mini-map origin by the inverse rotation matrix applied by the view matrix... The mini-map is rotating now, but is not staying in the fixed position I was hoping for.

I was wondering, if anyone here can give me a push in the right direction, or a hint towards a more elegant solution overall. If people would like more information I can upload images, show code... But what I wrote above is exactly how my code would look.

Thanks for any help!

# Answer
No, usually you don't undo transform by applying inverse. Because precision errors love to accumulate. Instead, either precalculate desired transform and set it directly, or reset current transform to identity and start over.

This answer is api-agnostic. If there is way to manipulate current transform, then should be also way for resetting it. (I am not familiar with XNA, sorry.)
> 2 votes

# Answer
You would be able to render your minimap to a texture (or alternatively use a pre-existing texture).

This article helps with learning RTT: http://rbwhitaker.wikidot.com/render-to-texture

Once you have the texture, you can simply draw the minimap as a standard SpriteBatch.
> 1 votes

---
Tags: xna, camera, rotation, matrix, transformation
---


# Question
Title: Would seam carving/liquid rescale make changing aspect ratios easier?
Seam carving is an algorithm which allows for resizing images without major distortions. I think it might help to make games which would adapt to different aspect ratios/resolutions much easier. But am I right?

You can watch this presentation to see how seam carving works for videos.

# Answer
> 2 votes
By quickly looking at the algorithm it seems more suited to image/video processing.

The problem with such image processing based techniques is that they are highly analytical, and they are more likely to leave some artifacts that might not be suitable for games due to the dynamic nature of the games, unlike movies or images were the data is previously known. This is even mentioned in the article, which makes it not so suitable for games. Quoting from Wikipedia:

> * The algorithm may need user-provided information to reduce errors. This can consist of painting the regions which are to be preserved.
> With human faces it is possible to use face detection.
> * Sometimes the algorithm, by removing a low energy seam, may end up inadvertently creating a seam of higher energy. The solution to this is to simulate a removal of a seam, and then check the energy delta to see if the energy increases. If it does, prefer other seams instead.

Other reasons not to use such approach is that it's more likely to be expensive performance wise, but this needs to be proved by actually testing it. Keep in mind that games use much different techniques to output for multiple resolutions that usually don't use traditional image processing techniques, as they can usually natively render to a render target (or multiple) with the target resolution. Think of traditional image processing techniques as the ones require analyzing pixels in color domain or frequency domain. I said usually because some Anti Aliasing aliasing techniques do some analysis on the image. Even though I don't know how widely they are used in games.

# Answer
> 0 votes
No.

* Seam carving makes no sense for dynamic images. It is for static images, by design. If you blindly apply it to every frame of video, you will get different unrelated results on every frame. Objects on that video will look jittering around and cause nausea.
* It is useful when altering raster data is cheaper than reproducing image with different composition / angle / whatever. In games, every new frame is rendered at runtime, so reproducing frames with new FOV aspect ratio and GUI layout is not quite an issue. Also adjusting some variables in calculations that will happen anyway is much cheaper than involving new shader pass that requires whole image analyzis.
* It is based on assumption that pixels are comparable by how much they are interesting / important for perception, and seams of most useless pixels may be thrown out. This approach distorts screen-space distances between objects. It is fine for illustrations, but not acceptable in games, because game *wants* player to know these distances, otherwise it will be lying about actual game situation.
* In lot of games, gameplay objects are bound to GUI. For example, figures in chess. Image distortion may not be tolerated, because it will just ruin GUI.

---
Tags: graphics, resolution, aspect-ratio
---


# Question
Title: Creating Seamless Perlin Noise Across Faces of Cube
I am writing a planet renderer and have stumbled into a problem that I cannot solve. I am generating heightmaps in a glsl pixel shader. These heightmaps are generated for every quad in the quadtree that the planetary sphere is built on. The sphere is a cube transformed by the equations found here. The way I am generating a point to be inputted into the noise function in the shader is shown here:

```
vec2 coords = vec2((gl_FragCoord.x - 0.5) * m_Scale , (gl_FragCoord.y - 0.5) * m_Scale)+m_Offset;
vec2 position = vec2(coords.x,coords.y);
vec3 noiseInput;

 if(m_t == 1){

 noiseInput = vec3(spherize(vec3(position.x, 0.0, position.y) + m_faceOffset))/m_worldSize;
}else if(m_t == 2){

noiseInput = vec3(spherize(vec3(position.x, position.y, 0.0) +  m_faceOffset))/m_worldSize;

}else if(m_t == 3){

noiseInput = vec3(spherize(vec3(0.0, position.x, position.y) +   m_faceOffset))/m_worldSize;

}

```

Here "m\_Scale" is the length of the quad's edges divided by the lengths of one of the root node's sides. m\_Offset is a variable which offsets the quad from the origin. m\_worldSize represents the planet's radius. m\_faceOffset is the variable which translates the quad to it's correct face of the cube (faceIndex = faceOffset):

```
if(c.face.equals(faces.TOP)){
                    c.faceIndex = new Vector3f(nhsize, hsize, nhsize);
                }else if(c.face.equals(faces.BOTTOM)){
                    c.faceIndex = new Vector3f(nhsize, nhsize, nhsize);
                }else if(c.face.equals(faces.FRONT)){
                    c.faceIndex = new Vector3f(nhsize, nhsize, hsize);
                }else if(c.face.equals(faces.BACK)){
                    c.faceIndex = new Vector3f(nhsize, nhsize, nhsize);
                }else if(c.face.equals(faces.RIGHT)){
                    c.faceIndex = new Vector3f(hsize, nhsize, nhsize);
                }else{
                    c.faceIndex = new Vector3f(nhsize, nhsize, nhsize);
                }

```

where hsize is the radius of the planet and nhsize is the radius negated. Finally, m\_t describes which face of the cube the quad is supposed to be on:

```
if(q.face.equals(QuadMesh.faces.TOP.toString()) || q.face.equals(QuadMesh.faces.BOTTOM.toString())){
                    t = 1;
                    }
                if(q.face.equals(QuadMesh.faces.FRONT.toString()) || q.face.equals(QuadMesh.faces.BACK.toString())){
                    t = 2;
                    }
                if(q.face.equals(QuadMesh.faces.RIGHT.toString()) || q.face.equals(QuadMesh.faces.LEFT.toString())){
                    t = 3;
                    }

```

"spherize" is the function which transforms a point on the cube to a point on the sphere:

```
     denom1 = hWorldSize * hWorldSize * 2f;
 denom2 = hWorldSize * hWorldSize * hWorldSize *hWorldSize * 3f;

     vec3 spherize(vec3 v){
float x = (v.x * (sqrt(1.0-((v.y*v.y)/m_denom1)-((v.z*v.z)/m_denom1)+(((v.y*v.y)*(v.z*v.z))/m_denom2))));
float y = (v.y * (sqrt(1.0-((v.x*v.x)/m_denom1)-((v.z*v.z)/m_denom1)+(((v.x*v.x)*(v.z*v.z))/m_denom2))));
float z = (v.z * (sqrt(1.0-((v.y*v.y)/m_denom1)-((v.x*v.x)/m_denom1)+(((v.y*v.y)*(v.x*v.x))/m_denom2))));
return vec3(x,y,z);
 }

```

This all leads to the following problem:

As one can see the faces of the "cube" do not match up. I am at a loss here; I use the exact same methods described above to transform the vertices of the cube to those of a sphere.

Any and all help is highly appreciated. If one needs more code to form an accurate opinion please let me know.

# Answer
I ended up going with the suggestions above and used the position of the sphere as the input to the noise...I did this by recalculating the sphere position in the vertex shader for the height map texture:

```
vec3 varPos = vec3(inPosition.xyz);
varPos *= m_Size;

if(m_t == 1){
vec3 v1 = vec3(varPos.x, 0.0, varPos.y);
vec3 v2 = v1 + m_faceOffset;
vec3 v3 = v2 + m_meshOffset;
spherePos = spherize(v3);
}else if(m_t == 2){
vec3 v1 = vec3(varPos.x, varPos.y, 0.0);
vec3 v2 = v1 + m_faceOffset;
vec3 v3 = v2 + m_meshOffset;
spherePos = spherize(v3);
}else if(m_t == 3){
vec3 v1 = vec3(0.0, varPos.x, varPos.y);
vec3 v2 = v1 + m_faceOffset;
vec3 v3 = v2 + m_meshOffset;
spherePos = spherize(v3);
}

```

Thanks for the help!
> 0 votes

---
Tags: glsl, perlin-noise, planet
---


# Question
Title: Implementing a Random Picker by Supplying an Outcome Table (Similar to a Drop Table)
Whilst trying to vary the draw color of some randomly positioned sprites, I really wanted to be able to just supple a table with 2 columns (colour and chance of picking) to some helper function that would do all calculations for me.

Ideally, I want to be able to do something like the follow (semi-pseudocode) :

```
var table = new object[]
{
    Color.White, 0.2, // Chance: 20%
    Color.Red, 0.2, // Chance: 20%
    Color.Blue, 0.5, // Chance: 50%
    Color.Black, 0, // Default, i.e. remaining chance (10%)
};

Color newColor = Pick<Color>.AtRandom(table); // Apologies if this is very wrong!

```

I'm fairly confident I could get something to work within the class - my issue is deciding on the correct way to supply the `Pick` class the chances for each possible selection. I don't want this to be specifically for `Color` \- I want to be able to select between any type of struct / instance of a class. The last line to me doesn't seem 'possible' as in I am unsure whether or not you would require an instance of `Pick` or if this can be done using a static class.

The use of `object[]` seems like a hackerish way to implement this. It's more streamlined to use a `Tuple` however the chance table becomes extremely verbose when every item in the array would be along the lines of `Tuple.Create<Color, double>(Color.Red, 0.2),` etc.

What is the most sensible / expandable way to do this?

Thanks for your time.

# Answer
> 2 votes
If you need to create an instance of the table anyway, you might as well build that into your Pick class. That way you can get type safety throughout, no hacky object\[\] business and boxing/unboxing.

eg.

```
public class PickTable<T>
{
   List<T> values;
   List<double> weights

   public PickTable(int capacity)
   {
     values = new List<T>(capacity);
     weights = new List<double>(capacity);
   }

   public void Add(T value, double weight)
   {
     values.Add(value);
     weights.Add(weight);
     // Might want to track total weight here, or do reweighting as necessary
     // (eg. for 0 weight = remainder)
   }

  public T AtRandom()
  {
    // Random selection logic goes here
    return values[selectedIndex];
  }
}

```

Using it is then just as concise as your version:

```
var colorTable = new PickTable<Color>(4);
colorTable.Add(Color.White, 0.2);
colorTable.Add(Color.Red, 0.2);
colorTable.Add(Color.Blue, 0.5);
colorTable.Add(Color.Black, 0);

Color newColor = colorTable.AtRandom();

```

If you're dealing with large tables or picking from them frequently, there's some good tips on sampling arbitrary discrete probability distributions here.

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


# Question
Title: How to handle animations for a turn based deterministic game?
I have a turn based combat system where all monsters act one turn, then all players, etc. The combat mechanics are completely deterministic - I can pre-calculate the outcome of a turn.

I'm interested if I should do all calculations ahead of time (monster A will be at X, monster B will be at Y), and then just play a bunch of animations based on these calculations:

1. (Calculate for A)
2. (Calculate for B)
3. (Animate A move to X)
4. (Animate B move to Y)

OR do one animation per calculation?

1. (Calculate for A)
2. (Animate A move to X)
3. (Calculate for B)
4. (Animate B move to Y)

# Answer
> 4 votes
This is primarily just a design decision. Consider that you can actually do these things at the same time. If you look at the situation in terms of your update loop:

```
 Update 1:
   Calculate outcome for entity: n
   Play animation: n (frame 1)
 Update 2:
   Calculate outcome for entity: n+1
   Play animation: n (frame 2) and n+1 (frame 1)
 Update 3:
   Calculate outcome for entity: n+2
   Play animation: n (frame 3) and n+1 (frame 2) and n+2 (frame 1)
 Update 4:
   Calculate outcome for entity: none left
   Play animation: n (frame 4) and n+1 (frame 3) and n+2 (frame 2)

```

Alternatively, if you can calculate the outcome very quickly, you can do all the entities in the first update, then spend the rest of your updates playing animations.

The reason I say it's mostly a design decision is because the only reasons to do it one way or the other is the requirements of your project or your design preference. In these situations it's usually best to just pick a method you think will work and go with it. Trying something out will help you learn if it was a good choice and give you much more information about the situation. It also often opens up alternatives that you didn't know existed until you tried implementing something.

---
Tags: animation, ai, turn-based, turn-based-strategy
---


title: Mixing animations

text:
# Question
Title: Mixing animations
I'm working on a swing animation and mixing it with a turn animation in a motorcycle game.

The issue is that for the swing animation to work while turning only the swinging arm has to animation, otherwise the other arm falls off the handlebar, you can see what I mean in the following videos;

http://www.youtube.com/watch?v=\_pJeEHufAPg

http://www.youtube.com/watch?v=IxPQ91kCSKk

Is there a way to inverse whatever animation is being applied to the other arm to keep it in place so it isn't influenced so much by its parent or is this just a pipe dream?

Anyone here managed to solve a similar problem? I'm using Unity3D fwiw.

# Answer
> 2 votes
What you need to find is a technique that, given some constraint C (the left hand on the handlebar), applies some displacement to your joints so that the final animation respects those constraints **while staying as close as possible to the initial animation**. This could be done with constraint-baseds motion editing techniques and in particular, Per-Frame Inverse Kinematics. The idea is:

1. Take an initial motion close to what you want but not perfect. Here, it is the motion in your first video;
2. Determine the constraints you need to apply. Here, most probably the hand should stay on the handlebar;
3. Then compute, at key frames (or similarly at every frame), the displacement you need to add to your animation to satisfy your constraints. This can be done with Inverse Kinematics for example;
4. Finally, smoothly interpolate your initial animation with the final required results by smoothly "adding" the computed joint displacements.

This is not trivial to do actually and it needs some careful thinking beforehand. I suggest your read this paper which is a good explanation of the problem with different possible solutions:

**Comparing Constraint-Based Motion Editing Methods**, Michael Gleicher, *Graphical Models, Volume 63, Number 2, page 107--134 - mar 2001*

> Tools for assisting with editing human motion have become one of the most active research areas in the field of computer animation. Not surprisingly, the area has demonstrated some stunning successes in both research and practice. This paper explores the range of constraint-based techniques used to alter motions while preserving specific spatial features. We examine a variety of methods, defining a taxonomy of these methods that is categorized by the mechanism employed to enforce temporal constraints.We pay particular attention to a less explored category of techniques that we term per-frame inverse kinematics plus filtering, and we show how these methods may provide an easier to implement while retaining the benefits of other approaches.

Your problem being in the "simple category", IK based techniques could work.

Finally, note that existing middleware could help. In particular, **HumanIK from Autodesk** is great for that (and much more).

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


# Question
Title: Rotating one object to track another in worldspace
This should be pretty straightforward, but its been awhile and my brain has officially turned off for the holidays :-) To keep things simple, lets assume everything is in 2D space.

I've got a large circle, who's centre will be the origin (0,0). Now lets say I've got Object A, who is sitting inside this circle at the origin, and is facing a direction (0,1), the positive y direction. Circumference of the circle shouldn't matter for what I'm trying to do. Now let's say I have two incoming parameters (which I have no control over). One of these parameters is a rotation (in Radians), and the other is a translation. If I apply this rotation to Object A while it's in the centre of the circle, followed by the translation, the object will now be on the outside of the circle but its direction will be facing the origin. In other words, the incoming parameters will translate the object to be outside but facing the centre of the circle, where it was originally inside and facing the positive y direction.

Here's where I'm stuck: If I also have a random point inside the same circle, and I want Object A to be translated to the exact same position it would normally be translated to (outside the circle) from those two incoming parameters, but facing the direction of this point instead (which could be anywhere inside the circle), what's the most efficient combination of operations to apply to it to accomplish this, assuming object A always starts in the origin, and this is the only information I have (the translation/rotation parameters, and the position of the point I wish to track). Assume the point can move around anywhere inside the circle, and the object will remain outside in the exact same position but its direction will "track" the point regardless of where it is.

UPDATE for clarification: Sometimes a picture is worth a thousand words ;-) See attached image... #1 is where the object starts at. #2 is what would happen if I apply the incoming translation and rotation parameters. #3 is what I'm trying to achieve. I do know that the "random" point is located at (0, 0.5) in this example. How do I get from #1 to #3 in the least amount of steps.

# Answer
> 0 votes
After re-positioning the object based on the incoming parameters, I think you can do something like this:

```
lookDirection = targetPoint.position - objectA.position;
objectA.rotation = atan2(lookDirection.y, lookDirection.x);

```

or, if you can only set incremental roations, then the second line becomes something like...

```
objectA.rotate(atan2(lookDirection.y, lookDirection.x) - objectACurrentRotation);

```

You might need to flip a sign or adjust the angle you get from atan2 to work with your rotation notation (since you don't specify what libraries or coordinate systems you're using), but I think it can be basically as simple as this.

Just remember to do those two steps anytime objectA or its targetPoint moves after this.

# Answer
> 0 votes
I believe this is what you're after.

Note that it makes more sense to pass in the distance from the center of the circle you wish object A to be placed instead of this translation vector, as it appears the rotation is determining how far around the circle objectA should be placed.

```
function PositionAndRotate( float distFromCenter, float angle, Vector2 objectBPos )
{
    // Calculate position using polar coordinate to cartesian and set it
    this.setPosition(Vector2( distFromCenter * cos(angle), distFromCenter * sin(angle) ));

    // Calculate look at vector
    Vector2 lookAt = objectBPos - this.getPosition();

    // Get angle needed to rotate object A to face object B
    float angleToRotateBy = atan2(lookAt.x, lookAt.y);

    // Set rotation for object A
    this.rotate(angleToRotateBy)
}

```

*This function assumes it is a method of object A.*

This is similar to DMGregory's answer but I wanted to show a more complete answer to resolve any ambiguity.

---
Tags: mathematics, rendering
---


title: First time shadow mapping problems

text:
# Question
Title: First time shadow mapping problems
I have implemented basic shadow mapping for the first time in OpenGL using shaders and I'm facing some problems. Below you can see an example of my rendered scene:

The process of the shadow mapping I'm following is that I render the scene to the framebuffer using a View Matrix from the light point of view and the projection and model matrices used for normal rendering.

In the second pass, I send the above MVP matrix from the light point of view to the vertex shader which transforms the position to light space. The fragment shader does the perspective divide and changes the position to texture coordinates.

Here is my vertex shader,

```

#version 150 core

uniform mat4 ModelViewMatrix;
uniform mat3 NormalMatrix;
uniform mat4 MVPMatrix;
uniform mat4 lightMVP;

uniform float scale;

in vec3 in_Position;
in vec3 in_Normal;
in vec2 in_TexCoord;

smooth out vec3 pass_Normal;
smooth out vec3 pass_Position;
smooth out vec2 TexCoord;
smooth out vec4 lightspace_Position;

void main(void){
    pass_Normal = NormalMatrix * in_Normal;
    pass_Position = (ModelViewMatrix * vec4(scale * in_Position, 1.0)).xyz;
    lightspace_Position = lightMVP * vec4(scale * in_Position, 1.0);
    TexCoord = in_TexCoord;

    gl_Position = MVPMatrix * vec4(scale * in_Position, 1.0);
}

```

And my fragment shader,

```

#version 150 core

struct Light{
    vec3 direction;
};

uniform Light light;
uniform sampler2D inSampler;
uniform sampler2D inShadowMap;

smooth in vec3 pass_Normal;
smooth in vec3 pass_Position;
smooth in vec2 TexCoord;
smooth in vec4 lightspace_Position;

out vec4 out_Color;

float CalcShadowFactor(vec4 lightspace_Position){

    vec3 ProjectionCoords = lightspace_Position.xyz / lightspace_Position.w;

    vec2 UVCoords;
    UVCoords.x = 0.5 * ProjectionCoords.x + 0.5;
    UVCoords.y = 0.5 * ProjectionCoords.y + 0.5;

    float Depth = texture(inShadowMap, UVCoords).x;
    if(Depth < (ProjectionCoords.z + 0.001)) return 0.5;
    else return 1.0;
}

void main(void){

    vec3 Normal = normalize(pass_Normal);
    vec3 light_Direction = -normalize(light.direction);
    vec3 camera_Direction = normalize(-pass_Position);
    vec3 half_vector = normalize(camera_Direction + light_Direction);

    float diffuse = max(0.2, dot(Normal, light_Direction));
    vec3 temp_Color = diffuse * vec3(1.0);

    float specular = max( 0.0, dot( Normal, half_vector) );

    float shadowFactor = CalcShadowFactor(lightspace_Position);

    if(diffuse != 0 && shadowFactor > 0.5){
        float fspecular = pow(specular, 128.0);
        temp_Color += fspecular;
    }

    out_Color = vec4(shadowFactor * texture(inSampler, TexCoord).xyz * temp_Color, 1.0);
}

```

One of the problems is self shadowing as you can see in the picture, the crate has its own shadow cast on itself. What I have tried is enabling polygon offset (i.e. glEnable(POLYGON\_OFFSET\_FILL), glPolygonOffset(GLfloat, GLfloat) ) but it didn't change much. As you see in the fragment shader, I have put a static offset value of 0.001 but I have to change the value depending on the distance of the light to get more desirable effects , which not very handy. I also tried using front face culling when I render to the framebuffer, that didn't change much too.

The other problem is that pixels outside the Light's view frustum get shaded. The only object that is supposed to be able to cast shadows is the crate. I guess I should pick more appropriate projection and view matrices, but I'm not sure how to do that. What are some common practices, should I pick an orthographic projection?

From googling around a bit, I understand that these issues are not that trivial. Does anyone have any easy to implement solutions to these problems. Could you give me some additional tips?

Please ask me if you need more information on my code.

Here is a comparison with and without shadow mapping of a close-up of the crate. The self-shadowing is more visible.

# Answer
> 6 votes
You should not shadow the polygons that are back faced from the light.

I changed your fragment shader to below code.

```
float CalcShadowFactor(vec4 lightspace_Position)
{

    vec3 ProjectionCoords = lightspace_Position.xyz / lightspace_Position.w;

    vec2 UVCoords;
    UVCoords.x = 0.5 * ProjectionCoords.x + 0.5;
    UVCoords.y = 0.5 * ProjectionCoords.y + 0.5;

    float Depth = texture(inShadowMap, UVCoords).x;
    if(Depth < (ProjectionCoords.z + 0.001)) return 0.5;
    else return 1.0;
}

void main(void)
{

    vec3 Normal = normalize(pass_Normal);
    vec3 light_Direction = -normalize(light.direction);
    vec3 camera_Direction = normalize(-pass_Position);
    vec3 half_vector = normalize(camera_Direction + light_Direction);

    float fndotl = dot(Normal, light_Direction);
    float shadowFactor = CalcShadowFactor(lightspace_Position);
    float diffuse = max(0.0, fndotl) * shadowFactor + 0.2;
    vec3 temp_Color = vec3(diffuse);

    float specular = max( 0.0, dot( Normal, half_vector) );

    if(shadowFactor > 0.9){
        float fspecular = pow(specular, 128.0);
        temp_Color += fspecular;
    }

    out_Color = vec4(shadowFactor * texture(inSampler, TexCoord).xyz * temp_Color, 1.0);
}

```

# Answer
> 8 votes
Regarding the self-shadowing, I'm not sure just what you're referring to - I don't see any "shadow acne" on the crate in your screenshot. If you mean that the faces facing away from the light are dark, well, of course they are - they should be! :) The side face does look a little weird, split down the diagonal into half lit and half shadowed. If you're using N dot L for lighting, and you have good normals (i.e. hard normals on this cube, not smoothed normals) that shouldn't happen.

Using polygon offset and/or drawing the back faces into the shadow map are the standard solutions (well...workarounds really) for shadow acne.

As for the projection matrix, you should think of the light as a camera. If it's a point light, it would be a perspective camera and if it's a directional light it would be like an orthographic camera. Construct the projection matrix just the same way you would for a camera, using the light's field of view, aspect ratio, etc.

To restrict the pixel shader to only draw the pixels in the light's view frustum, once you calculate the shadow map UVs just check if they're between 0 and 1 and `discard` if not (or set the light's color to zero). Another way is to set the shadow map texture to "clamp to border" mode and set a border color of zero, which will ensure everything outside the shadow map gets fully shadowed.

# Answer
> 3 votes
The pixels outside of the lights view are dark because they're being sampled from outside the lights depth texture.

When you transform the vertex by the projection matrix you get the clip coordinates \[lightspace\_Position\] of the fragment. You are then converting that into texture coordinates \[UVCoords\]. However, clip space coordinates of a fragment can still be outside the -1.0 to 1.0 range (off the screen and hence clipped) and therefore the converted texture coordinates can be outside of the 0.0 to 1.0 range of your texture.

Try this:

```
if(UVCoords.x >= 0.0 && UVCoords.x <= 1.0 && UVCoords.y >= 0.0 && UVCoords.y <= 1.0 && (Depth < (ProjectionCoords.z + 0.001)))
    return 0.5;

```

You can also multiply a bias matrix into your \[lightMVP\] and avoid doing the coordinate conversion in your fragment shader.

---
Tags: opengl, glsl, shadows, shadow-mapping
---


title: Multiple FBX Animation Files in Maya

text:
# Question
Title: Multiple FBX Animation Files in Maya
I bought some animated models which came as FBX files from the unity asset store and I'm trying to export them to PNG sprite sheets in Maya (for an html5 web project).

The file seems to be main fbx (character.fbx) and then an FBX file for each animation named character@animation.fbx.

I was wondering if there was a way for me to import all of these fbx files into Maya and then batch render each animation to PNG frames with some naming/directory structure?

Currently, I can import the main character fbx and an animation fbx and then render that single animation. This works, but it's tedious. Is there anyway to render all the animations at once?

# Answer
In Maya, if you can do it by hand, then you can script it. The easiest way to do is to do it once, then open the script editor and look at the output. You will see the sequence of MEL commands Maya executed. Based on that, it is normally easy to write a MEL script that does the same but for a bunch of files located in a directory.
> 1 votes

---
Tags: animation, rendering, spritesheet, maya, fbx
---


# Question
Title: Limitations of p2p multiplayer games vs client-server
I am reading up on multiplayer game architecture.

So far most of the articles i've found deal with the client-server model.

I'd like to know what are the limitations for using a p2p architecture? what "class" of games are possible (or more common) to implement using it? which aren't? and in general, what are its main differences and limitations against the client-server model.

# Answer
Here's my two cents:

**P2P**:

* *Pros:*
    + **No need for a central server**: this makes it much cheaper, and more viable for low-budget indie games.
    + Scales very well (up to a certain point when the average client just can't handle the bandwidth).
    + **Very good for data distribution**: Suits games where user-created content is dynamically synced (e.g. torrents).
    + More Stable: It can never happen that the server is having problems and no-one can play (implementation dependent).
* *Cons:*
    + **Hard to implement**: much harder to create a solid P2P architecture, than a server-client.
    + **It's very hard to prevent cheating** in such a system, unless you designate an authoritative peer (which will hinder any benefits of scaling well from P2P).
    + **Security is hard to achieve.**
    + A client's internet connection can influence the game for others too.
    + Latency is usually much greater (although it can be better when joining an internet game with multiple people from a LAN network for example).
    + **May require port forwarding**: P2P over the Internet requires port-forwarding, and not everyone is technically-inclined enough to do that. Additionally, the ISP may prevent port forwarding, and it increases the barrier to entry.

**Server-Client**:

* *Pros:*
    + Easy to implement: It's as straightforward as it gets.
    + If implemented well, scales extremely well (if the work can be distributed across multiple servers).
    + Cheating can be avoided easily (compared to P2P).
    + **Lower Latency**: If the server has a solid connection the latency can be extremely low.
    + A player's internet connection never affects another's game.
* *Cons:*
    + **Costs you money to run the servers**: definitely not suitable for a free game (unless you let the players set up a dedicated server, but that might be a security problem).
    + If the server has problems, everyone does.

I would consider P2P a good choice because the average internet connection is getting better and better, in the future P2P latency might not be a problem at all. Also much about P2P depends on the specific implementation.

There is also some architectures that combine P2P with Server-client.
> 13 votes

# Answer
A big risk of peer-to-peer games is that without a central authority in form of a neutral server, there is no way to prevent cheating. Each client can interprete the outcome of the game however it wants. Some games declare one of the clients the host and let him be the judge, but when that client is a cheater, they decide the outcome of the whole game.

With games which require low latency and high bandwidth, like any game which requires quick reaction from the players, you also have the problem that the host is just using a consumer-grade internet connection, not sitting in a datacenter with a high-performance backbone connection. That means the user-experience will suffer. This isn't so much of a problem in more strategy-oriented, "slower" games.
> 2 votes

# Answer
Implementing peer to peer multiplayer games is not easy and not applicable at the moment.

The problem you have is, that none of the peers knows all other peers so that you have multiple hops for each message which results in a higher latency compared to a client server model. See this paper for additional details.

Round-based games could easily use such a protocol since they dont depend on latency so much. Also they normaly have only a few hosts in a session so that one could broadcast every message to all other players.

Other games which use peer to peer just choose one of the Peers dynamically to host the game (i.e. CoD MW2), which results in problems like host-migration if the host disconnects.
> 0 votes

---
Tags: software-engineering, networking, multiplayer, online
---


title: How do Raymarch shaders work?

text:
# Question
Title: How do Raymarch shaders work?
I have been looking at shaders found here shadertoy.com and most of the cool ones have noise and raymarch in common. I do not understand the source code at all but I really want to. How do these shaders work and how does the raymarch algorithm work? I've searched all over and can't find anything on the topic.

Thanks

# Answer
It's probably easiest to understand by contrast with raytracing.

To render a primitive with raytracing, you need a function that, given the primitive and input ray, tells you exactly where that ray hits the primitive. Then you can test the ray against all relevant primitives, and pick the closest intersection.

This means potentially a lot of non-local data traversal as you search through all the candidate primitives in the scene, and running multiple different intersection tests depending on the primitive - a varied workload that historically made this almost exclusive to CPUs. It's only recently that specialized hardware and APIs have made such techniques more tractable on GPUs.

With raymarching, you don't always have such a simple ray intersection function. Given a point on the ray, you can estimate how close the point is to the surface, but you don't know exactly how far you need to extend that ray to hit the surface.

So, you "march" one step at a time:

1. Start at the "beginning" of the ray - the near plane for scene rendering, or the intersection with the bounding volume if it's just one object in the scene. (P0, at the far right side of the diagram below)
2. Evaluate your distance function to get an estimate for how close you are to the surface. (The largest circle in the diagram)
3. Move forward along the ray according to your estimate. The move should be conservatively short, so you're confident you won't tunnel through the surface anywhere.
4. Now you have a new point (P1, below and to the left) - get a new estimate and repeat.
5. Continue getting estimates and stepping forward until you get within a threshold distance of the surface, or you hit your maximum step count. (P4 below, at the left side where the ray has just about touched the surface)
6. Now you have the depth of the surface, and can infer things like normals/ambient occlusion from nearby samples, and use this data to light & colour the pixel.

Example diagram from GPU Gems 2, chapter 8

There's a great interactive demo by paniq you can play with here \- click and drag in the canvas to change the ray direction.

Because each ray is independent and uses (generally) only local information at each step, it's ripe for parallelizing on GPUs - even using conventional fragment shaders rather than sophisticated compute shaders or specialized raytracing hardware. Often, only two triangles will be drawn on the screen. After rasterizing these, each pixel passed to the fragment shader represents a single ray. The fragment shader marches that ray until it reaches the surface, returning the result (often just the depth value for texturing & shading in a separate full-screen pass).

The exact steps depend a lot on the particular effect you're trying to achieve. Raymarching techniques are used with...

* heightfields to simulate surface displacement on traditional rasterized geometry (parallax occlusion mapping)
* scene depth buffers for things like screenspace reflections
* volume textures for visualizing 3D-sampled datasets (often scientific/medical)
* implicit functions for rendering things like fractals
* procedural distance fields as in Iñigo Quilez's work (great links from msell in the comments above).

Raymarching is also used with blending at each step (often using fixed steps instead of estimating a distance each time) for rendering volumetric translucency, as in this example from Wikipedia.

This has become a popular way to render detailed clouds in realtime.

Even Interior Mapping, a way of simulating interior room detail behind building windows, could be considered a form of raymarching, where the ray is stepped from the point it enters the window to the closest wall, floor/ceiling, or furniture plane.

If there's a specific type of raymarching effect you're interested in, you can probably get more detailed answers by asking a new question with specific examples. As a family, the technique is too diverse to cover everything in one short answer. ;) I hope this gives you a framework for understanding what's happening under the hood in these shaders.
> 85 votes

---
Tags: shaders, algorithm, glsl, raymarching
---


# Question
Title: How do I combine the Android UI buttons with libGDX?
I want to combine the Android UI with libGDX. I want to have half of my screen drawing an animated sprite with the libGDX engine, and the other half of the screen drawing Android UI buttons.

How do I combine the Android UI buttons with libGDX?

# Answer
Libgdx has a great UI package called scene2d. It is specially written for UIs, but can be used for other things also.

See Scene2d.ui documentation

What you will want to do is create a UI stage. During your game loop call stage.draw() after you draw your game so it renders over the top of your game. If you just want to use the UI to receive input then just use `Gdx.input.setInputProcessor(...)` to set the UI stage as the input processor. If you want the game and the stage to receive input you will need to use an InputMultiplexer.

You add widgets (widgets being things like tables, buttons, and more) to the stage. And then add change listeners to the particular widgets to help control your game.
> 4 votes

# Answer
Nothing special, it just works. Libgdx view is just a wrapper around an ordinary OpenGL view, you can use it with any layout (including a LinearLayout split in half).

The autogenerated code has an `initialize` call. This call creates the Libgdx view and displays it using full screen.

If you remove the call, you can instead use `initializeForView`. This method creates and returns the Libgdx view, but does not display it (nor switches to full screen), so you can place it in any layout you want.
> 3 votes

---
Tags: android, libgdx
---


# Question
Title: How can I simulate a limited (256) color palette in OpenGL?
On Twitter, I found this screenshot of a game in development:

The image on top seems to be without any color limitation. But the two other pictures at the bottom have a 256 color palette.

I want to achieve a similar effect in *my* game (I am using OpenGL). How can I do so?

# Answer
I am the creator of that image.

The image on the right is rendered using a color look-up texture. In the final GLSL shader, I apply the dither, then convert the RGB values into integers in the range 0\<=x\<40, combine them into a single index, then look up the resulting color value in this image:

The lowest row is the raw palette.

The image to the left is made purely in the shader by downsampling the red and green channels to 8 values, and the blue channel to 4 values after applying the dither, resulting in RGB332. I've also played around with 7 red, 9 green and 4 blue shades, resulting in only 252 colors, but with a bigger emphasis on green, which the human eye is the most sensitive to.
> 31 votes

# Answer
You could use a color grading lookup table in a postprocessing step as described here and probably here.

After you've implemented this, all you'll have to do is make a screenshot, overlay the lookup texture ontop of it, then edit it in arbitrary graphics software until you like it - and then retrieve the modified lookup texture again. This may or may not include reducing the retrieved lookup table to a subset of colors.

When loading the lookup texture with color limitation in mind, just make sure to disable all filtering, so it won't produce additional colors.
> 6 votes

---
Tags: opengl, webgl
---


# Question
Title: very simple math destination and speed calculation
My player goes to (destinationX, destinationY)

His position is: (x,y)

and the player has an update event

```
function update() {
 this.x = this.x + dx;
 this.y = this.y + dy;
}

```

what is the formula for dx and dy ?

```
dx = (destinationX-this.player.x)/this.speed;
dz = (destinationZ-this.player.z)/this.speed;

```

is "almost" good: it goes to the good direction, but problem is his speed. It takes the same time to go from (0,0) to (10,10) than from (0,0) to (1000,1000)

# Answer
> 3 votes
You need to normalize the direction vector, then multiply the result by your speed (since you want larger speeds to make you move faster). Something like:

```
dx = (destinationX-this.player.x).normalize() * this.speed;
dz = (destinationZ-this.player.z).normalize() * this.speed;

```

If you don't have access to a `normalize` function, you can create your own, the normalization of a vector follows this equation:

```
normalized_a = sqrt((a.x * a.x) + (a.y * a.y) + (a.z * a.z))

```

# Answer
> 1 votes
@Byte56 is right. You only want a direction vector without any information about the distance to the target. You can get that by normalizing your vector to unit length. Do this:

```
 diffX = destinationX - this.player.x;
 diffY = destinationY - this.player.y;
 length = sqrt(diffX * diffX + diffY * diffY); //Pythagorean law
 dx = diffX / length * this.speed; //higher speed is faster
 dy = diffY / length * this.speed;

```

---
Tags: 2d, mathematics, movement, physics
---


# Question
Title: Trying to project a point onto a cubemap
I've got a simple test program with a camera within a cubemap (skybox). You can look around, and it feels like you're in a 3D room, but really it's just a cubemap image.

Now I want to draw a point (well, ultimately, a large number of points) on the screen, such that it appears to be anchored at a point on the cubemap. For example, if the cubemap is of a room, then I want to put a point on the "wall", and have it appear to be stationary when you look around.

Given that there is no actual environment, it's just a cubemap, the points I want to project are represented as x/y rotational angles, rather than absolute 3D vertices. I tried calculating the position manually, using the camera x/y angles and interpolating across the screen. However because the cubemap is distorted at the edges due to the camera's projection matrix, my linear calculations don't match up, so the point appears to wobble as you look around.

I know I need to incorporate the camera's projection matrix to get it to appear in the correct position, but I'm not sure how. I'm using the CML math library, and I noticed it has a project\_point() function, but it works with absolute 3D coordinates, so I don't know how that helps me when starting with angles instead of coordinates.

If someone could get me pointed in the right direction, I would appreciate it.

**Edit:** After reading other questions on polar coordinates, I came up with this for converting x/y angles (relative to the camera view angle) into a 3d coordinate that I could project onto the screen:

```
x = sin(horizontal_angle) * cos(vertical_angle)
y = sin(horizontal_angle) * sin(vertical_angle)
z = cos(horizontal_angle)

```

This almost works, I feel like I'm close. I can rotate the camera left and right, and the point appears to remain stationary. However, as soon as I rotate it up or down as well, the point moves rather significantly. However I I haven't been able to figure out why that is so far.

# Answer
Well the camera must stay in the center of the cubemap, so its position is fixed. Say (0,0,0). It is easy to convert polar coordinates (x,y angles) to cartesian coordinates on a sphere of fixed radius (say r=1). That way those points are stationary within the scene and will appear anchored to the cubemap even though they are somewhere inside the cube.

I'm sure you'll find plenty of answers how to do that calculation on stackoverflow https://stackoverflow.com/search?q=polar+coordinates

But before you begin, why not check if something else is wrong? Put a point on some coordinates (0.5, 0.8, 0.3) and see if it behaves stationary, i.e. anchored to the cubemap. If it doesn't then your scene rendering and camera rotation steps are mixed up.
> 1 votes

# Answer
I can't tell from what you wrote whether you want the point to stay stationary on the screen, or stationary with respect to the environment projected on the cubemap. However, in either case, the method I'd recommend would be the same: first map the angles to a point on a sphere, then project it onto the cube.

To get the location of the point on a sphere, start with a point at a fixed location in world space (i.e. wherever you want it to be if both angles are zero) and apply the rotations to it.

To project the point onto the cube, you first need to find out which side of the cube it is closest to, and then project it onto that side. For an axis-aligned unit cube centered on the origin, this is easy — just divide all coordinates of the point by the coordinate which has the largest absolute value. In pseudocode:

```
norm = max( abs( point.x ), abs( point.y ), abs( point.z ) );
point.x /= norm; point.y /= norm; point.z /= norm;

```

After this projection, one of the coordinates will be ±1.0, and the other two will range between -1.0 and +1.0.
> 1 votes

---
Tags: mathematics, projection
---


# Question
Title: Questions about networking theory in a 2d shooter game
So currently I am starting to work on a 2d top down space shooter game, and I have just got to networking. So far the client can draw a ship at a desired x, y and rotational coordinate with any set of vertex data (referenced from pre-existing vectors of data). The problem I am having is just the main idea of how the game loop should revolve around the networking. My idea was have each loop of the game set to 1000/60ms, and then ask the server for some data, render it and sleep for the remaining time in the frame. Problem with that is that I realised a normal ping to a game server is around 100ms, meaning the game would only be getting around 10fps. The solution I assume is to only receive events 10 times a second versus the 60 refreshes the game is getting, but how would you render and be polling to receive data at the same time? Finally I am using enet as the networking library if anyone is interested because it seems to be pretty simple in its concept, but if there is a better one for this type of game out there it would be nice to know. (I did try googling all of this stuff but its kind of hard to describe exactly what I am confused about, so thanks for any help).

# Answer
If you are using ENet you could make the server send an update packet for example 5 times a second, and use a non-blocking function to process it in your client.

A non-blocking function just checks if any packet has received, does not wait for one to arrive in case one hasn't already.

In ENet you can use

`int enet_host_service( ENetHost* host, ENetEvent* event, enet_uint32 timeout )`

Where the last parameter is how much to wait for an incoming event( can be a pakcet, but can be connection or disconnection request too )

You can use the documentation as a reference.

Edit:

As per request in comment here is how should your main programloop look like:

```
while( running )
{
    ProcessInput(); // Check for user input and process it
    UpdateNetworking(); // Send receive neccessary packets with enet_host_service
    Update(); // Update game logic
    Render(); // Render current scene
}

```
> 1 votes

---
Tags: 2d, networking, shooter
---


# Question
Title: Good way to integrate time to a quiz game
I wasn't sure which stack exchange site to pose this question to, so I'm asking it here, I hope it's appropriate. This thing I'm writing for fun is basically a mental math speed quiz game. I'm writing it in javascript and html.

What I want to happen is for there to be a score depending on how fast you finished the quiz and how many you got correct. For an incorrect answer, you get 0 points. But for a correct answer, if you took 5 seconds to solve that question, you get more points than if someone took 8 seconds to answer the question.

This seems trivial but I was thinking about it and I don't really have a good algorithm or equation for judging a performance based on time.

For example: someone answering a question correctly in 5 seconds gets 20 points, someone answering correctly in 10 seconds gets 14 points (not exact figures, just example)

Does someone have an idea of this? Thanks

# Answer
One way to do this would be:

```
Score = answer*(MAX_TIME - time_taken)

```

where answer is either 0 or 1 (if it was incorrect or correct)

(MAX\_TIME - time\_taken) could be the input to some function you create that weighs time taken differently. For example, you might want even small differences in time taken to result in large score differences, and could implement this as:

```
Score = answer*(MAX_TIME - time_taken)^3

```

The important thing you need to do is think about the relationship you want between score and time taken so you can find a function that best suits it.
> 1 votes

---
Tags: mathematics
---


# Question
Title: Level of Detail/Load on Demand for crowds: replace groups of objects instead of individual ones?
I have been thinking of using level of detail to make rendering crowds easier. The idea is to replace a group of meshes with a single one representing a group.

For example, you have 1 individual cube mesh. If you get 100 cubes together in a close space, replace all of those with a generic "blob of 100 cubes" mesh, that would be simplified and hopefully have a lower polycount than the sum of all 100 cubes. If 100 "blob of 100 cubes" meshes are together, then replace them with a simpler "blob of 10000 cubes" mesh. And so on.

There are many different challenges in doing this. Such as how to detect the objects are close? How to render the blob so it looks realistic enough? What to do about each object's metadata (physics, game variables)? etc So before I delve too much into it, I would like to see what is the current state of this technology and how people have been using this.

But I cannot find anything related to it. I've been looking for it for days, but every search I do about "LOD" and "crowds" only returns things about how to simplify each individual mesh of each game unit (ie. replacing a high poly count character, with a low poly character). Instead of replacing many game units with fewer ones, which is what I want to do. I've obviously played many games, and I can easily tell when they're using LoD for simplifying individual units. But I don't remember a single game that would replace groups. Am I looking it up wrong? Is there a specific term for this thing that I should be looking up for instead? Do you guys happen to know some case study examples of games that do this that I could check? Or maybe this isn't done at all?

Any help to point me in the right direction would be appreciated. Thanks.

# Answer
> 2 votes
LOD on individual meshes is still your best bet, IMHO. It's very well studied and works well for crowds, especially if they are animated individually. At the extreme, you have a single quad (or triangle) with a pre-rendered sprite that's appropriate for the camera angle. This is called **impostors** in the field. Since we're talking about extreme levels of simplification, you can get away with very few sprites to minimise on the texture memory required. For somewhere to start, here's a paper on 3D impostors which uses an interesting technique to address popping artifacts when changing camera angle: http://users.soe.ucsc.edu/~davis/papers/yee\_masters\_project\_paper.pdf

As for simplification via merging individuals into groups, the nearest thing I can think of is **Stochastic Simplification**, used for foliage and hair/fur mainly - it was used by Pixar in Cars for the bushes and Ratatouille for the fur. Check out these slides which get the general ideas across:

* **Stochastic pruning** \- randomly remove strands from the bunch
* **Area preservation** \- thicken the remaining strands to compensate
* **Contrast compensation** \- to remove the blurring effect

I have no idea whether this will work well for crowds; you may run into too much artifacts after an order of magnitude of simplification. If you do get it to work well, it will make an interesting paper.

---
Tags: optimization, loading, level-of-detail
---


# Question
Title: Java 2d game cross-platform compatability
I need to make a few small, simple 2d educational games primarily to help kids improve their reading. Drag & drop/matching words with pictures, spelling out words as well as maybe a scrolling shooter and some other things too. I also need these to run on multiple platforms (namely windows, osx, ipads and android).

If I do this with java (which I don’t currently know), is it possible to use the same code to create versions compatible with the above-mentioned platforms?

# Answer
> 1 votes
A Java application works on any common desktop operating system.

Android applications are written in Java, but are structured very differently than normal desktop applications. Also, most standard Java GUI toolkits aren't supported by Android. So porting to Android will require much more work than just clicking a button.

On iOS, Java isn't supported at all.

Did you consider building your game as a web application? Every device nowadays has a web browser which can execute Javascript, so you can't get much more plattform-independent than that.

---
Tags: java, 2d, ios, cross-platform
---


# Question
Title: C++&SFML Moving Sprites Smoothly in Tiles
As a student, I've always wanted to become a game developer. So far I've managed to learn the basics of C++ and SFML 2.1

For my first project, upon deciding to make a 2D RPG-ish game, I encountered a problem that the game loop refreshes so quickly that if I move them by 1 pixel per frame, the sprite will move more quick than I intended to.

I implemented a frame-determined movement system(not sure what it's called) that whatever the fps is, the character moves at same speed.

However, I couldn't solve the problem(which is what I'm asking) that the sprite won't move smoothly. What's happening in my build is that the player will move about 1px per frame, and can be interrupted by other inputs. What I want the sprite to do is move horizontally 32px per second. How can I do this?

Edit: wasn't being clear enough. What I want the program to do is when I press 'Right' key once, sprite moves towards the positive side of x-axis, for 32px. What's currently functioning in my program is the sprite will move only once, 1px

TL;DR : I want to move my sprite like old-school RPG games, moving predetermined pixels(or tiles) smoothly.

# Answer
Simulation should be separate from rendering. It sounds that your code doesn't make that distinction.

If you want contineous movement, e.g. n units of distance per unit of time, you need to update your **entity's** position based on time elapsed since previous iteration of game loop, and entities velocity and maybe some other factors -- power-ups for example. Then update sprite's location based on entities location. Then render the sprite. Velocity could be set based on input.

Here's some example code to illustrate the point. It's not too terrible. ;)

```
struct Entity
{
        Entity(x, y, vx, vy);

        /* Current position. */
        double x;
        double y;

        /* Velocity per unit of time. */
        double vx;
        double vy;

        sf::Sprite sprite;

        void update(double dt)
        {
                vx = vy = 0;
                if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) {
                        vx += -10;
                }
                if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) {
                        vx += 10;
                }
                if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) {
                        vy += -10;
                }
                if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) {
                        vy += 10;
                }
                x += vx * dt;
                y += vy * dt;
        }

        void render(sf::RenderTarget& rt)
        {
                sprite.setPosition({x, y});
                rt.draw(sprite);
        }
};

int main() {
        sf::RenderWindow window(sf::VideoMode(800, 600), "Example");
        Entity e(400, 300, 0, 0);
        sf::Clock clock;
        while (window.isOpen()) {
                /* Process events. For this example, we'll use "raw" input instead
                 * of event-based input for controls.
                 */
                sf::Event e;
                while (window.pollEvent(e)) {
                        if (event.type == sf::Event::Closed) {
                                window.close();
                        }
                }

                /* Check docs for sf::Clock. */
                e.update(clock.reset().asSeconds());
                e.render(window);
        }
}

```
> 3 votes

# Answer
What you're looking for is framerate independent movement. There are basically two different approaches available:

* Update your game once every given time frame ("fixed timesteps").
* Update your game based on the time since the last update ("delta time").

Both approaches got their own advantages and disadvantages. Just to name a few:

* Using **fixed timesteps**
    + A lot more easier approach for object interaction, e.g. collision detection (preventing ghosting).
    + Allows easy slow down of game logic in case the machine isn't able to run at the intended speed.
    + Missing handling might cause a situation where your game logic is no longer able to catch up, e.g. it wants to render 20 updates rather than 10 updates per second to catch up, without being able to do so, creating a backlog that's getting longer and longer.
    + Based on your (render) frame rate movement might appear to stutter, e.g. due to an update essentially happening right before or right after drawing.
* Using **delta time**
    + Requires lower amount of updates, possibly resulting in higher framerate/lower CPU load.
    + Proper object interaction (collision detection) is a lot harder to do to prevent issues such as ghosting.
    + Movement should always appear smooth, but might get "jumpy" if framerate drops too significantly.

Since both approaches got some nice features, I typically try to include both at once. If I need accuracy for something, e.g. player movement, shots, etc., I update it using fixed timesteps. If accuracy doesn't matter and it's all about quick processing (e.g. visual particles), I update them only once per iteration (using the delta time).

I'm usually using a main loop like this:

```
sf::Time updateTime;
sf::Clock updateClock

while (window.isOpen()) {
    // Event handling is performed here

    // Determine the time that passed
    sf::Time delta = updateClock.restart();

    updateTime += delta; // add up previous leftover time

    int loops = std::min<int>((int)(updateTime / sf::milliseconds(10)), 10); // determine the number of iterations to do (100 fps; capped at 10)
    while (loops--)
        updateSingleStep(); // update by one fixed timestep

    updateTime %= sf::milliseconds(10); // drop leftover frames

    updateDeltaTime(delta); // update based on time passed

    window.clear();
    // rendering
    window.display();

    sf::Sleep(sf::microsecond(1)); // sleep a minimum amount of time to ensure there's always at least some delta time (assuming very, very fast CPUs).
}

```

Of course it's important to remember to keep the update loops separated, e.g. fixed timesteps shouldn't rely on the delta timesteps to run at the "same speed", because frame drops can cause discrepancies.
> 1 votes

---
Tags: c++, sfml
---


title: How does MMO flash games works?

text:
# Question
Title: How does MMO flash games works?
I want to know how does MMO flash games work, for example: Dofus and Club Penguin.

I want to know if by ony using Adobe Flash and ActionScript you can do MMO games, or if there is other way to work with ActionScript and Flash beyond Adobe Flash.

# Answer
> 2 votes
As stated in comments no answer could really be definitive here, but you must be aware of the fact that Flash is getting more and more deprecated, that Games like Dofus have a very strict production process (and huge library of code) to overcome the fragilities of Flash.

To answer your questions:

* You *can* make MMOs with flash *but*, with the current state of technology it does not mean you should.
* Adobe Flash is an IDE for Flash devs and artists, it is developed by Adobe, the creators of Flash so despite the fact that some free platform exist you will *hardly* find better,
* In our days and time, there is new technologies which will provide more integrated results, for example HTML5 and Ajax (or if you like adobe, Adobe Air).

I tell all that because if you ask this question it is probably that you want to start a project but do not know the technology (no harm in that :D ) and to save you time and money I strongly suggest you to learn HTML5 as it will always be useful later.

To go back to Dofus, people over there are very talented and they are using Flash because at the time they created Dofus it was the best API providing the Art/Code balance they needed (Art in Dofus it the state of the Art in terms of vector art...)

---
Tags: flash, actionscript-3, mmo
---


# Question
Title: How to associate entities in a Entity Component System (Artemis)
I want to implement an association between 2 entities in a ECS architecture using Artemis framework, which handles Components, Entities and Systems very well for me.

I have an entity "Empire" (with several components like Empire ID, researched technologies, etc), and I would wish to establish "diplomacy" between 2 Empires (War, Peace).

In which way could I implement that with an ECS architecture? I know about unite components, but not relating entities.

Thank you

# Answer
You may be falling into a common trap. Entity component systems are very neat and useful, but they shouldn't be used for *everything*.

Simply add an `Information` component to your entities that contains, among other information, their empire affiliation.

This component can be utilized by lots of other systems, including the whatever `Combat` system you have. The `Combat` system can look at the empires and see if they're at war or not when deciding to attack.

The entire diplomacy system doesn't need to be in the entity component framework. It can be a separate system entirely.
> 3 votes

# Answer
I would approach this much like most games do using some form of a `Faction` system. Basically, a collective unit of objects, in your case the Empire; hold a `FactionComponent` managed by a faction system. As specific peace talks, treaties signed, etc occur you increase the faction level of one empire in relation to another empire. As specific events happen that are hostile between two empires, you lower the faction level between the two, perhaps placing them at war.

Based on the faction system, you can now differ between hostile and friendly targets quite easily all based on their level of faction between one another. The faction system becomes the glue or the association system that manages the relationship between the owners of these faction components.
> 0 votes

---
Tags: entity-system, artemis
---


# Question
Title: How can I make my sprite jump up and move forward at the same time?
I'm trying to make a sprite's movements work. For some reason, he can only jump and then move, or move and then jump, but never at the same time. I'm using `InputProcessor` and a `TiledMap` system. Here's some code :

```
@Override
public boolean keyDown(int keycode) {
    switch(keycode) {
    case Keys.W:
        if(canJump) {
        velocity.y = speed;
        canJump = false;
        }
        break;
    case Keys.A:
        velocity.x = -speed;
        break;
    case Keys.D:
        velocity.x = speed;
        break;
    }
    return true;
}

@Override
public boolean keyUp(int keycode) {
    switch(keycode) {
    case Keys.W:
        velocity.y = 0;
        break;
    case Keys.A:
        velocity.x = 0;
        break;
    case Keys.D:
        velocity.x = 0;
        break;
    }
    return true;
}

```

# Answer
Ok guys, I think that the problem was that **my computer can't detect the keypressess**, but my friends tested it out and they could go diagonally! Thanks for all your suggestions, and sorry about wasting Internet space on a useless question, and have a Merry Christmas and Happy New Year!
> 0 votes

# Answer
Create booleans W, A and D. Set them to true on keyDown and set them to false on keyUp, then in your game loop or update function, check the variables to see if the keys are being held and manipulate your sprite from there.
> 0 votes

---
Tags: libgdx, input, jumping
---


title: How to set speed based on screen size

text:
# Question
Title: How to set speed based on screen size
I am making a breakout clone for mobile and was wanting to make the ball speed to be related to the screen size. Larger screen would mean faster speed.

Right now I have it set like so:

```
dirx=math.random(-5,5)*(maxx/320)
diry=math.random(3,7)*(maxy/480)

```

My reasoning for this is that 320x480 is iPhone resolution so I figured it would be a good base to start at. For the record, it actually runs pretty well on iPhone setting.

Then for the actual movement I just add `dir` to the appropriate direction.

```
ball.x=ball.x+dirx
ball.y=ball.y+diry

```

The problem is if I change to a device with a larger screen resolution, the ball is crazy fast and is very jumpy.

Is some kind of formula that I can use to multiply to the `random` that will make the speed appear uniform across devices?

# Answer
You really shouldn't use pixel coordinates for game logic.

Just use coordinates that are independent of screen size, and make rendering code account for different screen sizes, this way you get much more flexible and maintainable code.

So for example assume you are using 1 meter as one unit. Your screen is 2 meters high and 1 meter wide(on every device). So the resulting pixel position can be calculated like:

```
PixelCoord.x = Coordinate.x * (DeviceSize.x / TableSize.x)
PixelCoord.y = Coordinate.y * (DeviceSize.y / TableSize.y)

```

where `Devicesize` is the device resolution and `TableSize` is the size of play area in meters( in this case the latter is `{ x=1, y=2 }` )

Note: This is just a very simple implementation, and needs some refinement, but I hope that you get the idea.

Note 2: I assume you are using floating point numbers to represent coordinates.(should be the case already with lua.)

Edit:

In the example above `Coordinate.xy`(the position of the object) ranges`[0, TableSize.xy]`, which means `x - [0,1]` `y - [0, 2]`. So for example an object in the middle of the screen would have the coordinates `[0.5, 1]`
> 5 votes

---
Tags: lua, corona-sdk
---