# Question
Title: Customize Colors for Sprites in Web Game
So I'm working on an html5/javascript/css3-based game. Without going into too much detail, I'm thinking of having the characters be simple 8 or 16-bit style sprites, but I'd like to allow the user to customize the colors of their character.

Here are some examples of what I'm talking about :

http://jsfiddle.net/simurai/CGmCe/light/
http://www.splashnology.com/article/sprite-animation-in-css3/1485/

So the problem I'm having is two-fold:

1) Should I use something other than a sprite map for my characters, like actually draw them as shapes and animate them in a canvas element? That way I can fill the sprite with colors of the user's choosing? My fear there is that this would be inefficient as far as resources and also waste a lot of time hand-drawing everything, but could allow other customization (like height/width etc).

2) Are there potentially some web apis that would allow you to alter colors inside of a sprite? I suppose I could do it on the back-end with GD, but I'm trying to make it entirely in-browser (including local storage).

It's not a definitive one-answer only question, but I'm hoping someone can suggest something they've seen that approaches the same problem from another angle or gives us a way to customize the sprites or manipulate them in some manner. Or avoid them altogether, and use a different method.

# Answer
## Answer to 1 & 2

Color Palette changing -\>Take a look here\<- Showing both client & server side color pallete changing in the two answers.

After you altered the pixels to your will. Retrieve the DataURL by calling

```
var newImgSrc = canvas.toDataURL(); //gets a base64 encoded PNG image

```

Now for a CSS3 game, edit the src attribute of the tag if it's added to the DOM.

```
imgInDom.setAttribute('src',newImgSrc); //Or use a jQuery equivalent function.

```

OR,

```
var newImg = new Image(); //create a new Image object
//document.createElement('img') does the same stuff.
//render image after it loads or else you wont see anything on the canvas.
newImg.onload = function(){
   //render it or append it to the DOM
}
newImg.src = newImgSrc; //specify the src of the Image, loads almost instantaneously
//For a CSS3 game, you may skip the onload handler function.
//And directly append the element to the DOM.

```

See more at MDN & Google Search
> 3 votes

---
Tags: javascript, sprites, html5
---


# Question
Title: What legal matters do I need to consider when releasing an MMO?
*Let's say* I've finished programming an indie MMO game similiar to *Tibia*. I've got:

* a stable server application ready to launch;
* a tested, bug-free, working client application ready to play;
* the game's official website (ready to host), with a *payment system* and freely downloadable game client.

No matter how impossible it sounds, let's also assume none of these break copyright laws.

My game divides accounts into *free* and *premium* groups. *Premium* accounts can access all game features, requiring server authorisation to work properly. Let's say that the "premium account" can be bought on the website for a fixed monthly rate. *Free* accounts can play for free, but with limited access. This is what the mentioned *payment system* will be for. If I've correctly understood, this is the freemium model.

I'm completely novice to business entity issues, so **in short: what steps, in legal terms, do I have to take from here so my game can legally earn me money?** For example, is there something like verification that the game gives the user what it actually offers when paying on its website?

If relevant, I live in Europe.

# Answer
> 16 votes
As made painfully obvious by recent events, 'Europe' is not a unified place in terms of laws or taxation, so giving a definitive answer here would be tricky to say the least. Even EU law is only a guide as each member state implements it differently.

Generally speaking, everything is legal until decided otherwise, so it's not so much "how do I earn money legally" but more "how do I avoid breaking laws when taking people's money".

Nobody can give you a comprehensive list of things to watch out for here - not even a lawyer, though they will most likely do a better job than me, for a price - but here are some you will need to consider in terms of money coming in:

* Business tax - most countries expect your business to pay tax on profits, or similar.
* Income tax - you will probably have to pay tax on your own income from the company.
* Value-added tax - some jurisdictions require that you pay VAT on services you sell.
* Trade laws - each country has its own laws on sales of goods and services, usually requiring that the goods/services are of reasonable quality, fit for purpose, matching the description, etc. Buyers may be entitled to refunds or replacements in certain circumstances, and there may also be laws that state that a buyer is entitled to a 'cooling down' period after purchase during which they can change their mind and receive a refund.
* Record-keeping - in the UK at least, companies need to keep records of your accounts for almost six years after the tax year they relate to. Your jurisdiction may be the same.

Then there are various other laws you need to be careful not to fall foul of:

* Storing user data - many countries have restrictions on what data you can collect from users, how long you can store it for, what form you have to store it in, whether you can disclose it to others, whether the user is entitled to see a copy of their data, etc.
* Other privacy issues - Storing cookies on an end user's machine requires their permission, if I read recent EU law correctly. Anything similar to a cookie mechanism is probably covered.
* Employment law - if you pay anybody to help with your game, you will need to follow various employment related laws. Note that if you accept volunteer labour, this may also end up being covered (especially by minimum wage laws), although I am unsure if it's been tested in EU courts so far.
* Libel, slander, defamation - If people use your service to illegally criticise others, you may be liable for facilitating it, depending on the nature of your service.
* Copyright and IP - even if your game does not infringe copyright, if it's possible for users to use it to infringe copyright, you could be held liable.

# Answer
> 5 votes
Others are saying to start with a lawyer or a publisher. While I agree that a lawyer will be important to the process (a publisher is not critical, and should be thought about with skepticism for indie games), the most important person to answer your question would actually be an accountant.

In the U.S. (and I am sure Europe) business accountants have a great deal of required knowledge of laws, taxation, and regulation that are required in order to gain certification. So, instead of running to an attorney, who may or may not understand this area of law, go first to an accountant who is certified to handle domestic accounts. Because the EU has intricate rules governing interstate commerce, a good place to start would be this site:

http://europa.eu/youreurope/business/managing-business/keeping-accounts/france/index\_en.htm

A proper accountant will be able to do everything from setting up your payment system to explaining the various legalities of charging folks in different countries, tax handling, etc. The lawyer will not likely know these things explicitly unless they specialize in that specific area, which will be rare and expensive.

# Answer
> 3 votes
Indie workflow:

1. Make the game
2. Find publishers
3. Find a cheap attorney to get the general advice of protecting your game
4. Submit to publishers
5. Consult with an accountant
6. Let your publisher tell you what to do next

I say all this just to say, make your game first then worry about this stuff. If you make something worth selling you will have to commit a small amount of funds to getting valid advice and not random people's understanding of business and tax law

---
Tags: mmo, legal, business, release
---


# Question
Title: Ideas for time-keeping in a webbased RPG?
I'm assigned a task of doing the preliminary research stuff for a web-based MMO RPG. Now my buggiest problem here is "web based" vs "MMO RPG". I did some research about time keeping systems and I'm totally confused as how exactly something as real-time as an MMO-RPG can work on some pull-only (unidirectional) platform like HTTP.

I know there is also a turn-based alternative to time keeping but can it work in an MMO setting ?

EDIT: Take a battle for example, player A (human) wants to attack Player B (also human) in the open. How does it work when when player A issues the "attack" command on player B ? how do I inform player B that he is being attacked ? and then how exactly the battle goes on between the two in an HTTP based communication channel?

To my knowledge this is impossible unless you resort to another technology (HTML is 1-way, that is you can just ask server and get response, server can't update you unless being asked to. this is very well-known and simply explained). So I though maybe I can somehow change the whole timekeeping model from real-time to a more non-real-time model (towards a turn based RPG for example) and somehow work around the whole problem of "interactivity".

EDIT2: It is not that I don't wanna use any server side technologies. For sure it is not gonna work client-side-only even for the most trivial of the multi-player games, let alone an RPG. So sure there would be a (probably complex) server side component to it (the so called Game Engine I suppose). The problem is not the technology that implements the logic (game mechanics) bits but the communication technology and how it limits the game mechanics abilities (like how real-time or turn based it is gonna be). HTTP is a request-response protocol meaning you get served only if you ask for it (explicitly send a GET or POST request to the server). HTTP server *can not* inform you if anything of interest happens in the game world unless you refresh the page (as some suggested) or you use some bi-directional tech (totally different animals) like Flash, WebSock, HTML5 etc etc.

So maybe the question is: Is it possible to implement a MMORPG using only HTML5/PHP and no periodic page refreshes? if so what would be rules to make it an MMO-RPG?

Can't explain it any clearer. Sorry :D

# Answer
If you need realtime push you will probably end-up using some sort of TCP mechanism for your client.

If you use flash have a look at flash.net.Socket

Else for HTML5/javascript you could use the WebSocket API for modern browsers. To add support for the older ones you could get inspired by this answer. It suggests using java or action script to bridge your JS client with your server:

On the other hand if lag is not the major issue then you can start prototyping with the usual HTTPRequest methods.

---

**Edit** in answer to ashy\_32bit's:

> I want to make an MMORPG work in a non-real-time platform like classic HTML+Java script (read Ajax) and not any fancy Flash or HTML5 or client-server or anything

Consider using JSON if you need a simple data interchange format. It became very much the defacto standard, It is used even in AAA C++ games for things like leader boards, social integration, micro transactions...

Also what do you mean by RPG? Today this monicker is used for a large variety of games, from text to action RPGs going through card and figurines based games.

I would strongly suggest you play a few web based MMOs first and then you can start figuring out what you really want to do.

Will your game be more text based? Will it be more graphics based. Will the graphics be static, will they move and interact like in action games?

## Text/static graphics

The thing about existing web based MMOs is that they are mostly text based or rely heavily on static graphics. They already include mechanisms for combat resolution. Usually they are either turn based and the user's client interface will simply fetch the latest events and highlight the ones that have not been highlighted yet.

Players periodically receive an amount of actions to execute, can accumulate a fixed amount of actions and can spend them for buildings/unit generation, research, attacks etc...

In this case the server can simply react on the clients' requests by fetching data relevant to the player, handling the player's action fetching and sorting the data relevant since the last acknowledged request and sending the results (either as a new page or in the form of a XML/JSON result).

## Action

Realtime MMOs rely heavily on animations and large amounts of data about the immediate state of other players/mobs/environment. You will rather stream deltas of the game state in the zone/instance relevant to each players.

In that case using binary data over UDP or TCP is deemed preferable. The more players you have to serve the more compression and savings you have to do in regard of data transmission.

Also you want your server to run the game environment instead of simply fetching data calculating and storing sending the result because the amount of actions, interactions is much larger you can't simply keep fetching and pushing data to your store. It has to live in the server's RAM and be periodically saved but not upon every action.

---

> Is it possible to implement a MMORPG using only HTML5/PHP and no periodic page refreshes?

Yes. You can. But when you speak about HTML5 it includes javascript. It means you intend to refresh the content of a canvas or on the page dynamically. And PHP is not suitable for more action oriented games.

For more action intensive games I would recommend writing your server with - in order of preference:

* ERLANG which is made for large distributed systems. Remember as a game grows the server side will have to grow: become distributed. And while PHP+SQL seem like a good solutions for scaling there are other solutions. This presentation is not fully relevant to the subject but it demonstrates the usefulness of the language in situations involving large amounts of users.
* C/C++ the amount of games written in this language attests of its popularity. It will be much more powerful. As you have direct access to primitive data structures you can also harness the power of hardware accelerated features like OpenCL. And it will be easier to find game developers who have good experience writing games in C/C++. But if you are not familiar with it I would not recommend using it for your server.
* Java. It's easier to quickly write a game server in java. Like with C++ you can then either create your own syncing mechanism across servers or simply break the game into zones and/or instances.

> if so what would be rules to make it an MMO-RPG?

This question is very weird. My answer would be; allow a large amount of people to interact in a role playing game...
> 6 votes

# Answer
Here is how it was done in olde web-based RPGs circa 10 years ago:

* HTML Meta Refresh tag was used to automatically refresh the combat page (or maybe iframe) each N seconds
* In one of those games combat worked the following way: it consisted of rounds, and in each round the participants had limited time (say 15 seconds) to submit their turns. These turns then resolved simultaneously.

On the top of my head, here is how I would implement a simple game like that:

* Store *all* game state (e.g. location of all players and NPCs, current state of all fights in progress etc.) in an SQL database, rather then having it in the memory of a game server application. This automatically gives you persistence and thread-safety.
* Implement a set of scripts for players to interact with the game world. Since you use a database, it could be even something as simple as PHP scripts. For example, you could have a `move.php` script, which would accept `location` parameter. After checking all game rules (e.g. how often and where the player is allowed to move?), this script would issue a query to the database to change the location of the currently logged character ID (which would be stored as a cookie)
* Create another "game loop" script that would be executed regularly. You can do it with cron, or simply implement an actual loop, which would sleep for, say, 1 second after each iteration. The purpose of this script is to increment the game time counter and resolve timed events, for example, advance fights to the next round each 15 seconds.
* Finally, make the primary interface script, which would automatically update using the `meta refresh` HTML tag. The server would generate the correct page depending on the state of the player character, e.g. if it is currently in a fight, the page would contain buttons for possible abilities that can be used in a fight.

Alternatively, instead of many separate scripts, you can have a single game server application that would listen to HTTP requests and process them accordingly.
> 4 votes

# Answer
I'm by far no expert, but if you want 2 human players to be able to interact in anyway you need some form of server-side language, simple html dont have the functionality needed. You need to somehow store/get the actions they perform.

Might be possible with WebSQL though but then again it is HTML5.

Why exactly don't you want to use server-side?
> 1 votes

# Answer
Without using something like flash or a websocket, there is still a way you can facilitate bi-directional communication, though it is it a bit of a hack: http://en.wikipedia.org/wiki/Comet\_(programming)

Essentially, you are making an HTTP request for which the server does not specify a size, so the browser will hold it open and the server can then continue to push data as events occur. The client can then make additional requests in the normal way which the server will process, update its state and then push out updates to the clients through these standing requests.

In terms of it being "real time", there are two basic approaches you can take, which really depend on what sort of events are taking place in your game.

The first would be to have a "tick", where the server refreshes the state of the game on some interval. If you need smooth, continuous movement, this is probably what you want. The exact rate depends on how frequently the client needs to be updated in order to not feel laggy. For reference, a fast paced action game will usually feel pretty good at a frame rate as low as 20 frames per second (50ms per frame), less action means you can push that up higher and thus stress the server less.

The other option is to schedule events. If you have discrete movement (i.e. on a grid) and action durations that tend to be measured in seconds, this might be a better approach. Each time some action takes place, you add it to the schedule, which fires off some sort of notification or callback when the event needs to be resolved.
> 1 votes

# Answer
Take a look at Node.js \+ socket.io combination. I'm currently finishing a multiplayer browser game with it and I'm very satisfied how it works. socket.io uses websockets by default, but falls back to flash sockets and then XHR, JSONP, htmlfile and other long-polling/Comet variants. This allows you to cover all browsers using a single, very simple interace.
> 1 votes

---
Tags: mmo, rpg, web
---


# Question
Title: Access violation in DirectX OMSetRenderTargets
I receive the following error when running the Triangle sample application for DirectX 11 in `D3D_FEATURE_LEVEL_9_1`:

> Unhandled exception at 0x527DAE81 (d3d11\_1sdklayers.dll) in Lesson2.Triangles.exe: 0xC0000005: Access violation reading location 0x00000000

This error occurs at the OMSetRenderTargets function, as shown below, and does not happen if I remove that function from the program (but then, the screen is blue, and does not render the triangle)

```

//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//// PARTICULAR PURPOSE.
////
//// Copyright (c) Microsoft Corporation. All rights reserved

#include
#include
#include "DirectXSample.h"
#include "BasicMath.h"
#include "BasicReaderWriter.h"

using namespace Microsoft::WRL;
using namespace Windows::UI::Core;
using namespace Windows::Foundation;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::ApplicationModel::Infrastructure;

// This class defines the application as a whole.
ref class Direct3DTutorialViewProvider : public IViewProvider
{
private:
    CoreWindow^ m_window;
    ComPtr m_swapChain;
    ComPtr m_d3dDevice;
    ComPtr m_d3dDeviceContext;
    ComPtr m_renderTargetView;

public:
    // This method is called on application launch.
    void Initialize(
        _In_ CoreWindow^ window,
        _In_ CoreApplicationView^ applicationView
        )
    {
        m_window = window;
    }

    // This method is called after Initialize.
    void Load(_In_ Platform::String^ entryPoint)
    {
    }

    // This method is called after Load.
    void Run()
    {
        // First, create the Direct3D device.

        // This flag is required in order to enable compatibility with Direct2D.
        UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;

#if defined(_DEBUG)
        // If the project is in a debug build, enable debugging via SDK Layers with this flag.
        creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

        // This array defines the ordering of feature levels that D3D should attempt to create.
        D3D_FEATURE_LEVEL featureLevels[] =
        {
            D3D_FEATURE_LEVEL_11_1,
            D3D_FEATURE_LEVEL_11_0,
            D3D_FEATURE_LEVEL_10_1,
            D3D_FEATURE_LEVEL_10_0,
            D3D_FEATURE_LEVEL_9_3,
            D3D_FEATURE_LEVEL_9_1
        };

        ComPtr d3dDevice;
        ComPtr d3dDeviceContext;
        DX::ThrowIfFailed(
            D3D11CreateDevice(
                nullptr,                    // specify nullptr to use the default adapter
                D3D_DRIVER_TYPE_HARDWARE,
                nullptr,                    // leave as nullptr if hardware is used
                creationFlags,              // optionally set debug and Direct2D compatibility flags
                featureLevels,
                ARRAYSIZE(featureLevels),
                D3D11_SDK_VERSION,          // always set this to D3D11_SDK_VERSION
                &d3dDevice,
                nullptr,
                &d3dDeviceContext
                )
            );

        // Retrieve the Direct3D 11.1 interfaces.
        DX::ThrowIfFailed(
            d3dDevice.As(&m_d3dDevice)
            );

        DX::ThrowIfFailed(
            d3dDeviceContext.As(&m_d3dDeviceContext)
            );

        // After the D3D device is created, create additional application resources.
        CreateWindowSizeDependentResources();

        // Create a Basic Reader-Writer class to load data from disk.  This class is examined
        // in the Resource Loading sample.
        BasicReaderWriter^ reader = ref new BasicReaderWriter();

        // Load the raw vertex shader bytecode from disk and create a vertex shader with it.
        auto vertexShaderBytecode = reader->ReadData("SimpleVertexShader.cso");
        ComPtr vertexShader;
        DX::ThrowIfFailed(
            m_d3dDevice->CreateVertexShader(
                vertexShaderBytecode->Data,
                vertexShaderBytecode->Length,
                nullptr,
                &vertexShader
                )
            );

        // Create an input layout that matches the layout defined in the vertex shader code.
        // For this lesson, this is simply a float2 vector defining the vertex position.
        const D3D11_INPUT_ELEMENT_DESC basicVertexLayoutDesc[] =
        {
            { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0,  0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
        };

        ComPtr inputLayout;
        DX::ThrowIfFailed(
            m_d3dDevice->CreateInputLayout(
                basicVertexLayoutDesc,
                ARRAYSIZE(basicVertexLayoutDesc),
                vertexShaderBytecode->Data,
                vertexShaderBytecode->Length,
                &inputLayout
                )
            );

        // Load the raw pixel shader bytecode from disk and create a pixel shader with it.
        auto pixelShaderBytecode = reader->ReadData("SimplePixelShader.cso");
        ComPtr pixelShader;
        DX::ThrowIfFailed(
            m_d3dDevice->CreatePixelShader(
                pixelShaderBytecode->Data,
                pixelShaderBytecode->Length,
                nullptr,
                &pixelShader
                )
            );

        // Create vertex and index buffers that define a simple triangle.

        float3 triangleVertices[] =
        {
            float3(-0.5f, -0.5f,13.5f),
            float3( 0.0f,  0.5f,0),
            float3( 0.5f, -0.5f,0),
        };

        D3D11_BUFFER_DESC vertexBufferDesc = {0};
        vertexBufferDesc.ByteWidth = sizeof(float3) * ARRAYSIZE(triangleVertices);
        vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
        vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
        vertexBufferDesc.CPUAccessFlags = 0;
        vertexBufferDesc.MiscFlags = 0;
        vertexBufferDesc.StructureByteStride = 0;

        D3D11_SUBRESOURCE_DATA vertexBufferData;
        vertexBufferData.pSysMem = triangleVertices;
        vertexBufferData.SysMemPitch = 0;
        vertexBufferData.SysMemSlicePitch = 0;

        ComPtr vertexBuffer;
        DX::ThrowIfFailed(
            m_d3dDevice->CreateBuffer(
                &vertexBufferDesc,
                &vertexBufferData,
                &vertexBuffer
                )
            );

        // Once all D3D resources are created, configure the application window.

        // Allow the application to respond when the window size changes.
        m_window->SizeChanged +=
            ref new TypedEventHandler(
                this,
                &Direct3DTutorialViewProvider::OnWindowSizeChanged
                );

        // Specify the cursor type as the standard arrow cursor.
        m_window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);

        // Activate the application window, making it visible and enabling it to receive events.
        m_window->Activate();

        // Enter the render loop.  Note that tailored applications should never exit.
        while (true)
        {
            // Process events incoming to the window.
            m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);

            // Specify the render target we created as the output target.
            ID3D11RenderTargetView* targets[1] = {m_renderTargetView.Get()};
            m_d3dDeviceContext->OMSetRenderTargets(
                1,
                targets,
                NULL // use no depth stencil
                );

            // Clear the render target to a solid color.
            const float clearColor[4] = { 0.071f, 0.04f, 0.561f, 1.0f };
//Code fails here
            m_d3dDeviceContext->ClearRenderTargetView(
                m_renderTargetView.Get(),
                clearColor
                );

            m_d3dDeviceContext->IASetInputLayout(inputLayout.Get());

            // Set the vertex and index buffers, and specify the way they define geometry.
            UINT stride = sizeof(float3);
            UINT offset = 0;
            m_d3dDeviceContext->IASetVertexBuffers(
                0,
                1,
                vertexBuffer.GetAddressOf(),
                &stride,
                &offset
                );

            m_d3dDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

            // Set the vertex and pixel shader stage state.
            m_d3dDeviceContext->VSSetShader(
                vertexShader.Get(),
                nullptr,
                0
                );

            m_d3dDeviceContext->PSSetShader(
                pixelShader.Get(),
                nullptr,
                0
                );

            // Draw the cube.
            m_d3dDeviceContext->Draw(3,0);

            // Present the rendered image to the window.  Because the maximum frame latency is set to 1,
            // the render loop will generally be throttled to the screen refresh rate, typically around
            // 60Hz, by sleeping the application on Present until the screen is refreshed.
            DX::ThrowIfFailed(
                m_swapChain->Present(1, 0)
                );
        }
    }

    // This method is called before the application exits.
    void Uninitialize()
    {
    }

private:

    // This method is called whenever the application window size changes.
    void OnWindowSizeChanged(
        _In_ CoreWindow^ sender,
        _In_ WindowSizeChangedEventArgs^ args
        )
    {
        m_renderTargetView = nullptr;
        CreateWindowSizeDependentResources();
    }

    // This method creates all application resources that depend on
    // the application window size.  It is called at app initialization,
    // and whenever the application window size changes.
    void CreateWindowSizeDependentResources()
    {
        if (m_swapChain != nullptr)
        {
            // If the swap chain already exists, resize it.
            DX::ThrowIfFailed(
                m_swapChain->ResizeBuffers(
                    2,
                    0,
                    0,
                    DXGI_FORMAT_R8G8B8A8_UNORM,
                    0
                    )
                );
        }
        else
        {
            // If the swap chain does not exist, create it.
            DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};

            swapChainDesc.Stereo = false;
            swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
            swapChainDesc.Scaling = DXGI_SCALING_NONE;
            swapChainDesc.Flags = 0;

            // Use automatic sizing.
            swapChainDesc.Width = 0;
            swapChainDesc.Height = 0;

            // This is the most common swap chain format.
            swapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

            // Don't use multi-sampling.
            swapChainDesc.SampleDesc.Count = 1;
            swapChainDesc.SampleDesc.Quality = 0;

            // Use two buffers to enable flip effect.
            swapChainDesc.BufferCount = 2;

            // We recommend using this swap effect for all applications.
            swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;

            // Once the swap chain description is configured, it must be
            // created on the same adapter as the existing D3D Device.

            // First, retrieve the underlying DXGI Device from the D3D Device.
            ComPtr dxgiDevice;
            DX::ThrowIfFailed(
                m_d3dDevice.As(&dxgiDevice)
                );

            // Ensure that DXGI does not queue more than one frame at a time. This both reduces
            // latency and ensures that the application will only render after each VSync, minimizing
            // power consumption.
            DX::ThrowIfFailed(
                dxgiDevice->SetMaximumFrameLatency(1)
                );

            // Next, get the parent factory from the DXGI Device.
            ComPtr dxgiAdapter;
            DX::ThrowIfFailed(
                dxgiDevice->GetAdapter(&dxgiAdapter)
                );

            ComPtr dxgiFactory;
            DX::ThrowIfFailed(
                dxgiAdapter->GetParent(
                    __uuidof(IDXGIFactory2),
                    &dxgiFactory
                    )
                );

            // Finally, create the swap chain.
            DX::ThrowIfFailed(
                dxgiFactory->CreateSwapChainForImmersiveWindow(
                    m_d3dDevice.Get(),
                    DX::GetIUnknown(m_window),
                    &swapChainDesc,
                    nullptr, // allow on all displays
                    &m_swapChain
                    )
                );
        }

        // Once the swap chain is created, create a render target view.  This will
        // allow Direct3D to render graphics to the window.

        ComPtr backBuffer;
        DX::ThrowIfFailed(
            m_swapChain->GetBuffer(
                0,
                __uuidof(ID3D11Texture2D),
                &backBuffer
                )
            );

        DX::ThrowIfFailed(
            m_d3dDevice->CreateRenderTargetView(
                backBuffer.Get(),
                nullptr,
                &m_renderTargetView
                )
            );

        // After the render target view is created, specify that the viewport,
        // which describes what portion of the window to draw to, should cover
        // the entire window.

        D3D11_TEXTURE2D_DESC backBufferDesc = {0};
        backBuffer->GetDesc(&backBufferDesc);

        D3D11_VIEWPORT viewport;
        viewport.TopLeftX = 0.0f;
        viewport.TopLeftY = 0.0f;
        viewport.Width = static_cast(backBufferDesc.Width);
        viewport.Height = static_cast(backBufferDesc.Height);
        viewport.MinDepth = D3D11_MIN_DEPTH;
        viewport.MaxDepth = D3D11_MAX_DEPTH;

        m_d3dDeviceContext->RSSetViewports(1, &viewport);
    }
};

// This class defines how to create the custom View Provider defined above.
ref class Direct3DTutorialViewProviderFactory : IViewProviderFactory
{
public:
    IViewProvider^ CreateViewProvider()
    {
        return ref new Direct3DTutorialViewProvider();
    }
};

[Platform::MTAThread]
int main(array^)
{
    auto viewProviderFactory = ref new Direct3DTutorialViewProviderFactory();
    Windows::ApplicationModel::Core::CoreApplication::Run(viewProviderFactory);
    return 0;
}

```

# Answer
> 0 votes
This bug was fixed in the Release Preview of Windows 8.

# Answer
> 0 votes
This likely means the render target is NULL or otherwise invalid. You should use a breakpoint in your debugger to stop the program, examine the variables and see what's going on.

# Answer
> 0 votes
IIRC, you have to get the UUID of the back buffer first

```
// Create a render target view
ID3D11Texture2D* pBackBuffer = NULL;
hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer );
if( FAILED( hr ) )
    return hr;

hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRenderTargetView );
pBackBuffer->Release();
if( FAILED( hr ) )
    return hr;

g_pImmediateContext->OMSetRenderTargets( 1, &g_pRenderTargetView, NULL );

```

# Answer
> -1 votes
Remove the line below and try again.

```
creationFlags |= D3D11_CREATE_DEVICE_DEBUG;

```

---
Tags: directx11, c++cli
---


title: Understanding how OpenGL blending works

text:
# Question
Title: Understanding how OpenGL blending works
I am attempting to understand how OpenGL (ES) blending works. I am finding it difficult to understand the documentation and how the results of glBlendFunc and glBlendEquation effect the final pixel that is written.

Do the source and destination out of glBlendFunc get added together with GL\_FUNC\_ADD by default?

This seems wrong because "basic" blending of GL\_ONE, GL\_ONE would output 2,2,2,2 then (Source giving 1,1,1,1 and dest giving 1,1,1,1).

I have written the following pseudo-code, what have I got wrong?

```
struct colour {
    float r, g, b, a;
};

colour blend_factor( GLenum factor,
    colour source,
    colour destination,
    colour blend_colour ) {

    colour colour_factor;
    float i = min( source.a, 1 - destination.a );

    // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glBlendFunc.xml
    switch( factor ) {
        case GL_ZERO: colour_factor = { 0, 0, 0, 0 }; break;
        case GL_ONE: colour_factor = { 1, 1, 1, 1 }; break;
        case GL_SRC_COLOR: colour_factor = source; break;
        case GL_ONE_MINUS_SRC_COLOR: colour_factor = { 1 - source.r, 1 - source.g, 1 - source.b, 1 - source.a }; break;
        // ...
    }

    return colour_factor;
}

colour blend( colour & source,
    colour destination,
    GLenum source_factor, // from glBlendFunc
    GLenum destination_factor, // from glBlendFunc
    colour blend_colour, // from glBlendColor
    GLenum blend_equation // from glBlendEquation
    ) {

    colour source_colour = blend_factor( source_factor, source, destination, blend_colour );
    colour destination_colour = blend_factor( destination_factor, source, destination, blend_colour );
    colour output;

    // From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glBlendEquation.xml
    switch( blend_equation ) {
        case GL_FUNC_ADD: output = add( mul( source, source_colour ), mul( destination, destination_colour ) );
        case GL_FUNC_SUBTRACT: output = sub( mul( source, source_colour ), mul( destination, destination_colour ) );
        case GL_FUNC_REVERSE_SUBTRACT: output = sub( mul( destination, destination_colour ), mul( source, source_colour ) );
    }

    return output;
}

void do_pixel() {

    colour final_colour;

    // Blending
    if( enable_blending ) {

        final_colour = blend( current_colour_output, framebuffer[ pixel ], ... );
    } else {

        final_colour = current_colour_output;
    }

}

```

Thanks!

# Answer
> 5 votes
```
case GL_FUNC_ADD: output = add( source_colour, destination_colour )

```

This is where you've gone wrong. The source and destination factors are multiplied into the source and destination colors, *then* added together. The OpenGL Wiki article on blending goes into greater detail on this matter.

---
Tags: opengl, blending
---


# Question
Title: Why does creating dynamic bodies in JBox2D freeze my app?
My game hangs/freezes when I create dynamic bullet objects with Box2D and I don't know why. I am making a game where the main character can shoot bullets by the user tapping on the screen. Each touch event spawns a new `FireProjectileEvent` that is handled properly by an event queue. So I know my problem is not trying to create a new body while the box2d world is locked. My bullets are then created and managed by an object pool class like this:

```
public Projectile getProjectile(){
    for(int i=0;i<mProjectiles.size();i++){
        if(!mProjectiles.get(i).isActive){
            return mProjectiles.get(i);
        }
    }

    return mSpriteFactory.createProjectile();

}

```

`mSpriteFactory.createProjectile()` leads to the physics component of the Projectile class creating its box2d body. I have narrowed the issue down to this method and it looks like this:

```
public void create(World world, float x, float y, Vec2 vertices[], boolean dynamic){

    BodyDef bodyDef = new BodyDef();
    if(dynamic){
        bodyDef.type = BodyType.DYNAMIC;
    }else{
        bodyDef.type = BodyType.STATIC;
    }
    bodyDef.position.set(x, y);
    mBody = world.createBody(bodyDef);

    PolygonShape dynamicBox = new PolygonShape();
    dynamicBox.set(vertices, vertices.length);
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = dynamicBox;
    fixtureDef.density = 1.0f;
    fixtureDef.friction = 0.0f;
    mBody.createFixture(fixtureDef);
    mBody.setFixedRotation(true);

}

```

If the dynamic parameter is set to true my game freezes before crashing, but if it is false, it will create a projectile exactly how I want it just doesn't function properly (because a projectile is not a static object). **Why does my program fail when I try to create a dynamic object at runtime but not when I create a static one?** I have other dynamic objects (like my main character) that work fine. Any help would be greatly appreciated.

This is a screenshot of a method profile I did: Especially notable is number 8. I'm just still unsure what I'm doing wrong.

Other notes:
I am using JBox2D 2.1.2.2. (Upgraded from 2.1.2.1 to try to fix this problem)
When the application freezes, if I hit the back button, it appears to move my game backwards by one update tick. Very strange.

# Answer
It turned out that the vertices of my bullets were not making proper shapes due to a simple mistake.

They were something like: (0.0, 0.0),(0.0,0.5),(0.5,0.5),(0.0,0.5) which is obviously wrong but very hard to spot. Thank you for the help everyone, and I did end up using LibGDX; it's awesome.
> 1 votes

# Answer
Try to create new bodies so that they don't collide right away with others. Eg. its big problem if you create many bullets to same location at once.

Another note: Libgdx have java to native wrapper for box2d. Performance is so much better that maybe you could swap there.
> 0 votes

# Answer
I would suggest building a minimal test applet using the basics of the function above, nothing else. You may find the issue doesn't lie in this method directly, but rather in what it is tying into (the b2World or something else in your current setup).

I would also try the same under standard Java on the desktop rather than Android's Dalvik JVM, in the rather unlikely case that there is some discrepancy between them, since JBox2D was developed under/for the former.
> 0 votes

---
Tags: java, android, box2d, jbox2d
---


# Question
Title: Do rendered-to-textures need to be bound when being drawn to?
In OpenGL, if I'm rendering to a texture using a framebuffer, do I have to have that texture bound while I'm rendering to it? In code:

```
glBindTexture(...);
glTexImage2D(...);

glBindFramebuffer(...);
glFrameBufferTexture2D(...);

//START DRAWING HERE: does the texture I'm rendering to need to be bound here?

```

# Answer
> 5 votes
No.

When you bind textures to a `GL_FRAMEBUFFER` object (FBO), those textures get associated with it. Later, when you bind the FBO, the associated textures get bound as well.

An example:

```
// a framebuffer with a color texture and a depth texture

m_TexWidth = 1024;
m_TexHeight = 1024;

m_TextureTotal = 2;
m_Texture = new GLuint[m_TextureTotal];
glGenTextures(m_TextureTotal, m_Texture);

glGenFramebuffers(1, &m_Target);
glBindFramebuffer(GL_FRAMEBUFFER, m_Target);

// color

glBindTexture(GL_TEXTURE_2D, m_Texture[0]);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_TexWidth, m_TexHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_Texture[0], 0);

// depth

glBindTexture(GL_TEXTURE_2D, m_Texture[1]);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, m_TexWidth, m_TexHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_Texture[1], 0);

GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE)
{
    LOG_FATAL("Could not validate framebuffer");
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);

```

Now, if you want to use that framebuffer so you can render to it:

```
glBindFramebuffer(GL_FRAMEBUFFER, m_Target);

```

And back to the backbuffer:

```
glBindFramebuffer(GL_FRAMEBUFFER, 0);

```

**EDIT:** Earlier I claimed that textures are created per FBO. That is wrong, all textures are always created global in OpenGL. The difference is that these textures are now *associated* with the FBO.

# Answer
> 5 votes
No, the texture doesn't need to be bound.

---
Tags: opengl, textures, multiple-render-targets
---


# Question
Title: Determinism in multiplayer simulation with Box2D, and single computer
I wrote a small test car driving multiplayer game with Box2D using TCP server-client communcations.

I ran 1 instance of server.exe and 2 instance of client.exe on the same machine that I code and compile the executables. I type inputs (WASD for a simple car movement) into one of the 2 clients and I can get both clients to update the simulation.

There are 2 cars in the simulation. As long as the cars do not collide, I get the same identical output on both client.exe. I can run the car(s) around for as long as I could they still update the same. However, if I start to collide the cars, very quickly they go out of sync.

My tools: `Windows 7, C++, MSVS 2010, Box2D, freeGlut`.

My Psuedocode:

```
// client.exe
void timer(int value)
{
   tcpServer.send(my_inputs);
   foreach(i = player including myself) inputs[i] = tcpServer.receive();
   foreach(i = player including myself) players[i].process(inputs[i]);
   myb2World.step(33, 8, 6); // Box2D world step simulation
   foreach(i = player including myself) renderer.render(player[i]);

   glutTimerFunc(33, timer, 0);
}

// server.exe
void serviceloop
{
    while(all clients alive)
    {
       foreach(c = clients) tcpClients[c].receive(&inputs[c]);

       // send input of each client to all clients
       foreach(source = clients)
       {
          foreach(dest = clients)
          {
              tcpClients[dest].send(inputs[source]);
          }
       }
    }
}

```

I have read all over the internet and SE the following claims (paraphrased):

1. Box2D is deterministic as long as floating point architecture/implementation is the same.
2. (For any deterministic engine) Determinism is gauranteed if playback of recorded inputs is on the same machine with exe compiled using same compiler and machine.

Additionally my server.exe and client.exe gameloop is single thread with blocking socket calls and fixed time step.

**Question: Can anyone explain what I did wrong to get different Box2D output?**

# Answer
> 1 votes
~~Maybe glutTimerFunc(33, timer, 0); produce different results on different machines. Another thing is that your code. takes different amount of time to execute every once you run it (especially on different computers), so that may be the source of desynchronization.~~

Anyway the right way to do what you want to achieve is to run main physics simulation on server and send results to clients. You can avoid lag by making clients run their own simulation for results to use in time between getting results from the server.

# Answer
> -2 votes
The problem is that the two cars are out of sync due to the cars not syncing, I guess. I would do something like this:

```
//client
void tick() {
    step(a,b,c)
    for(body in myb2World) {
        if(body.userdata.owner == this) {
            tcpServer.send(body);
        }
    }
}

//server
void serviceloop
{
    while(all clients alive)
    {
       foreach(c = clients) tcpClients[c].receive(&inputs[c]);

       // send input of each client to all clients
       foreach(source = clients)
       {
          foreach(dest = clients)
          {
              tcpClients[dest].send(inputs[source]);
          }
       }
    }
}

```

and at the client the bodies not of that client are updated with the correct state.

---
Tags: box2d, multiplayer
---


# Question
Title: Drawing an outline around an arbitrary group of hexagons
Is there an algorithm for drawing an outline around around an arbitrary group of hexagons? The polygon outline drawn may be concave. See the images below, the green line is what I am trying to achieve. The hexagons are stored as vertices and drawn as polygons.

**Edit:**

I've uploaded images that should explain more. I want to favour convex hulls because it's conveys an area of control more quickly. Each hexagon is stored in a multidimensional array so they all have x and y coordinates, I can easily find adjacent hexagons and the opposite vertex, i.e. `adjacentHexagon = getAdjacentHexagon( someHexagon, NORTHWEST )` if there isn't a hexagon immediately adjacent it will continue to search in that direction until it finds one or hits the map edges.

# Answer
It seems to me that the easiest way to do this would be in two steps:

* Determine the smallest possible convex polygon surrounding all red nodes.
* Expand the convex polygon until it reaches the largest possible area without intersecting with white nodes.

Suppose we start with this situation:

Look at that glorious programmer art. I've chose red and green for the node colors because it makes things a bit more visible.

Think of it like a balloon. First we wrap it around the nodes as tight as possible, and then we'll blow it up as much as it will allow.

We want to create a conbex polygon around all the edges. So we start at an arbitrary node, let's say the one at the top-left.

* Starting at the top-left corner on the first node, we move around it in a clockwise fashion, towards the node in the top-center.
* When the distance between the points on the first node with the center of the second node becomes *greater* instead of *smaller*, we jump to the next node.
* The next node is never the node we came from, unless we've reached the last node. In that case, we traverse the node graph in reverse order.

This is a very basic algorithm, but it works. Here's what you should end up with:

Unfortunately, this polygon is too thin. Lines have collapsed onto each other. So let's expand the polygon with a new algorithm.

* Store the original convex polygon we made.
* For every line segment, try creating a new line segment to the next point in sequence if that's valid. For example, instead of a line segment `{Node1, point2}{Node1, point3}`, create a line segment `{Node1, point2}{Node2,point1}`
* Create a new convex polygon using this line segment.
* Check if a green node falls within this new convex polygon.
* If it doesn't, use this convex polygon from now on.
* Use a fitness function to determine whether the line segment is better or worse than the old line segment. An example could be: greatest distance between points.
* Stop iterating for this point when the fitness function returns a worse value.

What you should now end up with is this:

This algorithm isn't perfect and still needs work, but it should give you a start.

*P.S.: I spent over an hour on this problem, it was extremely interesting to solve!*
> 7 votes

---
Tags: rendering, algorithm, lua
---


# Question
Title: Will making players pay a virtual currency before entering a match discourage them from playing?
I'm making a multiplayer match-making game, and by my current design, people will need to pay a small fee before joining a match. At the end of the match, the team that won will get the money. That will be a virtual currency, but still, will it discourage people to enter matches? I introduced it to make the matches matter more, because there's always a fear that you will loose your investments.

I'm not talking about anything big here, but even a small amount might have a similar psychological effect as a bigger one.

# Answer
> 4 votes
This is technically a few questions in one (that do go together, and organically flow from one another), and I will break it apart to answer them. I will be paraphrasing:

> Is it reasonable to have a player pay a "fee" to perform actions in my game?

This is the whole concept behind micro-transactions (I will use real money here for something more tangible, but can be extended to imaginary currency/points/rep), and companies have made millions in terms of real money from it. there is still some discussion of what should be the limits of this, and sometimes the question of ethics comes up, but that aside. Yes you can require a fee for some actions in your game, but the following question needs to be observed.

> how do I balance a monetary system in my game?

This can be done in terms of pure numbers, or in terms of psychology. pretty much it all comes down to what is the value of the currency with respect to effort put into the game, or physical currency being spent (I do not condone/like the latter, so I will not discuss it to much). If there is a item (that boost your characters stats to an extraordinary amount) in the game that can only be obtained by purchasing it from a specific vendor for lets say 2,000,000 (currency), and it requires the player approximately 1 minutes of actively trying to earn 50 (currency) then it will take said player 40,000 minutes to acquire enough currency to buy said item. putting that in perspective that is 27.8 days (without breaks). if the player does the same math they will do some risk/reward analysis, and might come to the conclusion that that amount of time is not worth said item.

the big take away is figuring out some kind of calculation of this risk/reward analysis the easier it is to earn currency the higher prices can be, and visa-versa, but some numbers no matter how easy the currency is to obtain the player might just think are to high even if it is obtainable.

> if the player is going to be gambling in my game how should I approach setting the wager amounts?

this is actually the meat of your question (I know you didn't say gambling, but in essence you are "put down amountX for the chance to win amountY" is gambling)

this falls back in a circular fashion to the previous section where if the currency is easy to obtain then players will be more likely to wager more. though at the same time players will also see it like they would putting money down on a game of High card draw or Black-Jack. The higher the anti the higher the likely-hood of better players, and the statement "to rich for my blood" comes to mind.

for this reason I would advocate for a tiered wager system(tier1 costs x, tier2 cost Y, tier3 costs z... || x \< y \< z \< ...) this will allow for your in game economy to feel more open, and also give players a sense that "if I go to a low wager match then I will see weaker opponents, and a high tier match will have strong opponents" this also gives the player the chance to try the system out by possibly entering at the lowest tier to get a feel for how the system works. then the "better" players will gravitate toward the higher tiers, though your more casual players will gravitate toward your lower tiers, and the middle tiers will only ever be used for the high tier player to recoup losses, and get back into the high tiers, or the low tier players to seek a challenge, and improve their skills.

In conclusion:

you can't really set hard and fast numbers for what is to much, and what is just right its the same as balancing how much damage a weapon does with respect to how much damage a shield can take, or how many points eliminating a given enemy type is worth. Though when you throw in perception it does make things interesting (low to one person can be high to another).

It will come down to how easy the player perceives earning currency in your system is. if they see that after every "story event" they earn 1,000,000 currency, but for most other "events" they earn 20 currency then you can put higher prices on things, but if there are only say 10 of those "story events" in the game, and the player hasn't seen one in a while they might tighten up the purse strings a little.

In short the key word is balancing.

aside:

If your going to have a wager system on a section of the game have a defined rule set that you state up front (winning/losing, scoring, and objectives) even separately (or mandatory the first time they enter the section, but still reachable later) otherwise a new player might feel cheated if they lose the first time, and if it is at the beginning of each match an experienced player might get bored having to sit through it every time.

# Answer
> 4 votes
Assuming the players will attribute some value to in-game currency (for example, because they invested time in acquiring it), then **yes, I'm pretty sure even a small amount will discourage players from partaking**. The jump from free (*gratis*) to 1 credit is bigger than, say, the jump from 1 credit to 2 credits. In the first jump's case:

1. You're forcing your players to make a purchase decision.
2. The expected profit changes from guaranteed positive (getting to partake in a match) to a possible negative (the effect of which is exacerbated by people's tendency to be loss averse).

(As a side-note: I'm *guessing* this might make A/B testing problematic, as some (all) people will be used to playing for naught (some of the time), it will become hard to stomach when they find out have to pay to play all of the time when beta testing is over.)

**On the other hand**, people are essentially *gambling* on themselves. Gambling is *fun*. Gambling is *addictive*. Gambling made me lose one my *most prized marbles* when I was in lower school. :-(

I wish I could cite one of my favourite blogs on psychology and video games as an appropriate source for all of the above, but I could only find this piece: Sunk Costs, Pre-Orders, and Game Over. Which basically suggests that having players pay to play might not be so bad after all in the long run.

> Ever feel compelled to see a game through to its completion or spend some more time with it even though you’re not enjoying it but you feel like you have to justify spending money on it?

Some players won't spend the money, but the ones that will, will probably play more and consequently spend more.

# Answer
> 1 votes
It certainly can work. However, you also run the risk that people feel it is too high pressure, and any belief about imbalances will get significantly amplified once money (even virtual) is on the table.

In addition, you'd need to make sure that the virtual currency is an item of actual desire, instead of massive inflation like many in-game economies can suffer.

---
Tags: multiplayer, economy, psychology
---


# Question
Title: How do I draw shape distortion with a Texture2D in XNA?
Say I have a rectangular Texture2D object in XNA, and I draw it on the screen. How can I animate it so it slowly changes to a trapezoid shape, and then to a pentagon, etc.

I have no idea what this technique is called, so I couldn't find anything on Google.

# Answer
> 1 votes
Presumably you are using `SpriteBatch`. `SpriteBatch` is only capable of drawing rectangles. You need to go lower-level.

What you are looking for is **how to draw 2D *primitives***.

I'll leave it as an exercise to search the web for an appropriate tutorial. But you will probably find yourself at least using the `BasicEffect` class and the `GraphicsDevice.Draw*Primitives()` method.

In fact, you probably want to look up how to use the method `GraphicsDevice.DrawUserPrimitives<VertexPositionTexture>()`. That is an ideal place to start.

I'm going to assume that you are good enough at coding to figure out how to modify the contents of your vertex array each frame in order to animate it. If you need a starting point, look up "lerping" ("linear interpolation"). Particularly the `Vector3.Lerp` method. MSDN is your friend.

---
Tags: xna, animation
---


# Question
Title: Run FSX (Flight Simulator) on remote desktop
Obviously I cannot run FSX in a remote desktop session. When I try to start it appears the message: `Flight Simulator cannot run during a Remote Desktop session and will now quit`

Especially for development (coding on a second machine) a RDP session would be handy. Any workarounds for this?

# Answer
I am using VNC now in order to avoid the issue. While VNC 4.x was not suitable (too slow), VNC 5.x is acceptable for my particular use case.
> 1 votes

---
Tags: simulations, microsoft
---


# Question
Title: Making a surface transparent from blackness of texture
I am making a "halo" shader in unity using GLSL. And I've come to a roadblock.

What I need to do is take a texture, like the following, and make it transparent according to the darkness of it. And I don't want a cutout, because that cuts it off at a hard edge.

This line of code doesn't seem to work.

`gl_FragColor = texture2D( vec4( _MainTex.r, _MainTex.g, _MainTex.b, _MainTex.a), vec2(textureCoordinates));`

# Answer
Normally you store the transparency of a texture in the alpha channel, you can use an external editor like Paint.Net (free) or Photoshop to edit the alpha channels of a picture.

However since you're using shaders there is another trick you can do. A color is totally black if all it's color channels (R/G/B) are 0. It's gray when it's 128/128/128 and white when it's 255/255/255. If you want to determine the blackness you can take the average of the RGB channels, however a picture with bright red but no green or blue will still mean 'pretty black' and will still be 2/3rds transparent. However just try it for fun change your blend shader code to and see how it looks:

```
float blackness = (_Maintex.r + _Maintex.g + _Maintex.b) / 3.0;
gl_FragColor = texture2D( vec4( _MainTex.r, _MainTex.g, _MainTex.b, blackness), vec2(textureCoordinates));

```
> 1 votes

---
Tags: unity, textures, glsl, blending, transparency
---


title: Hidden Loading with UDK

text:
# Question
Title: Hidden Loading with UDK
I was wondering, how would I go about creating hidden loading scenes with UDK? For example, a character walks in to an elevator, the elevator fakes movement, whilst the previous floor is destroyed and the next floor is loaded on top.

I assume it's possible with UDK, since it's supposedly rather flexible, but I've never used UDK before (I decided to ask this question first to save me learning it all, finding out it isn't possible, then giving up).

So yeah, is hiding the loading process possible? And if so, how would I go about doing it?

# Answer
> 2 votes
There are a few relevant resources on the UDN about this subject (keywords "level streaming"), and even a convenient "hub" article that links to all of them:

http://udn.epicgames.com/Three/LevelStreamingHome.html

"The level streaming functionality in Unreal Engine 3 makes it possible to load and unload map files into memory as well as toggle their visibility all during play. This makes it possible to have worlds broken up into smaller chunks so that only the relevant parts of the world are taking up resources and being rendered at any point. If done properly, this allows for the creation of very large, seamless levels that can make the player feel as if they are playing within a world that dwarfs them in size."

---
Tags: udk, loading
---


title: Integration of LibRocket and Android

text:
# Question
Title: Integration of LibRocket and Android
I am using OpenGL ES 2.0 to create a 2D game for Android 2.2 and was planning on using LibRocket for the GUI. Does anyone have any links or knowledge they would share on how to integrate LibRocket with the android platform? I know that it is a c++ library that would need to go through the NDK, however I rather not change my OpenGL rendering code to the NDK unless I have to.

# Answer
> 5 votes
This might be tough and I'm not convinced that you will have acceptable performance on android devices at the end, but it seems that at least one game has been released on android using LibRocket.

You can write a few wrapper classes in c++ that allow LibRocket to use your own rendering functions. These classes can call back the proper java functions of your engine. You will also need, on the other hand, to forward input from java back to LibRocket using the provided method.

Here is a more straightforward description of the steps:

* Build LibRocket for Android platform using the NDK (this already might be difficult, but LibRocket shouldn't have much external dependency. Iirc, it only requires the STL).
* Write your interface between java and LibRocket as a second C++ lib. You must write three classes that inherit from `Rocket::Core::RenderInterface`, `Rocket::Core::SystemInterface`, and `Rocket::Core::FileInterface`. Each method of these classes should forward calls to an equivalent java method that can do the proper things in your engine. Here you can find some good help to do that.
* Write some static functions that will be called by java (check any sample from the NDK to see how to call c++ from java) to forward inputs. Check Injecting Input from the official LibRocket doc to see what you'll need.

Then simply write an initializer in c++ that will instantiate each of the three interface and bind them to LibRocket. Call it from Java at the beginning:

```
Rocket::Core::SetRenderInterface(new MyRenderInterface(Width, Height));
Rocket::Core::SetSystemInterface(new MySystemInterface());
Rocket::Core::SetFileInterface(new MyFileInterface());

```

Hope this will help.

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


title: Optimization and Saving/Loading

text:
# Question
Title: Optimization and Saving/Loading
I'm developing a 2D tile based game and I have a few questions regarding it.

First I would like to know if this is the correct way to structure my `Tile` class:

```
namespace TileGame.Engine {
    public enum TileType {
        Air,
        Stone
    }

    class Tile {
        TileType type;
        bool collidable;

        static Tile air = new Tile(TileType.Air);
        static Tile stone = new Tile(TileType.Stone);

        public Tile(TileType type) {
            this.type = type;

            collidable = true;
        }
    }
}

```

With this method I just say `world[y, x] = Tile.Stone` and this seems right to me but I'm not a very experienced coder and would like assistance.

Now the reason I doubt this so much is because I like everything to be as optimized as possible and there is a major flaw in this that I need help overcoming. It has to do with saving and loading... well more on loading actually. The way it's done relies on the principle of casting an enumeration into a byte which gives you the corresponding number where its declared in the enumeration. Each `TileType` is cast as a byte and written out to a file. So `TileType.Air` would appear as 0 and `TileType.Stone` would appear as 1 in the file (well in byte form obviously). Loading in the file is alot different though because I can't just loop through all the bytes in the file cast them as a `TileType` and assign it:

```
for(int x = 0; x < size.X; x++) {
     for(int y = 0; y < size.Y; y+) {
          world[y, x].Type = (TileType)byteReader.ReadByte();
     }
}

```

This just wont work presumably because I have to actually say `world[y, x] = Tile.Stone` as apposed to `world[y, x].Type = TileType.Stone`. In order to be able to say that I need a gigantic switch case statement (I only have 2 tiles but you could imagine what it would look like with hundreds):

```
Tile tile;
for(int x = 0; x < size.X; x++) {
     for(int y = 0; y < size.Y; y+) {
          switch(byteReader.ReadByte()){
               case 0:
                    tile = Tile.Air;
                    break;
               case 1:
                    tile = Tile.Stone;
                    break;
          }
          world[y, x] = tile;
     }
}

```

Now you can see how unoptimized this is and I don't know what to do. I would really just like to cast the byte as a `TileType` and use that but as said before I have to say `world[y, x] = Tile.whatever` and `TileType` can't be used this way.

So what should I do? I would imagine I need to restructure my `Tile` class to fit the requirements but I don't know how I would do that. Please help!

Thanks.

# Answer
It's been a while since I used C#, but I think you can structure your class something like this:

```
public static class Tile {
    public static enum TileType {
        Air,
        Stone
    }
    public static bool IsSolid(TileType tile) {
        switch(tile) {
            case Air:
                return false;
            case Stone:
                return true;
        }
    }
}

```

Then just fill your `world[y, x]` with the type `TileType` and fill it up like so:

```
for(int x = 0; x < size.X; x++) {
     for(int y = 0; y < size.Y; y+) {
          world[y, x] = (Tile.TileType)byteReader.ReadByte();
     }
}

```

Then when you want to test collision you can just do this:

```
if(Tile.IsSolid(world[y,x])) {
   //collide with tile
}

```

Finally I don't think you should worry so much about optimizing right now. You can optimize forever. You'll never finish your game like that! You can worry about making it neat and clean, but not necessarily optimal. If something is really bugging you, just add a little comment for later defining how important you think the optimization is:

```
//TODO optimize this! Level 3

```

Then when you find things going slow, check your to-dos, tackling the highest level ones first.
> 5 votes

# Answer
There is no right way to optimize loading code other than simply compressing your files. We've benchmarked and shown that loading uncompressed TGA files (textures that can be directly loaded into the GPU with no CPU transformation necessary) is waaaay slower than loading compressed PNGs (which need several CPU-side passes to decompress before loading into the GPU).

The simple fact is that your CPU is several orders of magnitude faster than your storage device (even SSDs), and any loading/saving code is going to be I/O bound, not CPU bound.

Instead of worrying about byte conversions, worry about making your I/O code streamable. Meaning, process data as it is read in, rather than needing to wait for it all to be loaded and then processing it. The processing time will then end up being completely hidden by the disk I/O.

I'm not a C# expert so I don't know the proper APIs off the top of my head. I do know that the APIs are available, and Googling ".net streaming io" should find them for you.
> 0 votes

---
Tags: 2d, tiles, tilemap, loading, savegame
---


# Question
Title: Is it possible to extract textures or sprites from compiled game files?
For instance, every map in Portal has what appear to be sprites over a texture indicating the obstacles you'll face (see screenshot). Are these resources compiled into the source as byte code, or is it possible to extract them from installation files? Obviously I understand copyright implications, and I am only interested in using it for a recreational project. Instead of recreating them, I wonder if they can be extracted.

# Answer
You can save yourself a lot of trouble and just download them here.

But as for your question. It totally depends on the game, but usually they are not compiled into the source as byte code. Often times they are available in the resource files found in the same directory as the game install. But really there's no definitive answer on this. Theoretically the texture files will always be extract-able, it just depends on how much work you want to devote to it.
> 9 votes

---
Tags: game-design, graphics, graphics-programming
---


# Question
Title: How can I do Mouse Selection In OpenGL 3.0?
Hello I'm pretty good programmer I've made my own 2D games in SDL and made a gui in 3D using Old OpenGL and Modern OpenGL but.. I'm having problems with trying to click 3D models with opengl I have no idea what to do too be honest.

Do I read the area that I've clicked?

or what do I do?

100% shore this has been asked before but I just don't know what to do...??

using :

OpenGL 3.0

WIN32 API

C++

# Answer
> 1 votes
I know two ways how to do this:

1) Use frame buffer, where you render all objects, each with different color (no lighing, no texturing, ...). Then render normal scene.

When you click with your mouse, you read 2D coordinates, look in frame buffer and find color of pixel, where you have clicked. Then you will find object according to this color.

This method is called pixel picking.

2) Render your scene, read clicked coordinates. Now you have to transfer 2D point back to 3D - create ray from camera to clicked point. Then do ray tracing and find first object in path (ray object collision).

*// EDIT:*

I have found this article, it could be useful.

Or you can create 3D points - your screen coordinates (x, y) - devided by screen size (you have to get coords in interval \<-1,1\>), and z coordinate will be -1 (starting point) and 1 (ending point). These are NDC (normalized device coordinates). Then multiply them by inverse projection matrix and inverse modelview matrix. Results should be starting and ending points of ray. You can find something here \- it will help you understand those transformations.

Maybe you can use gluUnProject for this purpose...

# Answer
> 1 votes
Sorry, selection API is not in OpenGL 3.0, but here's a question with a good answer on doing ray (un-)projection for picking: How can I convert a mouse click to a ray?

---
Tags: mouse, selection
---


title: Exporting UV coords from Blender

text:
# Question
Title: Exporting UV coords from Blender
So I have searched on google and various other websites but I've not found an answer. The only ones I did find did not work.

So my question is how do I get UV coords from blender (2.63)?

Currently I'm writing my own custom file exporter, and so far have managed to export vertices and their normals. Is there a way to export the UV coords?

N.B. I'm currently try to figure it out using a simple cube that is unwrapped and has a texture applied to it.

# Answer
> 1 votes
Yep, you can export those. This is a bit of code I was using when I wrote a custom exporter:

```
 if len(mesh.uv_textures)>0:
    uvLayer=mesh.uv_textures.active
    uvLayer=uvLayer.data
    uv=uvLayer[faceIdx]
    uv=uv.uv1, uv.uv2, uv.uv3, uv.uv4
    uvCoord=uv[vertIndex][0], 1.0-uv[vertIndex][1]
    uvCoord=roundVec2(uvCoord)
else:
    uvCoord=v.uvco[0], 1.0-v.uvco[1]
    uvCoord=roundVec2(uvCoord)

```

Where `vertIndex` is enumerating over all the vertices in a face. And `faceIdx` is enumerating over all the faces in a mesh.

Then when writing:

```
file.write('u %.6f %.6f \n' %uvCoord) # uv

```

I should mention that I eventually abandoned the whole writing my own exporter. It's far easier to just write an importer that imports from a common export standard. This also has the additional benefit of your exporter being updated by someone else if Blender ever changes things.

Additionally, if you still want to write your own. Reading how it's done in the "official" exporters is a pretty big help.

For a larger picture of how this code is used:

```
class processVerts():
    def __init__(self, mesh, vert, face, faceIdx, vertIdx, file):
        ...
        def roundVec3(v):
            return round(v[0], 6), round(v[1], 6), round(v[2], 6)

        v=roundVec3(tuple(vert.co))
        ...
        if len(mesh.uv_textures)>0:
            uvLayer=mesh.uv_textures.active
            uvLayer=uvLayer.data
            uv=uvLayer[faceIdx]
            uv=uv.uv1, uv.uv2, uv.uv3, uv.uv4
            uvCoord=uv[vertIdx][0], 1.0-uv[vertIdx][1]
            uvCoord=roundVec2(uvCoord)
        else:
            uvCoord=v.uvco[0], 1.0-v.uvco[1]
            uvCoord=roundVec2(uvCoord)
        ...
        file.write('u %.6f %.6f \n' %uvCoord) # uv

class processFace():
    def __init__(self, mesh, face, faceIdx, file):
        ...
        for vertIdx, vert in enumerate(face.vertices):
                processVerts(mesh, meshVerts[vert], face, faceIdx, vertIdx, file)

class processMesh():
    def __init__(self, mesh, file):
        for faceIdx, face in enumerate(mesh.faces):
            processFace(mesh, face, faceIdx, file)

```

---
Tags: blender, python, uv-mapping
---


# Question
Title: Interpolation gives the appearance of collisions
I'm implementing a simple 2D platformer with a constant speed update of the game logic, but with the rendering done as fast as the machine can handle. I interpolate positions between actual game updates by just using the position and velocity of objects at the last update. This makes things look really smooth in general, but when something hits a wall/floor, it appears to go through the wall for a moment before being positioned correctly. This is because the interpolator is not taking walls into account, so it guesses the position into walls until the actual game update fixes it. Are there any particularly elegant solutions for this?

Simply increasing the update rate seems like a band-aid solution, and I'm trying to avoid increasing the system reqs. I could also check for collisions in the actual interpolator, but that seems like heavy overhead, and then I'm no longer dividing the drawing and the game updating.

# Answer
> 1 votes
Don't interpolate with velocity. Calculate the next actual position ( with full physics ) and simply interpolate between the last and current positions. Same for rotation and any other physical properties that graphics cares about.

What might happen now is that an object bounces before hitting the floor, but if you keep your objects at reasonable speeds you probably won't notice is much.

Also try to run physics around as often as graphics. A lot of physics engines run at over 60hz ( and there's basically zero reasons to run graphics faster than the monitor's display rates aside from benchmarking ).

# Answer
> 1 votes
So you're *extrapolating*? This problem reminds me of netcode in 3D shooters: The client has to "predict" its own collisions with walls, to avoid being placed back later by the server.

If you're dead set on not coupling game world updates to render updates, the only option would be to "predict" collisions in your view/renderer logic, as you kind of suggest in your post. You'd still have the separation of the actual game state and the game "view", though.

If you regard your design as client-server, it's actually not bad: The game update loop is the server, and the client is the view/renderer, which predicts movement, including collision. However, it does introduce a set of potential problems usually present in realtime client-server game architectures...

## Some potential issues

Depending on your game, you'll also have to predict things like enemy/projectile collision and f.e. as a result, have a rocket explode, do damage, and kill an enemy before all this *actually* happens in the next game update.

Second, since you'll probably want the game to respond immediately to player input (otherwise it feels weird), you might want the player character to start a jump somewhere inbetween 2 game updates. The same goes for firing projectiles. Are you going to initiate these actions on the server on the next update? Or will you get the projectile's position from the view, breaking the separation of game updates and view?

What if an early, predicted projectile hits an enemy and predicts its death, but is avoided in the next game update because the actual projectile is fired later?

One option is to wait for 2 game updates and interpolate instead of extrapolating. Drawbacks are the artificial delay in view, and the problem of having to make player movement instantaneous, predicting it, resulting in displayed player actions being in the future, relative to the rest of the world, which introduces its own set of problems...

## Final thoughts

As you can see, de-coupling game updates from rendering introduces potential problems. Depending on the nature of your game, these may or may not be dealbreakers. Post an update sometime, I'm curious how your approach turns out, whatever it may be.

# Answer
> 0 votes
Your problem stems from that you are interpolating between the current frame, and the next (future) frame. As long as your game logic is updating at a reasonable rate you could simply interpolate between the last frame and the current frame, ie delaying the display of the graphics with 1 game tick. This way it can interpolate between two known states instead of between a known and an unknown state.

The obvious downside is that game input is delayed, but if your game logic updates at 60fps you would only delay it with 16ms. If you also have a slight acceleration to the movements of the characters you can minimize the impact of this delay.

It seems that you are spending a lot of effort on enabling the game to look smooth while using low update frequencies though, perhaps making the game logic able to update at variable rates would be easier.

---
Tags: collision-detection, interpolation
---


# Question
Title: 3DS Max exporting too many vertexes for model
I have a sample model of a cube and a buddha downloaded from internet in 3ds format which I can load correctly into my program and view them without problem, but wanted to try and create my own model.

I created a simple box mesh in 3ds max, and exported it as .3ds (Converted to mesh -\> export as .3ds)
When inspecting the .3ds file with a hex viewer, I was expecting to see 8 vertexes and 12 faces declared (as the model I downloaded from internet). But what i found was that it listed 26 vertexes, and 12 faces! And when I try to load that file with my .3ds viewer, my parser isn't detecting the face block (0x4120), which is strange because it worked for other objects downloaded from internet.

Do I have to set any special property in order to export a 3ds file with minimum vertexes and a vertex-index list?

# Answer
If your cube has hard normals, then each of the 8 vertices will need to be repeated 3 times because it occurs with 3 different normals, one for each cube face that shares it. That's 24 verts. You said 26, and I don't know where the other two come from, but if there are UVs on the model as well, perhaps some UV seam is causing that.

To export with a minimum number of vertices, you probably have to delete all UVs and smooth all normals, or some such. I don't know exactly how to do that in 3DS Max, but it should be possible.
> 0 votes

---
Tags: opengl, graphics, models, 3dsmax
---


# Question
Title: Changing the culling mode in the HLSL effect
I'm writing a cel-shading effect in HLSL and Direct3D 11, and I need to be able to flip the culling mode on the outline pass of the effect. I know you do this in XNA by setting **CullMode** to **CW** or **CCW** inside the pass definition, but is that how you do it in D3D11/SlimDX?

# Answer
You can do that by creating rasterizer state and setting it active in context. See D3D11\_RASTERIZER\_DESC and SlimDX.Direct3D11.RasterizerStateDescription.IsFrontCounterclockwise.

And if you use Effect11 framework, then you can do that directly in fx file like this:

```
// define your rasterizer state
RasterizerState MyCull {
    FrontCounterClockwise = TRUE; // or FALSE
};

// in some effect pass use MyCull state for Rasterizer State
SetRasterizerState( MyCull );

```
> 0 votes

---
Tags: hlsl, directx11, slimdx, culling, effect
---


# Question
Title: What is the benefit of triple buffering?
I read everything written in a previous question. From what I understand in double buffering the program must wait until the finished drawing is copied or swapped before starting the next drawing. In triple buffering the program has two back buffers and can immediately start drawing in the one that is not involved in such copying.

But with triple buffering if you're in a situation where you can take advantage of the third buffer doesn't that suggest that you are drawing frames faster than the monitor can refresh. So then you don't actually get a higher frame rate. So what is the benefit of triple buffering then?

# Answer
Both Double and Triple buffering solve the problem of black redraws on the screen. Triple buffering, however, solves a problem of concurrency when the current draw buffer is being memcpy-ed to the screen, and your game scene can start drawing already.

This article is the best way to explain the benefits of triple buffering ... http://remis-thoughts.blogspot.com/2012/01/triple-buffering-as-concurrency.html
> 6 votes

---
Tags: opengl, performance, double-buffering
---


title: "Untangle"-Game AI

text:
# Question
Title: "Untangle"-Game AI
I am trying to program an AI for such untangle games like Untangle game.

I tried the following possibilities:

1) Just set one node after the other to a random place. If every node was moved once, start over with the first node in the list.

2) First move all nodes which have the most wrong connections. If all were moved once, move the nodes which have the fewest (but not 0) wrong connections. If all were moved but there are some left, move all which are left. If none are left start over.

3) Just 2) bust starting with the nodes with the fewest connections.

4)/5) As 2) and 3) but when I didn't move nodes which have only correct connections.

All of these approaches are too slow and inefficient.

Can anyone suggest a solution which does not depend so much on fortune?

# Answer
I believe what you are looking for is a planar graph embedding algorithm.

If you want to solve the problem "properly" (in linear time), this thesis linked in this math.SE question seems to be what you are looking for.

Here is another paper on the subject A Linear Time Algorithm for Embedding Graphs in an Arbitrary Surface. Be aware that they are quite math heavy.

**Edit**: I found this implementation which should help: http://code.google.com/p/planarity/, particulary the planar graph drawing algorithm.
> 2 votes

---
Tags: game-design, ai, puzzle
---


title: Using model tools as map editor

text:
# Question
Title: Using model tools as map editor
I want to make a game which would require a 3D map editor. Of course, I would like to avoid creating such an editor. My idea is now to use modeling tools (3DS Max, Maya, Blender) to create the map, and to give game specific objects specified names. This way I'd just need to write an COLLADA -\> native map format converter. But I'm not sure if this is possible the way I imagine it, that's why I'd like to hear your thoughts on the matter.

* Are modeling tools suitable to create big open world maps?
* Can this "naming convention"-idea for game specific objects work?
* Are the modeling tools able to export a scene in chunks / in a way that occlusion culling and collision detection can be properly done? If not: Is there a way to build a suitable data structure from the exported data?

# Answer
> 1 votes
In principle I see no reason you can't do this. You might have to wirte script utilities for max(maya, blender), and possibly your own exporter though.

Max has mechanisms for referencing other scenes, and I assume blender and maya have something similar, too. I don't know if these are exactly suited to working on the world in chunks.

For a simple grid-like chunk system though it shouldn't be too hard to write a script that allows you to save and load chunks from different scene files on the fly to edit them.

As for the naming system, that should certainly work as well, you can do pretty much whatever you want when you write your collada or custom file format parser. You could for example prefix occlusion portals with \[portal\], other things you might need could be \[collider\] or \[physics proxy\] etc...

BSP trees are relatively popular for collision detection (mostly for static geometry since compiling them can be expensive), you could compile one from the collision meshes referenced in your map file at any point you like. I don't know of any built in functionality to export one in max, though.

Extending max, blender or maya to a map editor could be a huge or small task, depending on the functionality you need.

---
Tags: tools, map-editor
---


# Question
Title: Cocos2d rotating sprite while moving with CCBezierBy
I've done my moving actions which consists of sequences of CCBezierBy. However I would like the sprite to rotate by following the direction of the movement (like an airplane). How sould I do this with cocos2d?

I've done the following to test this out.

```
    CCSprite *green = [CCSprite spriteWithFile:@"enemy_green.png"];
    [green setPosition:ccp(50, 160)];
    [self addChild:green];

    ccBezierConfig bezier;
    bezier.controlPoint_1 = ccp(100, 200);
    bezier.controlPoint_2 = ccp(400, 200);
    bezier.endPosition = ccp(300,160);

    [green runAction:[CCAutoBezier actionWithDuration:4.0 bezier:bezier]];

```

In my subclass:

```
@interface CCAutoBezier : CCBezierBy

@end

@implementation CCAutoBezier

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }

    return self;
}

-(void) update:(ccTime) t
{
    CGPoint oldpos=[self.target position];
    [super update:t];
    CGPoint newpos=[self.target position];

    float angle = atan2(newpos.y - oldpos.y, newpos.x - oldpos.x);
    [self.target setRotation: angle];
}

@end

```

However it rotating, but not following the path...

# Answer
I'm not sure if there is a class dedicated to this purpose or not but you can simply implement your own. just inherit your class from CCBezierBy class and then in update function after applying what CCBezierBy by does change direction of airplane based on movement generated bu CCBezierBy.

there might be some errors in this code(i'll be glad if you fix them), but this is showing how easy you can implement it!

```
-(void) update: (ccTime) t
{
    CGPoint oldpos=[target position];
    [super update:t];
    CCPoint newpos=[target position];

    float angle = atan2(-newpos.y + oldpos.y, newpos.x - oldpos.x) * 180 / M_PI;
    [target setRotation: angle];
}

```

I'm not sure if this will help you but here is my code (though in c++ using cocos2d-x)

```
class mybezier : public CCBezierBy
{
public:
    static CCBezierBy* actionWithDuration(float t,ccBezierConfig k)
    {
        mybezier* b = new mybezier;
        b->CCBezierBy::initWithDuration(t,k);
        return b;
    }

    virtual void update(ccTime t)
    {
        CCPoint oldpos = getTarget()->getPosition();
        CCBezierBy::update(t);
        CCPoint newpos = getTarget()->getPosition();
        float angle = atan2(-newpos.y + oldpos.y, newpos.x - oldpos.x) * 180 / M_PI;
        getTarget()->setRotation(angle);//*  180);
    }
};

```

and I'm calling this class using this lines:

```
ccBezierConfig x;
x.controlPoint_1 = CCPoint(CCDirector::sharedDirector()->getWinSize().width / 2,0);
x.controlPoint_2 = CCPoint(0, CCDirector::sharedDirector()->getWinSize().height / 2);
x.endPosition = CCPoint(0,0);
pSprite->runAction(CCRepeatForever::actionWithAction(mybezier::actionWithDuration(10,x)));

```
> 2 votes

# Answer
This works great, here it is in Objective-C for Cocos2d on iOS. Just use CCTBezierRotateTo instead of CCBezierTo. Same thing should work for CCBezierBy. My sprites rotate to follow the path given by bezierForward.

I call it like this:

```
id bezierForward = [CCTBezierRotateTo actionWithDuration:10.0 bezier:bezier];
[missileSprite runAction:bezierForward];

```

Here is the .h:

```
#import "CCActionInterval.h"
@interface CCTBezierRotateTo : CCBezierTo
@end

```

Here is the class:

```
@implementation CCTBezierRotateTo

-(CCBezierBy*) actionWithDuration :(float)t :(ccBezierConfig) k {
    CCTBezierRotateTo* r = [CCTBezierRotateTo actionWithDuration:t];
    return r;
}

-(void) update:(ccTime)time {
    CGPoint oldpos = [[self target] position];
    [super update:time];
    CGPoint newpos = [[self target] position];
    float angle = atan2(-newpos.y + oldpos.y, newpos.x - oldpos.x) * 180 / M_PI;
    angle += 90; // my sprites start pointing up
    [[self target] setRotation:angle];
    NSLog(@"oldpos %f,%f newpos %f,%f angle %f", oldpos.x, oldpos.y, newpos.x, newpos.y,  angle);
}

```
> 2 votes

---
Tags: sprites, cocos2d, rotation
---


title: Making a clone of Starcraft legal?

text:
# Question
Title: Making a clone of Starcraft legal?
My question is similar to a previous question. Consider the following clone of Starcraft: Change the artwork, sound, music, change the names of units. However, leave the unit hit points unchanged, unit damage unchanged, unit movement speed unchanged, change ability names but not ability effects.

Is that considered illegal? In other words, is copying the unit hit points, damage, etc. considered illegal even if everything else is changed?

# Answer
> 2 votes
You can't copyright or trademark numbers. Every RPG I've ever played has an attack stat and a defense stat, many of which are quite similar. No one sues them. As long as you don't copy their artwork there won't be any problem.

---
Tags: legal
---


title: Calculating AABB's Origin

text:
# Question
Title: Calculating AABB's Origin
I can't work out how to find the position in which my AABB should be corresponding to my object.

# Answer
> 1 votes
I assume you're using that code in the picture and it's giving you the incorrect box shown on the right? The algorithm looks sound enough to find the minimum and maximum `X` and `Y` values in your list so are you sure your vertex list is properly representing the triangle you're trying to determine a box for?

It looks like your bounding box is the right size, just shifted in the `X` direction. Are you sure that the vertex locations you're sending are accurate for that triangle? Have you tried shifting it in different directions to make sure the disparity is consistent? What have you tried?

Additionally, I notice you aren't setting your `AABB` rectangle to an initial value, that's going to potentially cause a problem when setting it for some objects. Whether that's the problem here or not, I'm not sure. I'd recommend setting `AABB` initially to represent the first vertex you send in--so you know it starts with valid data, then iterating through the rest of the list: `AABB = verts[0]` (or, if Flash is different, however you'd do it there).

# Answer
> 0 votes
You could create the AABB using two points, from the bottom left of the triangle as a minimum point, and the maximum point being the top right, i.e. x is the point on the right, and y is the top left point.

---
Tags: mathematics, aabb
---


title: How To Approach 360 Degree Snake

text:
# Question
Title: How To Approach 360 Degree Snake
I've recently gotten into XNA and must say I love it. As sort of a hello world game I decided to create the classic game "Snake". The 90 degree version was very simple and easy to implement. But as I try to make a version of it that allows 360 degree rotation using left and right arrows, I've come into sort of a problem.

What i'm doing now stems from the 90 degree version: Iterating through each snake body part beginning at the tail, and ending right before the head. This works great when moving every 100 milliseconds. The problem with this is that it makes for a choppy style of gameplay as technically the game progresses at only 6 fps rather than it's potential 60.

I would like to move the snake *every* game loop. But unfortunately because the snake moves at the rate of it's head's size it goes way too fast. This would mean that the head would need to move at a much smaller increment such as (2, 2) in it's direction rather than what I have now (32, 32). Because I've been working on this game off and on for a couple of weeks while managing school I think that I've been thinking *too* hard on how to accomplish this. It's probably a simple solution, i'm just not catching it.

Here's some pseudo code for what I've tried based off of what makes sense to me. I can't really think of another way to do it.

```
for(int i = SnakeLength - 1; i > 0; i--){
    current = SnakePart[i], next = SnakePart[i - 1];

    current.x = next.x - (current.width * cos(next.angle));
    current.y = next.y - (current.height * sin(next.angle));

    current.angle = next.angle;
}

SnakeHead.x += cos(SnakeAngle) * SnakeSpeed;
SnakeHead.y += sin(SnakeAngle) * SnakeSpeed;

```

This produces something like this: Code in Action. As you can see each part always stays behind the head and doesn't make a "Trail" effect.

A perfect example of what i'm going for can be found here: Data Worm. Not the viewport rotation but the trailing effect of the triangles.

Thanks for any help!

# Answer
> 5 votes
With that algorithm, you're making each segment face the same angle as the one in front of it. That's why they all end up getting directly behind the head, they're ultimately all facing the same angle. As you can see in the Data Worm game you linked, each segment just faces *toward the segment in front of it*. Determine the angle from the current segment to its `next` and have the segment point that way instead of setting it to `next.angle`.

For that implementation, you may want to actually iterate from front to back instead. The behavior will be different based on the direction you pass through the list. Try them both and see which works better.

I've used a similar idea for a project prototype in the past (Unity WebPlayer link). I used similar (albeit 3D) code to get each segment to turn toward the segment in front of it and stay back a set distance. Worked like a charm.

---
Tags: xna-4.0, game-mechanics, rotation
---


# Question
Title: Straightforward guidelines for converting OpenGL to OpenGL ES?
Is there a straightforward list of finite steps that I need to follow to convert an OpenGL program into an OpenGL ES that's used on the iPhone and iPad? I'd be using GLKit.

I've seen some similar API functions but I gather that triangles have to be presented differently.

# Answer
Since you're not saying which version of GL you're using, I'm going to assume it's reasonably modern.

There's not that much difference, no. Some of the deprecated functions are gone entirely, and some of the newer desktop GL functions are not yet in GL ES, but otherwise they're the same. "Presenting triangles" will only be very different if you're still using the ancient OpenGL 1.x immediate mode API. If you're using VBOs already, the code will translate almost directly to GL ES. You'll also need to use shaders, as GL ES 2.x does not support any fixed function code, but again the APIs and shader language features are very comparable, and may even port over with no changes at all.

There are some performance things to care about, but there is no straight forward guide to those. You need to profile, benchmark, and study your target hardware. In general, though, some of the advanced rendering techniques that are good on desktops just don't run well on mobile devices.
> 3 votes

---
Tags: opengl, opengl-es, ios, opengl-es2, ipad
---


# Question
Title: Is there a repository of game logic algorithms?
I'm writing my first 2D game, and I'm writing some tracking logic for the computer enemies. Basic follow-the-player tracking was easy, but ineffectual. Too easy to escape. So I'm trying to implement some more sophisticated flanking and other tactics, and (as expected) it's pretty tricky. This is a topic I know nothing about.

I'm going to keep trying, but it'd be awesome to have some examples or tips to work off of.

Is there any place that has a decent set of pseudocode AI algorithms, or tips or advice on the subject, e.g. for 2D tracking?

# Answer
A great book is Artificial Intelligence for Games, Second Edition, and you can find the code repository here.
> 4 votes

# Answer
What kind of game logic are you looking for? Pathfinding? FSM? Genre-specific logic (RTS, FPS)?

Take a look at Alive.
> 1 votes

# Answer
http://aiwisdom.com is run by Steve Rabin, an accomplished game logic engineer (editor for the AI Game Wisdom series of books, and coordinator for the AI dev panels at GDC). Unfortunately it mostly just contains summaries of the articles in the books themselves, which can be a bit hard to get a hold of these days. That said, if you can get a copy of the books, they are quite excellent.

http://aigamedev.com is also a good resource.

I also agree with integeruser's answer. The book he mentions is quite good for someone just starting out.
> 0 votes

---
Tags: algorithm, ai
---