# Question
Title: Sweep and prune vs quad tree when all objects are dynamic (moving)
As I understand it there are 3 popular strategies for spatial partitioning: sweep and prune, quad/oct tree and uniform grid. Uniform grid is problematic for me because I have not set an upper limit on how big each entity can become so every time an entity move I may need to update multiple grids.

So right now I am exploring sweep and prune vs trees on which is better for my use case. I know for sure that a majority of my objects contained in the structure will be moving every frame. I need to support 2 tests: 1) whether any objects overlap/collide with each other and 2) whether any object will overlap/collide with a ray that can traverse through the entire playing region.

I know for question like these the answer is usually impossible to know beforehand without testing etc. But certainly this is a very common problem and many of you have experience with. If so, can you share the strength/weakness of each method with respect to my use case and which method is more likely to produce better results? And for the record I am trying to animate 1k+ dynamic entities in 3D space so brute forcing is unlikely to be enough. I also have another structure for static objects so all contained entities are dynamic.

# Answer
I recently went through this exercise and evaluated both on a couple of platforms.

I found that my engine had many moving objects clustering on top of each other. As they moved around the Sweep and Prune (SAP) implementation caused too much sorting and overlap callbacks every frame. It was crippling my platform, which is not too powerful. I did all the tricks - use quantized floats stored as integers to allow for integer compares, stab entries, etc.

My research covered reading up on how commercial engines were doing it as well as discussions on a number of message boards.

In the end I chose a dynamic bounding tree based on the implementation in Box2D. You can find a great implementation here: https://code.google.com/p/box2d/source/browse/trunk/Box2D/Box2D/Collision/b2DynamicTree.h

A number of people have used this version and converted it to 3D with much success.

The key is that the objects, when put the tree, have their AABB inflated in the direction of their velocity by some platform and use-case amount. When the object moves, if it doesn't travel outside of the AABB, the tree is not modified. This effectively amortizes the cost of tree updates over multiple frames.

This structure is normally paired with a OverlappingPairCache - a cache that stores A/B pairs of objects. Every frame that cache is walked and collisions performed between them.

I would encourage you to start with the bounding tree. If I had I probably would never have looked back. Instead I burned a lot of time tinkering with my SAP before giving up and looking elsewhere. This seems consistent with what people are seeing in Box2D, Bullet, PhysX and maybe even new versions of Havok.

If you want more details on implementation details, let me know. The thread on the Bullet Physics Research forum I found most interesting is here:

http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?f=4&t=9800

And Randy Gaul's write is really good, too:

http://www.randygaul.net/2013/08/06/dynamic-aabb-tree/
> 4 votes

---
Tags: collision-detection, algorithm
---


# Question
Title: Normal Mapped Models Render with render target background color acting as transparency and lighting Problem
SOLVED. See my comment below.

Originally I noticed some sort of transparency when rendering in Direct3D 11. I noticed it was worse once I changed my background color to something other than black. I also created a simple exporter for Maya to output the model data. The format is exactly as in the Rastertek's model format. Most of my rendering code is more or less based off of the Rastertek website. I thought it was my exporter, but it renders just fine in the Rastertek executable. Here's a picutre of what I am talking about.

https://www.dropbox.com/s/2j5qukam32h2tgc/Direct3D%20Model.png

The model is a simple cylinder with a cone sticking into it from the top.
I thought it had something do with the normals, or a culling problem, but I am unsure.

Also, I am still new to some of this. I will post code if needed.

EDIT: Color/Lighting transparency is working now.

Here is my Depth initialization code:

```
    ID3D11Texture2D* backBufferPtr;

    // Get the pointer to the back buffer.
    HRESULT result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
    if(FAILED(result))
    {
        return false;
    }

    // Create the render target view with the back buffer pointer.
    result = m_device->CreateRenderTargetView(backBufferPtr, NULL, &m_renderTargetView);
    if(FAILED(result))
    {
        return false;
    }

    // Release pointer to the back buffer as we no longer need it.
    backBufferPtr->Release();
    backBufferPtr = 0;

    D3D11_TEXTURE2D_DESC depthBufferDesc;
    // Initialize the description of the depth buffer.
    ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));

    // Set up the description of the depth buffer.
    depthBufferDesc.Width = width;
    depthBufferDesc.Height = height;
    depthBufferDesc.MipLevels = 1;
    depthBufferDesc.ArraySize = 1;
    depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    depthBufferDesc.SampleDesc.Count = 1;
    depthBufferDesc.SampleDesc.Quality = 0;
    depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
    depthBufferDesc.CPUAccessFlags = 0;
    depthBufferDesc.MiscFlags = 0;

    // Create the texture for the depth buffer using the filled out description.
    result = m_device->CreateTexture2D(&depthBufferDesc, NULL, &m_depthStencilBuffer);
    if(FAILED(result))
    {
        return false;
    }

    D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
    // Initialize the description of the stencil state.
    ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));

    // Set up the description of the stencil state.
    depthStencilDesc.DepthEnable = true;
    depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
    depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

    depthStencilDesc.StencilEnable = true;
    depthStencilDesc.StencilReadMask = 0xFF;
    depthStencilDesc.StencilWriteMask = 0xFF;

    // Stencil operations if pixel is front-facing.
    depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
    depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

    // Stencil operations if pixel is back-facing.
    depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
    depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

    // Create the depth stencil state.
    result = m_device->CreateDepthStencilState(&depthStencilDesc, &m_depthStencilState);
    if(FAILED(result))
    {
        return false;
    }

    // Set the depth stencil state.
    m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);

    D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
    // Initailze the depth stencil view.
    ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));

    // Set up the depth stencil view description.
    depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
    depthStencilViewDesc.Texture2D.MipSlice = 0;

    // Create the depth stencil view.
    result = m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView);
    if(FAILED(result))
    {
        return false;
    }

    // Bind the render target view and depth stencil buffer to the output render pipeline.
    m_deviceContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView);

    D3D11_RASTERIZER_DESC rasterDesc;
    // Setup the raster description which will determine how and what polygons will be drawn.
    rasterDesc.AntialiasedLineEnable = false;
    rasterDesc.CullMode = D3D11_CULL_BACK;
    rasterDesc.DepthBias = 0;
    rasterDesc.DepthBiasClamp = 0.0f;
    rasterDesc.DepthClipEnable = true;
    rasterDesc.FillMode = D3D11_FILL_SOLID;
    rasterDesc.FrontCounterClockwise = false;
    rasterDesc.MultisampleEnable = false;
    rasterDesc.ScissorEnable = false;
    rasterDesc.SlopeScaledDepthBias = 0.0f;

    // Create the rasterizer state from the description we just filled out.
    result = m_device->CreateRasterizerState(&rasterDesc, &m_rasterState);
    if(FAILED(result))
    {
        return false;
    }

    // Now set the rasterizer state.
    m_deviceContext->RSSetState(m_rasterState);

    // Setup the viewport for rendering.
    m_viewport.Width = (float)width;
    m_viewport.Height = (float)height;
    m_viewport.MinDepth = 0.0f;
    m_viewport.MaxDepth = 1.0f;
    m_viewport.TopLeftX = 0.0f;
    m_viewport.TopLeftY = 0.0f;

    // Create the viewport.
    m_deviceContext->RSSetViewports(1, &m_viewport);

    // Setup the projection matrix.
    float fieldOfView = (float)XM_PI / 4.0f;
    float screenAspect = (float)width / (float)height;

    // Create the projection matrix for 3D rendering.
    m_screenDepth = 1000.0f;
    m_projectionMatrix = XMMatrixPerspectiveFovLH( fieldOfView, screenAspect, 0.1f, m_screenDepth );

    // Initialize the world matrix to the identity matrix.
    m_worldMatrix =XMMatrixIdentity();

    return true;

```

Updated Picture: https://www.dropbox.com/s/me86svum7cep1ti/D3D11%20Picture.PNG

# Answer
> 0 votes
I think I have fixed it. I am using DirectX Tool Kit as well, and now that I got the graphics debugger to work, I noticed that the depth testing was being disabled. I can only assume it is a result of using SpriteBatch to render text and other 2D components. So simply setting the depthStencilState at the begining of my render function, it fixed it.

---
Tags: directx, rendering, directx11
---


# Question
Title: Different bounding volumes for culling and collision detection
Should an object in a 3D-engine use different bounding volumes for collision-detection (broad-phase) and culling?

Basically `class renderBounds` and `class physBounds` versus `class boundingVolume`?

Each of this classes then could either contain the same type of volumes (AABB's, kDOP's, sphere's etc.) or a special fitting one for the particular object.

(note: without considering of using an external physics engine)

# Answer
> 1 votes
Usually I see AABB used for broadphase in a collision detection. For culling I usually see a depth buffer + frustum culling.

You can cull entire models from the frustum by computing an OBB of the model in model space. This can be transformed to world space and quickly tested against the frustum. Alternatively the frustum can be transformed to model space and tested against a model space OBB, or even model space AABB.

Whatever you do, it won't be worth the time unless you're cutting off the top portion of N in a large O( N^2 ) loop, or you're playing nice with the cache. Maybe it is for these reasons many people only do triangle to frustum checks, or let the driver do screen space culling.

# Answer
> 0 votes
A lot dependa on what an 'object' is and how complex its topology is. Consider a character model with 16 bones. Each bone has a physics volume used for hit detection in an fps. But when you render the object all you care about is the player. In this case thr physics representation is complex but visibility is a sphere-v-frustum which is cheap ans rotationally invariant. A tank with articulatef parts is the same. The key to effectice culling is to make sure the cpu cost of culling is cheaper than the cpu costs of drawing plus the gpu costs of drawing. Spend too much time culling and you lose. Often the AABB of an entity in the broadphase works as long as it is not a complex object - there is a one to one relationship between the physics entity and a draw call.

One additional thought is that sometimes you wany to use some kind of hierarchical structure to accelerate culling. In this case the broadphase aabb would need to be inserted into this structure or the frustum ia tested against the broadphase for overlaps. Finally some things have no physics such as particle systems ao you will want your culling system to support those things as well. Hope that helps.

---
Tags: collision-detection, occlusion
---


title: Given seams, how do I unfold a mesh?

text:
# Question
Title: Given seams, how do I unfold a mesh?
If a user marks a seam on a mesh, how do 3D modelling programs (like Blender or Maya) unfold the mesh on to a 2D surface? I can only find papers trying to automate the seaming for you. Given *user-defined* seams, does the unfolding happen?

# Answer
> 0 votes
One simple method is to use a force-directed graph approach. You model each vertex as a point mass in UV space. Each vertex receives a spring-like force that tries to keep it at the correct distance in UV space from each (post-seam-split) vertex with which it shares an edge, attractive when they're too far apart and repulsive when they're too close.

That handles (approximate) local shape preservation, but then you need a force to spread non-adjacent faces apart so they don't stay crumpled-up in UV space. You could model this as a weak repulsion from non-adjacent vertices or, as is done with Pelt Mapping, an attraction between seam vertices and a "stretching frame."

Other types of iterative constraint solving can work too, like using Verlet integration with an angular constraint to try to preserve face or edge angles.

The hope is that after many iterations, the local corrections will diffuse through the connections between vertices to arrive at a globally-acceptable output.

A more sophisticated approach is called Least Squares Conformal Mapping.

---
Tags: algorithm, geometry, 3d-meshes, uv-mapping, seams
---


# Question
Title: How can I implement a futuristic "barrier field" that reacts to hits?
I want to implement a "shield" that reacts to projectile hits. Currently, my colliders are mapped to the animated sprite's outline on all frames.

I'm looking for something like the image below. For example, what shader could I use?

# Answer
Here's how I've approached this situation in Unity in the past:

I create a custom shield shader that accepts some number of vector parameters (typically 3 or 4), each representing a recent hit. The xyz components are the position of the hit in local coordinates, and the w component is the intensity.

Within the fragment shader, I compute the object-space distance of the pixel being shaded from each recent hit's xyz position, and apply a falloff curve to get a brightness value. The falloff range or the max brightness can be linked to the intensity parameter w. After summing the brightness from all hits, I use that as a blend weight for my "shield active" output value (usually a texture or refraction effect).

I then have a script on the shield GameObject that logs recent hits, keeping a buffer of Vector4s the same size as the shader accepts. Each frame in Update(), it decays the w parameter on each (so hits fade over time) and passes the vectors to the shield Renderer's material with SetVector() for rendering. This script needs some logic for how to allocate the limited hit slots when a new hit comes in - for instance overwriting old/weak hits first, or combining two nearby hits into a single more intense one.

(Ordinary cautions about creating and caching a unique material instance and manually Destroy()ing it when done apply, so that you don't leak materials)

If you need a lot of simultaneous hits sometimes, and can afford the extra draw calls, you can also render the mesh repeatedly for each (batch of) hit(s) using DrawMeshNow().

If you want to do this without custom shaders, and are okay with the shield effect sitting right on the object's skin (instead of a distance away), you could try using Projectors with the default "Projector/Light" material to effectively "stamp" a shield glow onto the geometry. Note that this re-renders every object in the projector's volume, for each projector placed, so your draw calls go up. I'm not sure if projectors work with sprites, so you might need to create a mesh the shape of your sprite for the projector to shine onto.
> 1 votes

# Answer
If you could generate a texture which is about the normal on the surface of the object you want to show the shield. There is no need for shaders.

* First, you need to prepare a cellular texture like the reaction in the picture, which should be transparent. Then, about the reaction when hit by the beam.
* Then, you need to prepare a(maybe several) dome for your shield and apply the material which contains the texture in the first step.
* After that, when hit by a beam, just put the dome at the hit point, and change its rotation to face the contradict direction of the normal.

So, the only important thing is to find out the normal of your sprite.

About shader solution, I'm not sure if this method could work. This is just an idea:

1. You need to pass the hit point's world coordinate(for example, `pos`) into your shader.
2. Use `newpos = mul(UNITY_MATRIX_MVP, pos)` to get a position. and `newpos.uv` to get the UV.
3. Draw the texture in the area around the `newpos.uv` within a radius in the fragment shader. However, this method could not generate the correct perspective effect.

Hope this can be a bit helpful to you.
> 0 votes

---
Tags: unity, shaders, sprites, graphic-effects
---


title: Player being covered by glClearColor?

text:
# Question
Title: Player being covered by glClearColor?
Here is a video of the problem: https://www.youtube.com/watch?v=6vnDOB1Vk4o (this is the game I've been making for fun/practice).

You notice, in the beginning of the video, I walk off the map and into the black. When I do so the black covers the player.

I draw the player last in my code:

```
 // Draw the player & the world
public void draw(Graphics g, Graphics graphics, GameStateManager gsm) {
    glClearColor(0, 0, 0, 0);
    System.out.println(player.getPlayerX() + " - " + player.getPlayerY());
    glViewport(-(int)player.getPlayerX() + 350, -(int)player.getPlayerY() + 300, Display.getWidth(), Display.getHeight());
    worldGen.worldGenerator();
    // Draw the player to the screen (60, 60)
    player.draw();

}

```

# Answer
> 1 votes
Why are you moving the viewport? You should only really touch it when the screen resizes.

because you move the viewport everything outside it will not be drawn.

instead adjust the view matrix to move the "camera" to where the player is this allows you to have larger levels as well.

---
Tags: opengl, java
---


# Question
Title: Tile map only rendering 1 layer when it should be 3
I've been working on this for a while and I can not seem to figure it out. I had the fileParser() method in the constructor and it worked fine. Then I was told it's very bad practice to have it in the constructor. So I moved it to it's own method(which required making most of the variables static) and moved the call to the main Game class and now it runs without errors, but only my last layer is rendering. I've moved things in the class around. I've used more variables than there are at the moment. I've checked my files and they are for sure 32 by 32. So I have no clue why this is happening.

```
import com.stardust.main.gfx.Assets;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TileMap
{
   private static final int TILE_SIZE = 32;
   //placeholder for each tile
   BufferedImage[] tiles = new BufferedImage[37];

   //array of tile types
   private static int[][] map = new int[TILE_SIZE][TILE_SIZE];
   //position coordinates
   private int posX, posY;
   //Edge of map Cooridinates
   public static int sx, sy;
   private String fileName;
   private static int x = 0, y = 0;

   public TileMap(int posX, int posY, String fileName) throws IOException
   {
       this.fileName = fileName;
       this.posX = posX;
       this.posY = posY;
       this.sx = map.length * TILE_SIZE;
       this.sy = map.length * TILE_SIZE;

       setTile();

   }

   public void render(Graphics g)
   {
       for(int x = 0; x < TILE_SIZE; x++)
       {
           for(int y = 0; y < TILE_SIZE; y++)
           {
               int textureType = map[x][y];
               BufferedImage texture = tiles[textureType];
               g.drawImage(texture, posX, posY, null);
               posY += TILE_SIZE;
           }
           posX += 32;
           posY = Game.mapY;
       }
       posX = Game.mapX;
       posY = Game.mapY;

   }

   private void setTile()
   {
       tiles[0] = Assets.grass;
       tiles[1] = Assets.dirt;
       tiles[2] = Assets.water;
       tiles[3] = Assets.tree;
       tiles[4] = Assets.multiTree;
       tiles[5] = Assets.NSpath;
       tiles[6] = Assets.uprtPath;
       tiles[7] = Assets.EWpath;
       tiles[8] = Assets.upltPath;
       tiles[9] = Assets.dnltPath;
       tiles[10] = Assets.dnrtPath;
       tiles[11] = Assets.watgrsdn;
       tiles[12] = Assets.watgrslt;
       tiles[13] = Assets.watgrsup;
       tiles[14] = Assets.watgrsrt;
       tiles[15] = Assets.watgrsSE;
       tiles[16] = Assets.watgrsSW;
       tiles[17] = Assets.watgrsNW;
       tiles[18] = Assets.watgrsNE;
       tiles[19] = Assets.wallWood;
       tiles[20] = Assets.pointer;
       tiles[21] = Assets.pathOpRt;
       tiles[22] = Assets.pathOpLt;
       tiles[23] = Assets.pathOpDn;
       tiles[24] = Assets.pathOpUp;
       tiles[25] = Assets.pathOpAll;
       tiles[26] = Assets.roughWood;
       tiles[27] = Assets.pathOpen;
       tiles[28] = Assets.counter;
       tiles[29] = Assets.storeDude;
       tiles[30] = Assets.pot;
       tiles[31] = Assets.singleHouse;
       tiles[32] = Assets.doubleHouse;
       tiles[33] = Assets.wepBanner;
       tiles[34] = Assets.armBanner;
       tiles[35] = Assets.innBanner;
       tiles[36] = Assets.blankTile;
   }

   public void fileParser() throws IOException
   {
       BufferedReader in = new BufferedReader(new FileReader(fileName));

       String line;

       while((line = in.readLine()) != null)
       {
           String[] values = line.split(",");

           for(String str : values)
           {
               int str_int = Integer.parseInt(str);
               map[x][y] = str_int;
               ++y;
           }
           ++x;
           y = 0;
       }
       x = 0;

       in.close();
   }
}

```

# Answer
> 1 votes
Your map\[\]\[\] is static so the three objects (layers) will access the same map (and overwrite it). You should make it nonstatic to allow each object to have it's own.

Secondly the fileParser() method is private so you will have to either make it public or call it inside the class.

---
Tags: java, tilemap
---


# Question
Title: Loading content into an Winforms/XNA Editor's content project
So i am bulding a game editor/engine basically for teh lulz but i have encountered a problem i cannot seem to fix, i cannot load any new content through the Winforms UI during runtime.

I tried using the File.Copy method in .Net to copy the files to the content folder but this does not seem to work as the file needs to be added to the content project in order for my ContentManager object to read it.

Any thoughts on how to fix this?

# Answer
> 2 votes
Dynamically importing and processing content at runtime is explained in the sample WinForms Series 2: Content Loading. This is the preferred method.

You can also build an XNA Content Project file using MSBuild. this blog post explains how. You can create a temporary project file, so you don't need to modify or rebuild files in your Solution.

Additional information in this blog post. It helpfully explains the layers of the XNA Content Pipeline (so you can decide what layers it would be best to interface with to meet your requirements).

# Answer
> 0 votes
In Visual Studio...

1. Right mouse click on the Content Project
2. Select 'Add' then 'Existing Item...'
3. Navigate to the folder containing your content, change the filetype from the drop down box if needed, select your content file, then click on 'Add'.
4. Use your content.

---
Tags: xna, c#, .net, xna-content-pipeline, map-editor
---


title: Making a parenting system

text:
# Question
Title: Making a parenting system
Each Entity can have one parent and any number of children. They have a position vector and a quaternion orientation.

I know that I can make objects *look* like they're in a hierarchy by multiplying parent transforms all the way to the root, but how to I get the canonical coordinates out of those transformations? I need to have the real position of every Entity in the world in order to update their bounding meshes.

I would like to keep my drawing code for everything as just this:

```
XMMATRIX transform = XMMatrixRotationQuaternion(orientation);
transform = XMMatrixMultiply(transform, XMMatrixTranslation(position));
transform = XMMatrixMultiply(world, transform);
model->Draw(context, *states, transform, view, projection);

```

Eg. without relying on visual tricks to get the hierarchy looking right, so no multiplications with parent transforms while rendering.

How do I properly change a child's position and orientation with respect to the parent?

# Answer
Fundamentally, if you want objects that are in a hierarchy relative to a parent, you need to do a concatenation of the local-to-parent transform with the parent. This is how it works. I see now way around it, and I wouldn't describe it as 'visual tricks' - that's how a transform hierarchy works. Objects have orientations and positions in world space, but if they are relative to their parent, they need to perform transforms every time they, or their ancestors, move.

However, I think you can have your cake and eat it too: use two transforms: one a local-to-parent transform and one a cached worldspace transform. You also want a dirty flag. When an object moves in world space the local-to-parent matrix, or in your case orientation and translation, is updated and the dirty flag is set. All of the children then have their dirty flags set. Any request for an entities world matrix must first check the dirty flag. If set travel up to the first ancestor that is not dirty and recalculate each descendants world space matrix, clearing their dirty flag, back to the original entity. Then return the new world matrix. This avoids recalculating matrices of top level objects that have not moved or children who are part of a hierarchy that is static this frame. Normally this lazy evaluation is hidden behind the object's GetWorldMatrix() method so the caller never sees it. All the rest of the work is hidden behind SetWorldMatrix( ), SetLocalToParentMatrix(), etc. They do all the right operations under the hood.

I would also note that while storing orientation and translation is cheaper from a storage perspective, it is quite expensive to perform a quaternion to matrix every frame. This solution might help you for objects that do not move often, but I suspect it might actually be more performant to store the local-to-parent transform as a matrix, but I am not sure what kind of transforms you are performing.
> 0 votes

---
Tags: directx11
---


# Question
Title: How can I implement bounding volume subdivision for my sprite images?
Lately, I have been researching different Collision methods, how to deal with multiple collisions and different types of bounding shapes, circles, rectangles, polygons and ellipsoids. Some common collision methods are the:

'Axis aligned bounding box'

```
if (rect1.x < rect2.x + rect2.width &&
   rect1.x + rect1.width > rect2.x &&
   rect1.y < rect2.y + rect2.height &&
   rect1.height + rect1.y > rect2.y) {
    // collision detected!
}

```

'Circle Collision'

```
double dx = (circle1.x + circle1.radius) - (circle2.x + circle2.radius);
double dy = (circle1.y + circle1.radius) - (circle2.y + circle2.radius);
double distance = Math.sqrt(dx * dx + dy * dy);

if (distance < circle1.radius + circle2.radius) {
    // collision detected!
}

```

---

**The bounding box/shape dilema**

For one my projects, I am using images, which are rectangle by nature. However, to simply check for intersections with the images' edges would result in unsatisfactory collision detection. As Gamasutra puts it:

> " The experience of playing some of the early flight simulators illustrated how bad collision detection can ruin a game. Flying through a mountain peak and surviving isn’t very realistic. Even some recent games have exhibited collision problems. Many game players have been disappointed by the sight of their favorite heroes or heroines with parts of their bodies inside rigid walls. Even worse, many players have had the experience of being hit by a rocket or bullet that was “not even close” to them. "

From that resource I discovered an interesting method of making bounding boxes or circles which Gamasutra calls subdivision

*I am having trouble thinking how to do this subdivision process for my images (as I am working with images) and how to properly implement either subdividing process within my collision reliant app.*

For example take mario and a koopa shell. I wouldn't want their transparent space to trigger intersection

# Answer
Kiro,

Imagine Mario and the Koopa shell surrounded by rectangles. Once you detect that the two rectangles are overlapping, you then need to perform per-pixel intersection testing. There are many ways to do this, all depending on the kind of engine you are using. Essentially you want to compare each pixel in one image against the pixels in the other image.

I found an explanation of one technique here, which seems to encode spans to accelerate it, using SDL2, here: http://lazyfoo.net/SDL\_tutorials/lesson18/

And I found these stack overflow ones:

https://stackoverflow.com/questions/173199/can-someone-explain-per-pixel-collision-detection https://stackoverflow.com/questions/20596893/per-pixel-collision-detection

And some more:

http://www.austincc.edu/cchrist1/GAME1343/PerPixelCollision/PerPixelCollision.htm

Good luck!
> 0 votes

---
Tags: collision-detection
---


# Question
Title: In Ogre, how to get the depth buffer value?
I am rendering an object to a texture using the following setup code which I copied from Ogre's rendering to texture tutorial:

```
Ogre::RenderTexture *renderTexture = rtt_texture->getBuffer()->getRenderTarget();

renderTexture->addViewport(myViewPoint); //the original code uses mCamera, but I want
//to render the scene from a different view point.
renderTexture->getViewport(0)->setClearEveryFrame(true);
renderTexture->getViewport(0)->setBackgroundColour(Ogre::ColourValue::Black);
renderTexture->getViewport(0)->setOverlaysEnabled(false);

```

Is there any way I can get the depth value at runtime as seen from `myViewPoint`?

I tried to use:

```
Ogre::GLDepthBuffer *depthBuf = renderTexture->getDepthBuffer();

```

but it didn't compile and the compiler says `GLDepthBuffer is not a member of Ogre`.

# Answer
To use the class "GLDepthBuffer", you will have to manually include (and link) the OpenGL RenderSystem into your application (since that class is part of that Ogre plugin):

```
#include <RenderSystems/GL/OgreGLDepthBuffer.h>

```

However, Ogre currently does not provide a direct way to retrieve the depth buffer. The following code will help you to get the GLDepthBuffer instance:

```
Ogre::DepthBuffer* pDepthBuffer = OgreFramework::getSingletonPtr()->m_pViewport->getTarget()->getDepthBuffer();

if(OgreFramework::getSingletonPtr()->m_pRoot->getRenderSystem()->getName().find("OpenGL") != Ogre::String::npos)
{
    Ogre::GLDepthBuffer* pGlDepthBuffer = static_cast<Ogre::GLDepthBuffer*>(pDepthBuffer);
    Ogre::GLRenderBuffer* pRenderBuffer = pGlDepthBuffer->getDepthBuffer();
}

```

Unfortunately, the last line will not yield the expected result, since that will only return a null pointer as described in the API.

**Bottom-line:** You will have to find a way to access the depth buffer in OpenGL via the context (Ogre::GLContext and its subclasses for various platforms) or the FBOs. As a starting point, search the following method in the Ogre code base (part of multiple classes):

```
getCustomAttribute( const String& name, void* pData )

```

Alternatively you can also retrieve the context by adding the following lines below the previous code snippet (on Windows; other platforms have similar ways):

```
Ogre::GLContext* pGLContext = pGlDepthBuffer->getGLContext();

if(WIN32)
{
    Ogre::Win32Context* pWinContext = static_cast<Ogre::Win32Context*>(pGLContext);
}

```

If you found a way, please let us know either on the forums or even better, create a pull-request for our repository on BitBucket and we might merge it in.
> 1 votes

---
Tags: ogre
---


# Question
Title: Collisions reflecting ball velocities incorrectly
Ok so this is for a small uni project. My lecturer provided me with a framework for a simple brickbreaker game. I am currently trying to overcome to problem of detecting a collision between the two game objects. One object is always the ball and the other objects can either be the bricks or the bat.

```
public Collision hitBy( GameObject obj )
{
    //obj is the bat or the bricks
    //the current object is the ball

    // if ball hits top of object
    if(topX + width >= obj.topX && topX <= obj.topX + obj.width &&
       topY + height >= obj.topY - 2 && topY + height <= obj.topY){
        return Collision.HITY;
    }

    //if ball hits left hand side
    else if(topY + height >= obj.topY && topY <= obj.topY + obj.height &&
            topX + width >= obj.topX -2 && topX + width <= obj.topX){
        return Collision.HITX;
    }

    else return Collision.NO_HIT;
}

```

So far I have a method that is used to detect this collision. The the current obj is a ball and the obj passed into the method is the the bricks. At the moment I have only added statement to check for left and top collisions but do not want to continue as I have a few problems.

The ball reacts perfectly if it hits the top of the bricks or bat but when it hits the ball often does not change directing. It seems that it is happening toward the top of the left hand edge but I cannot figure out why.

I would like to know if there is another way of approaching this or if people know where I'm going wrong.

Lastly the collision.HITX calls another method later on the changes the x direction likewise with y.

# Answer
It doesn't change the direction because you didn't handle it.. you want something like ball bouncing

take a look at this example :

**NOTE**: I know you asked it for android/java but I did it in c# it was an assignement in WinForms :) but just look maybe it'll give some idea

```
 public void moveBall(Rectangle r)
 {
       x = ballLocation.X + vX;   // x and y are the new coordinate of the ball
       y = ballLocation.Y + vY;

       if (x + diameter > r.Width) // when the ball moves right and hits the right
                                   // border of the form
       {
           // vX is the ball velocity on X axis
           // set new velocity on x axis but convert it to negative
           // so the ball will move left
           vX = new Random().Next(minVelocity, maxVelocity);
           vX = -vX;
       }
       else if (x < 0) // when the ball move left and hits the left border
       {
           // set new velocity (Note that I didn't convert it to negative
           // because i'm getting a positive value)
           vX = new Random().Next(minVelocity, maxVelocity);
       }

       if (y + diameter > r.Height) // when the ball hits the bottom border of the
                                    //form
       {
           // vY is the ball velocity on Y axis
           // set new velocity and convert it to negative
           // so the ball will move up
           vY = new Random().Next(minVelocity, maxVelocity);
           vY = -vY;
       }
       else if (y < 0) // when the ball hits the upper border of the form
       {
           // set new velocity on Y axis
           // so the ball will move down
           vY = new Random().Next(minVelocity, maxVelocity);
       }
        // set the ball location to the new values
        ballLocation = new Rectangle(x, y, diameter, diameter);
    }

```

Note : in all screens no matter if it's phone or pc or tv screen, the upper left corner is (0,0,RGB) means -\> pixel which construct from point and one of the colors :RED ,GREEN,BLUE. So if you want to move object to :

**Right:**

add value to x axis

**Left :**

subtract value to x axis

**Down:**

add value to y axis

**Up:**

subtract value to y axis
> 1 votes

# Answer
So from what I understand your coordinate system's origin is at the top left of the screen.

I think you need to get rid of your magic number in your IF statements first (I also split it up into two IF statements, easier to read):

```
// if ball hits top of object
if(topX + width >= obj.topX && topX <= obj.topX + obj.width) {
    if(topY + height >= obj.topY && topY + height <= obj.topY + obj.height) {
        return Collision.HITY;
    }
}

```

Now that might have fixed it partially, the next thing I would do is reset the position of the ball when it collides (if you're not doing so already somewhere else):

```
// if ball hits top of object
if(topX + width >= obj.topX && topX <= obj.topX + obj.width) {
    if(topY + height >= obj.topY && topY + height <= obj.topY + obj.height) {
        setY(obj.topY - height);
        return Collision.HITY;
    }
}

```

This way during the next frame update it won't think that ball and obj are colliding again. It may be executing this code multiple times before you can even see it on the screen. This is the same way I would do it for the left, right, and bottom collision.
> 1 votes

# Answer
Restated, you have the following problem:

You have two rectangles, and wish to categorize them into one of three categories:

1. No collision
2. A collision with the left or right
3. A collision with the top or bottom

The first one is simple, and you should not write your own rectangle intersection function.

I see that your post is tagged java and android, so I will point you to the documentation for the Android Rect class: http://developer.android.com/reference/android/graphics/Rect.html

Part 1 of the problem can be addressed by use of the Rect class by taking the x,w,width,height as so:

```
Rect myRect = new Rect(topX,topY,topX+width,topY+height);
Rect otherRect = new Rect(obj.topX,obj.topY,obj.topX+obj.with,obj.topY+height);
if(Rect.intersects(myRect,otherRect)){
//collision
}else{
//no collision
}

```

The SECOND part of the problem requires the centers of the objects and the direction from one to the other, and can be done simply using Math.atan2.

```
double theAngle = Math.atan2(myRect.centerY()-otherRect.centerY(),myRect.centerX()-otherRect.centerX());

```

And this gives you the direction in which the center of your object is in relation to the center of the other object.

Of course, this still is not done.... you need to know what the spread of angles are for the corners of the other object, so you take the angles from the center of the other object to the corners in question (you will be able to filter out three of them based on whether or not the centerx/centery is less than or greater than the other object.

Once you've figured out the quadrant, you can figure out the angle at which you are on one face or the other, and then you're done.
> 1 votes

# Answer
I made an Atari breakout game in my hs comp sci class, and I had trouble reflecting the ball off surfaces because I used x++ and y++, etc. to control the direction of the ball. To make this more efficient, I used vectors to control the speed and direction of my ball:

```
x+= speed * cos(theta);
Y+= speed * sin(theta);

```

Incrementing theta by Pi/2 radians (90 degrees) allows it to deflect easily on intersection and requires very few lines of code. You can even deflect it at an angle other than 90 degrees.

For your intersections, you could just think of the ball surrounded by a rectangle and use the axis aligned bounding box intersection method. Check whether the objects' borders are touching or within each other.
> 0 votes

# Answer
If you want to make sure it handles the collision perfectly without over shooting the brick, you can use the method mentioned in this answer:

https://stackoverflow.com/questions/18704999/how-to-fix-circle-and-rectangle-overlap-in-collision-response/18790389#18790389

You give it the current position and future position of the ball and it gives you intersection time, the normal, and a point.
> -1 votes

---
Tags: java, android, collision-detection
---


title: Box2D pixel to meter conversion

text:
# Question
Title: Box2D pixel to meter conversion
I have a game that was written in pixels and now I want to change it to meters like(box2D do). How I need to do that. I have wached a lot of tutorials and all they have some SCALING FACTOR but when I implement it my game don't work as I aspected. How I need to do that? For example I have a Coin and I want to make position of that coin random. I also want that coin sprite have a CircleShape (Box2D). Here are my code where I update my coin coordinates at specific time

```
if(time > 1.5f && !goToWallet && setUpCoin){
                coin.setCoinPosition(-100, -100); // do not show coin on the screen
                coin.update(coin.getCoinX(), coin.getCoinY());
                cam.update();
                if(showTime > MathUtils.random(5, 20) && !goToWallet){
                    coin.setCoinPosition(MathUtils.random(50, Gdx.graphics.getWidth() - 50)/100f, MathUtils.random(50, Gdx.graphics.getHeight() - 50)/100f); // random position of the screen IN PIXELS!!!
                    coin.update(coin.getCoinX(), coin.getCoinY());
                    cam.update();
                    time = showTime = 0.0f;
                }
            }

```

The problem is that is very easy to do in pixels, but How I need to do that in meters?

Here's my Coin class

```
public class Coin {
    /*
    A lot of variables
    */

    private final float radius;
    private BodyDef body;
    private FixtureDef bodyPhysics;
    private static Box2DDebugRenderer rend;
    private static World world;
    private static CircleShape coin;

    public Coin(World world, Box2DDebugRenderer rend){
        this.rend = rend;
        this.world = world;

        body = new BodyDef();
        bodyPhysics = new FixtureDef();
        coin = new CircleShape();
        coin.setRadius(.05f);
        body.type = BodyType.StaticBody;
        bodyPhysics.shape = coin;
        world.createBody(body).createFixture(bodyPhysics);
}
public void setCoinPosition(float x, float y){
    this.x = x;
    this.y = y;
    coin.setPosition(new Vector2(x, y));
}

```

}

# Answer
Like you said, you need a scaling factor.

```
float scaling = // some number. Probably something like 100 will do for Box2D.

public Vector2 metersToPixels(float xMeters, float yMeters) {
    return new Vector2(xMeters / scaling, yMeters / scaling);
}

public Vector2 pixelsToMeters(float xPixels, float yPixels) {
    return new Vector2(xPixels * scaling, yPixels * scaling);
}

public void setCoinPositionPixels(float x, float y){
    // Assuming "x", "y" etc. are in pixels.
    this.x = x;
    this.y = y;
    // But Box2D is in meters
    coin.setPosition(pixelsToMeters(x, y));
}

```

Then all of your earlier functions should magically work.

Also, I think you're a bit confused about Box2D. In Box2D, a body is a physical object with mass, moment of inertia, etc. Many fixtures may be attached to a body, but they are relative to the body's center of mass. By default, the fixtures will move with the body (i.e they may fall with gravity). So what you probably want is something like:

```
coin.body.SetTransform(pixelsToMeters(x, y), 0.0f);

```

That will move the body instead of the fixture, which is probably what you want. Note that the body will still behave according to gravity after you've moved it.
> 1 votes

---
Tags: java, libgdx, box2d
---


# Question
Title: Processing - implement a first person camera?
First off, I'm sorry if there are duplicates of this. I did an extensive Google search but was unable to find anything that made sense to me. (I am new to 3D rendering and such.)

I want to make a first person camera that the user can control with the mouse. My current implmentation in Processing looks like this:

```
PMatrix3D cam;
int oldMouseX=0, oldMouseY=0;
void setup(){
    // ...
    cam = new PMatrix3D();
}
void draw(){
    // ...
    int deltaX=oldMouseX-mouseX;
    int deltaY=oldMouseY-mouseY;
    oldMouseX=mouseX;
    oldMouseY=mouseY;
    cam.rotateY((PI/600)*deltaX);
    cam.rotateX((PI/600)*deltaY);
    PVector x = cam.mult(new PVector(1, 0, 0), new PVector(0, 0, 0));
    PVector y = cam.mult(new PVector(0, 1, 0), new PVector(0, 0, 0));
    PVector d = x.cross(y); d.normalize(); d.mult(R);
    float fov = PI/3.0;
    float cameraZ = (height/2.0) / tan(fov/2.0);
    perspective(fov, float(width)/float(height), cameraZ/10.0, cameraZ*1000.0);
    camera(0, 0, 0, d.x, d.y, d.z, y.x, y.y, y.z);
    // render objects
}

```

It works well, but there is a problem. When the mouse is moved along the x-axis of the screen, and then the y-axis, or in some way one axis at a time, the camera rolls. I understand that 3D rotation is supposed to work like that, 2 consecutive rotations around 2 axes make a rotation around the third. The problem is that once the camera is in this rolled state, it is difficult to get it to be straight again.

How can I make it so it is easy to point the camera in any direction? Please explain in easy to understand terms, if possible.

Also, I am a bit confused on

```
cam.rotateY((PI/600)*deltaX);
cam.rotateX((PI/600)*deltaY);

```

Before, I had it as

```
cam.rotateX((PI/600)*deltaX);
cam.rotateY((PI/600)*deltaY);

```

But that cause the x and y axes to be switched. (i.e., moving the mouse horizontally caused the camera to rotate vertically.) Why is this?

# Answer
> 1 votes
You can use just the `camera()` method to change the perspective more easily.

To use it, you probably want two variables: `rotationAngle` and `elevationAngle`. Moving the mouse sideways changes `rotationAngle` between `0` and `TWO_PI`. You can then set variable `centerY` to `sin(rotationAngle)` and `centerX` to `cos(rotationAngle)`. Moving the mouse up and down would change `elevationAngle` to anywhere between `0` and `PI`. Multiply `centerX` and `centerY` by `sin(elevationAngle)` and set `centerZ` to `-cos(elevationAngle)`. You can then call `camera()` with the calculated values.

Final code:

```
float rotationAngle;
float elevationAngle;

float centerX;
float centerY;
float centerZ;

void setup() {
  // ...
}

void draw() {
  // ...
  updateCamera();
  // render objects
}

void updateCamera() {
  rotationAngle = map(mouseX, 0, width, 0, TWO_PI);
  elevationAngle = map(mouseY, 0, height, 0, PI);

  centerX = cos(rotationAngle) * sin(elevationAngle);
  centerY = sin(rotationAngle) * sin(elevationAngle);
  centerZ = -cos(elevationAngle);

  camera(0, 0, 0, centerX, centerY, centerZ, 0, 0, 1);
}

```

---
Tags: 3d, camera, processing
---


# Question
Title: Is there a way to use the ContentManager with full directory paths
So i want to figure out a way to use the ContentManager.Load method with full directory paths, so lets say

```
Content.Load<T>(@"Images\SomeImage");

```

becomes

```
Content.Load<T>(@"C:\Users\UserName\Documents\Visual Studio 2013\Projects\MyProject\Content\SomeImage");

```

Thanks in advance.

# Answer
> 1 votes
Set `Game.Content.RootDirectory` to the path you want and then just specify the file name portion. But keep in mind that you still have to include them in the Content project.

If you don't want to/can't do that, then forgo the ContentPipeline altogether.

---
Tags: xna, c#, .net, xna-content-pipeline, map-editor
---


# Question
Title: Overload how an object instance of a class is treated when used
So I've made this struct that encapsulates a `glm::vec4`. This is because `vec3`s are treated as 16-byte in GLSL, but I don't want to assign a `vec4` if I only really need 3 components. Anyway, my question isn't really OpenGL/GLSL specific, but since it is in this context it would be easier to post it here.

Below is my "overloaded vec3", and some code for how I use it:

```
struct GpuVec3
{
public:
    GpuVec3() {}

    GpuVec3& GpuVec3::operator=(const vec3& other)
    {
        v.x = other.x;
        v.y = other.y;
        v.z = other.z;
        v.w = 1.0f;

        return *this;
    }

private:
    vec4 v;
};

// ...

// Struct using GpuVec3 members
struct Material
{
public:
    GpuVec3 Emissive;
    GpuVec3 Ambient;
    GpuVec3 Diffuse;
    GpuVec4 SpecularAndShininess;
};

// Assign vec3 to GpuVec3 (works fine)
material->Emissive = vec3(0.1f, 0.0f, 0.0f);

// ... initializing uniform block and stuff ...

// Passing Emissive to function that expects vec3 (doesn't work, of course)
// UniformBlock3fv(GLchar* uniformBlockName, GLchar* uniformName, glm::vec3 value)
program->UniformBlock3fv("uniMaterial", "Emissive", material->Emissive);

```

In the last line of code I want to be able to pass my `GpuVec3` to a function that expects a `vec3`, this is not possible of course.

My question is, is there some way in C/C++ possible to overload how an object instance of a class is treated when used? A pseudo-code example below what I want to happen if I use my object:

```
if (material->Emissive is called) { return v.xyz; }

```

# Answer
I think you would do to keep your GPUVec3 and your vec3 as two separate classes, not one containing the other. Here's an example:

```
struct vec3
{
    float x,y,z;
};

struct GPUVec3
{
    float x,y,z, pad;

    GPUVec3() { }
    GPUVec3( float x, float y, float z ) { }
    GPUVec3( const vec3 & v ) { }

    operator vec3 const & () const { return *(vec3*)this; }

} __attribute__ ((aligned(16)));

```

I have also provided an overload that lets you assign from vec3 to GPUVec3 and back again. This isn't a complete implementation, but you get the idea - using constructors and overloads it is possible to get the conversions to be called automatically. The takeaway here is that vec3 doesn't need to be 16 byte aligned, but *can* be. Since you can assign a GPUVec3 back to a reference to a vec3, you can read back and pass around a GPUVec3's xyz without copying. The same is not true for vec3 - it is not *always* 16 byte aligned (but could be) so you can't safely just cast it to a GPUVec3. This lets you put vec3s wherever you need and only have to worry about the 16-byte alignment interchange with the GPU in gpu-centric variables.

This stack exchange has a great overview of the C++ operator idioms and includes something on assignment idioms. MOre can be found, fore sure: https://stackoverflow.com/questions/4421706/operator-overloading

Here's an example in use and compiles fine under xcode:

```
int main (int argc, char * const argv[])
{

    GPUVec3 gpuVec3;

    vec3 from;

    gpuVec3 = from;

    vec3 to = gpuVec3;

    // insert code here...
    return 0;
}

```
> 2 votes

# Answer
You could use an user-defined conversion, something like this:

```
struct GpuVec3
{
public:
    GpuVec3() {}

    GpuVec3& GpuVec3::operator=(const vec3& other)
    {
        v.x = other.x;
        v.y = other.y;
        v.z = other.z;
        v.w = 1.0f;

        return *this;
    }

    operator glm::vec3() const { return v.xyz; }

private:
    vec4 v;
};

```

You can read more about it here: http://en.cppreference.com/w/cpp/language/cast\_operator
> 0 votes

---
Tags: opengl, c++, glsl, c
---


# Question
Title: Can diffuse and specular component of Phong model shine thru object?
I have been implementing simple 3D engine in OpenGL, mostly based on tutorials by Tom Dalling. I have implemented the Phong lightening model as described in his tutorial, but I see light artifacts on concave shaped objects (and also when using normal mapping). I came to a point, where i don´t know if my code is broken, or this is actually normal behaviour, and you need special handling for it.

I think that these artifacts could be happening, because the normals of concave object at same points head back into the point light source, not actually considering there is a solid object in between. I tried to do a little scetch of this situation in 2D (for diffuse component):

So I need to know, if this is a common problem of this light model, or my calculations are wrong.

# Answer
> 2 votes
That simple lighting does not know anything about other objects in scene, nor shadows they cast. It just does the lighting knowing the light position and surface normal (and eye position for specular). That's it. No occlusion info, no light refraction, no reflection, no anything, just lighting.

If you need object shadows, there are separate techniques for that (Shadow Mapping, Stencil Shadows, etc.) Some are less well suited for self-shadowing, some are better.

Does that answer your question?

---
Tags: opengl, lighting
---


# Question
Title: Modeling object oriented snakes and ladders
I'm trying to create a basic clone of Snakes and Ladders using object oriented design. I'm struggling to model my objects and their relationships. For the time being I'm interested in moving players around the board.

I came up with three main objects. A `Board`, a `Cell`, and a `Player`. There is also the concept of a grid, which is abstract. The idea that any grid representing the state of the game can be plugged into the board. The grid is an array where each element contains a `Cell` object.

```
  class Board
    attr_reader :grid

    def initialize(input = {})
      @grid = input.fetch(:grid, default_grid)
    end

    def get_cell(index)
      grid[index]
    end

    def add_player(index, player)
      get_cell(index).add_player(player)
    end

    def remove_player(index, player)
      get_cell(index).remove_player(player)
    end

    def move_player(from, to, player)
      remove_player(from, player)
      add_player(to, player)
    end

  private

    def default_grid
      Array.new(100)
    end
  end

```

A cell instance keeps an array of players who currently occupy the cell. I'm having difficulty because cells can have behaviour. They can be just a tile with no behaviour; a portal which sends the player somewhere (snake or a ladder); an exit, which has no behaviour but must be coupled with an entrance for rendering purposes (so the player would know what entrance the exit belongs to).

The only difference between a snake and a ladder is that a snake's destination is less than its location, while the opposite is true for a ladder. So here's my implementation of `Cell`

```
class Cell
  attr_reader :location, :destination, :origin, :players

  def initialize(input)
    @location = input.fetch(:location)
    @destination = input.fetch(:destination, nil)
    @origin = input.fetch(:origin, nil)

    @players = input.fetch(:players, [])
  end

  def add_player(player)
    players << player
  end

  def type
    if origin
      location < origin ? :snake_exit : :ladder_exit
    elsif destination
      destination < origin ? :snake : :ladder
    else
      :tile
    end
  end
end

```

My instinct tells me my Cell object is poorly designed. Especially the `type` method. But I don't know how to change my design. It's trying to be too many things.

As you can see below, the board can add and remove a player from cells:

```
    def add_player(index, player)
      get_cell(index).add_player(player)
    end

    def remove_player(index, player)
      get_cell(index).remove_player(player)
    end

    def move_player(from, to, player)
      remove_player(from, player)
      add_player(to, player)
    end

```

But what if a cell has behaviour? How does it tell the board to move the player? I thought of adding a method to the `Board` class:

```
def play_turn
  get_cell(player.position).remove_player(player)
  player.position += Dice.roll
  cell = get_cell(player.position)
  case cell.type
  when :snake, :ladder
    player.position = cell.location
    get_cell(player.position).add_player(player)
  else
    cell.add_player(player)
  end
  #...
end

```

But my instinct tells me this is wrong. What if I decide to modify the game and add more cell types other than snakes and ladders? I would have to do more type checks and decide what methods to execute.

```
if cell.type == :snake
  # cell.do_something
elsif cell.type == :black_hole
  cell.consume_player(player)

```

This raises the question of whose responsibility is it to move the player? Instinctively, since teleporting to another location is the cell's behaviour, it should be the cell, right?

But how would that work when the cell has no knowledge of other cells? A cell has no knowledge of other cells so it can't possibly add the player to another cell. The board does this now.

But if moving the player is not the cell's job, then the Cell has no behaviour. It's just a data container that the board will use to make a decision on what to do with the player.

Maybe it's the responsibility of the player object? But it also has no knowledge of what cells are.

Another question is who should track player's positions? The board? The player, or the cell itself?

Sorry, there are a lot of questions here. But this is a complex problem, and I'm looking for guidance on how to simulate a player's movement on the board. I feel like my objects are poorly designed.

For the sake of completeness here is my player's class:

```
class Player
  attr_reader :name, :color, :position

  def initialize(name, color, position = 0)
    @name, @color, @position = name, color, position
  end
end

```

# Answer
> 1 votes
> I'm having difficulty because cells can have behaviour. They can be just a tile with no behaviour; a portal which sends the player somewhere (snake or a ladder); an exit, which has no behaviour but must be coupled with an entrance for rendering purposes (so the player would know what entrance the exit belongs to).
>
> ---
>
> But my instinct tells me this is wrong. What if I decide to modify the game and add more cell types other than snakes and ladders? I would have to do more type checks and decide what methods to execute.

It sounds like you should utilize some form of inheritance to to give each type of cell unique behavior, and to allow you to easily add new kinds of cells. For example, you could modify your **Cell** class to not have a type, but instead have a method called *onLanding(Board, Player)*. The basic **Cell** class would just add that player to itself using the methods provided by **Board**. Then you could create other types of cell classes that are derived from **Cell** and override its *onLanding* method to move the player to another tile, change the player's name or color, or any other functionality that your **Board** and **Player** classes provide in their public interfaces.

The **Board** class would not have to know what each type of cell in its grid is; in its *play\_turn* method, it would just call the cell's *onLanding* method whenever a player is moved to that cell. Then the cell can do whatever it needs to do to the player.

> Another question is who should track player's positions? The board? The player, or the cell itself?

Currently, that sounds like that would be most fitting to your Board class.

It might be a good idea to move Board's play\_turn method to another class, though its not necessary. You could create a new class that handles the game play and game rules, while Board's primary responsibility would be to contain the current state of the game board, such as player positions and cells. The new class could then update an instance of Board to reflect changes in the game state.

I admit I'm not any kind of master of OOD, but I hope my suggestions at least give you some ideas.

---
Tags: architecture, design-patterns
---


title: Touch drawing in the dirt

text:
# Question
Title: Touch drawing in the dirt
Which approach should I take for creating a game/app where the player, looking above the ground "canvas", would be able to "move" dirt (i.e. soil, or generally powder) around using fingers? I.e. similar to what you would achieve if you placed some dirt on a A4 white paper, and then move it around using palms/fingers?

I first thought it would be something similar to how painting apps work, but they more or less use a texture brush, and this doesn't seem to give me the desired effects. The ultimate experience would probably be to do it using a full-fledged physics particle system, but I am not sure a midrange device (Android, iOS) is capable of rendering something like that with satisfying detail in realtime? Admittedly, I am not trying to do what's shown in the video, but at least something that wouldn't look like moving "puzzles" around.

All other materials related to these search terms are merely using particles to simulate dirt flying around vehicle tires, so I am slightly stucked and I feel a nudge in the right direction might do wonders. Any algorithm/technology hints?

# Answer
> 3 votes
So i'll post my attempt here.
Idea is to have very simple particles (=speed(with friction)+position) that are layered.
The top (=0) layer shows the dust at scale 1, then every layer below has bigger scale, and those particles will move slower and slower the deeper the layer.

The difficulty here is to fine tune :
• appearance of the dust brushes (here random/with center gradient opacity).
• behavior of each particle, depending on its layer (i reduced the speed boost on lower layer, maybe the friction should be higher in lower layers too).
• size / number of particles per layer and such.

The first lines of the code are parameters that you can change to quite greatly change the way it looks.

http://jsfiddle.net/gamealchemist/4gfx1L2e/

```
// parameters
var layerCount = 3;
var dustSize = 50;
var dustPoints = 200;
var mouseRadius = 200;
var normalSpeed = 100;
var dustMaxOpacity = 0.85;
var baseScale = 1;
var friction = 0.1;
var partCountForLayer = function (layer, layerCount) {
    var tmp = 1 + (layerCount - layer);
    return 20 * tmp * tmp;
};

var dusts = []; // stores all dust image
var parts = []; // stores all particles

// create dust images
for (var i = 0; i < 5; i++) {
    dusts.push(createDust(dustSize, dustPoints));
}

// Boilerplate
var cv = document.getElementById('cv');
var ctx = cv.getContext('2d');

// Part class : defines a dust particle
function Part(layer) {
    this.x = cv.width * Math.random();
    this.y = cv.height * Math.random();
    this.vx = 0;
    this.vy = 0;
    this.layer = layer;
    this.scale = baseScale * (1 + 3 * layer);
    this.width = dustSize * this.scale;
    this.heigth = dustSize * this.scale;
    this.whichDust = Math.floor(dusts.length * Math.random());
    this.draw = function () {
        ctx.drawImage(dusts[this.whichDust], this.x, this.y, this.width, this.heigth);
    };
    // moves the dust with its current parameters
    this.update = function () {
        this.vx -= friction * this.vx;
        this.vy -= friction * this.vy;
        this.x += this.vx;
        this.y += this.vy;
    };
    // move the dust with a brush in (x,y)  having radius
    // the normalized (0;1) move is stored in dx, dy
    this.sweep = function (x, y, radius, dx, dy) {
        var xDiff = this.x + this.width * 0.5 - x;
        var yDiff = this.y + this.heigth * 0.5 - y;
        var dist = Math.sqrt(xDiff * xDiff + yDiff * yDiff);
        if ((dist > 0.5 * this.width) && (dist > radius)) return;
        this.vx += normalSpeed * dx / (2 + 3 * this.layer);
        this.vy += normalSpeed * dy / (2 + 3 * this.layer);
    };

}

// fill the layers
for (var l = 0; l < layerCount; l++) {
    var dustCount = partCountForLayer(l, layerCount);
    for (var pi = 0; pi < dustCount; pi++) {
        parts.push(new Part(l));
    }
}

// -------------------------------------------

function animate() {
    ctx.clearRect(0, 0, cv.width, cv.height);
    ctx.fillText('-_ Swipe the dust with the mouse _-', 20, 20);
    parts.forEach(function (p) {
        p.draw();
        p.update();
    });
}

setInterval(animate, 30);

// moves all particles after a brush was used
function moveDust() {
    console.log('md');
    var dx = mouse.x - mouse.startX;
    var dy = mouse.y - mouse.startY;
    dx /= cv.width;
    dy /= cv.height;
    parts.forEach(function (p) {
        p.sweep( mouse.startX, mouse.startY, mouseRadius, dx, dy)
    });
}

// -------------------------------------------

// creates an image with random points drawn on it.
function createDust(size, count) {
    var dustImage = document.createElement('canvas');
    dustImage.width = size;
    dustImage.height = size;
    var dctx = dustImage.getContext('2d');
    var sqRad = (0.5 * size) * (0.5 * size);
    dctx.clearRect(0, 0, size, size);
    for (var i = 0; i < count; i++) {
        var x = (Math.random() - 0.5) * size;
        var y = (Math.random() - 0.5) * size;
        var d = x * x + y * y;
        if (d > sqRad) continue;
        dctx.globalAlpha = dustMaxOpacity * (1 - Math.sqrt(d / sqRad));
        dctx.fillRect(x + 0.5 * size, y + 0.5 * size, 1, 1);
    }
    return dustImage;
}

// -------------------------------------------
//       Mouse handling
// -------------------------------------------

function setupMouse(canvas, preventDefault) {
    var rectLeft, rectTop;
    var hook = canvas.addEventListener.bind(canvas);
    hook('mousedown', updateMouseStatus.bind(null, true));
    hook('mouseup', updateMouseStatus.bind(null, false));
    hook('mouseout', updateMouseStatus.bind(null, null));
    hook('mousemove', updateCoordinates);
    window.addEventListener('scroll', updateRect);

    function updateMouseStatus(b, e) {
        mouse.down = !!b;
        updateCoordinates(e);
        if (b) {
            mouse.startX = mouse.x;
            mouse.startY = mouse.y;
        } else if (b!=null) {
            moveDust();
        }

        if (preventDefault) {
            e.stopPropagation();
            e.preventDefault();
        }
    }

    function updateCoordinates(e) {
        mouse.x = (e.clientX - rectLeft);
        mouse.y = (e.clientY - rectTop);
    }

    function updateRect() {
        var rect = canvas.getBoundingClientRect();
        rectLeft = rect.left;
        rectTop = rect.top;
    }
    updateRect();
};

var mouse = {
    x: 0,
    y: 0,
    startX: 0,
    startY: 0,
    down: false
};

setupMouse(cv, true);

```

# Answer
> 1 votes
This really isn't an answer, but hopefully a nudge in the right direction. I think my approach would be to have the background image painted with the hole dug, and then place a dirt pile image on top. When the user swipes across the dirt pile you can erase that portion of the dirt pile image. This way you will slowly reveal what is under it. sort of like a scratch ticket. You could darken the image on one edge of the swipe and lighten the opposite edge to simulate highlights and shadows.

---
Tags: particles, multitouch
---


# Question
Title: Can I create relative filepaths to images in an XCode SDL project?
Can I create relative filepaths to images in an XCode SDL project?

I have to use absolute filepaths as it is, but it would be much easier if I could make the filepaths relative.

# Answer
> 1 votes
Changing the working directory worked for me recently:

Go to `Product` -\> `Scheme` -\> `Edit Scheme`.

Then click `Run` on the left hand panel and then finally enter the path of the files under `Working Directory`.

All of your paths are then relative to the path you entered.

# Answer
> 0 votes
you could place your files in a folder called `resources` or whatever you want it to be at the same directory as the exe. For the file path when using a `SDL_LoadBMP()` or whatnot will be `resources/name_of_image.bmp`

# Answer
> 0 votes
XCode usually runs your project from an internal directory used for development. One easy way to get the path to your program is to query NSBundle.

```
NSString * filename = @"images/my_image.jpg";

NSString * resourcePath = [[NSBundle mainBundle] resourcePath];
NSString * fullPath = [filename stringByAppendingPathComponent:filePath];

// fullPath is now the absolute path to the file.

```

You didn't specify the language, but if you are using C++, you can still use Objective-C inside a `.mm` file, in the same project.

---
Tags: sdl, xcode
---


# Question
Title: How to move object along circumference of another object?
I have following piece of code, now i want to move the "moon" object in the orbit around "earth". please help!!

```
#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <math.h>
int main()
{
int gd,gm;
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\tc\\bgi");
setcolor(WHITE);

settextstyle(DEFAULT_FONT, HORIZ_DIR, 2);
outtextxy(10, 10, "Welcome to Graphics Programming");
outtextxy(10, 30, "My VU-ID is BC123456789");

//rectangle(x1,y1,x2,y2);
rectangle(10,60,400,400);

int Earth_x,Earth_y;
Earth_x=10+390/2;        // This expression calculates the center of the rectangle
Earth_y=60+340/2;        // as we want to draw our Earth in the center.
outtextxy(Earth_x, Earth_y, "Earth");
circle(Earth_x,Earth_y,30);

//Moon orbit
circle(Earth_x,Earth_y,100);

int Moon_x,Moon_y;
Moon_x=Earth_x+100;         //Initial coordinates of Moon
Moon_y=Earth_y;
while(1){                   // continuous loop as condition will always be true
setcolor(WHITE);
outtextxy(Moon_x, Moon_y, "Moon");
circle(Moon_x,Moon_y,10);
// redraw Moon orbit
circle(Earth_x,Earth_y,100);
delay(100);
setcolor(BLACK);
outtextxy(Moon_x, Moon_y, "Moon");
circle(Moon_x,Moon_y,10);
delay(100);

```

# Answer
Use polar coordinate system. Cast Moon's position to polar coordinates by formulas:

```
r = sqrt( sqr(Moon_x - Earth_x) + sqr(Moon_y - Earth_y) );
phi = atan2( Moon_y - Earth_y, Moon_x - Earth_x );

```

Then, you can change angle (phi) to move Moon around the center:

```
phi += angular_speed;

```

And after that cast changed polar coordinates back to cartesian coordinates:

```
Moon_x = r * cos( phi )
Moon_y = r * sin( phi )

```
> 3 votes

---
Tags: c++, graphics-programming
---


title: Maximum Number of Bends - Snake

text:
# Question
Title: Maximum Number of Bends - Snake
A naive Snake game implementation works by using a queue data structure to store the position of every single square that the snake is a part of.

You can reduce the amount of memory by only storing the location and direction of the head, the location of the tail, and an array of locations where the snake bends.

In a 100 x 100 grid, there's 10,000 squares. A queue of points (stored as pairs of bytes) would require 10,000 * 2 bytes = 19.5KiB of memory in the worst case scenario, where every square is filled up. (This would be accomplished by the snake starting on a corner, and the dots always appearing right in front of him in an S-shaped pattern.)

Assuming you can store the location of the head, direction of the head, and location of the tail in bytes (total of 2 bytes + 2 bytes + 1 byte for location), what is the maximum amount of bends that could exist in a 100x100 grid, and how much space would you save with this method in the worst case? In the average case?

# Answer
> 0 votes
You can store the direction with 2 bits: 1 for axis and 1 for pos/neg. As such, storage-wise it will be more efficient regardless of the number of bends -- about ~2.5 KB for 10,000 tiles. Store it as a bitmask as well (1.25 KB for 10K tiles) and then you have fast collision checks ("is snake on tile"). The slowest operation would be "Access nth body part" which would require you to iterate over all snake tiles, from the head, but if you don't need that operation that often, you should be fine.

# Answer
> 0 votes
In the worst case it looks to me like you're going to use **more** memory this way. Picture a snake that goes something like this: ‾|\_|‾|\_|‾ as much as possible. There are a few spots at the edge of the screen where it must go straight for a few squares but those aren't enough to overcome the higher memory storage per location unless the world is small.

While the average memory is lower what difference does that make? I would say the "naive" approach is the best one.

---
Tags: algorithm, memory-efficiency
---


# Question
Title: Explain the difference between extrapolation and interpolation
http://www.unagames.com/blog/daniele/2010/06/fixed-time-step-implementation-box2d here there are two algorithms of smoothing in case of fixed time step physics simulation. I don't understand the formula of interpolation:

```
state = currentState * alpha + previousState * (1-alpha)

```

And also I don't understand the comparison figure. Please explaing what is the meaning of multiplying `current state` with `alpha` and summing with `previous state` with `1 - alpha`.

# Answer
**Part 1: Interpolation:**

Interpolation **let's us approximate** something that already happened. Multiplying "trick" (which is just math) is to mix the previous state with the current state by a certain percentage. If previous was dark and now is bright, we assume in the middle it was grey.

So if for example we take a moving train. We know that right now it is 56km from London and an hour ago it was 140km from London, knowing these two positions (A and B) and a time between them - 1 hour, we can interpolate between them and know the trains position at any given time between now and an hour ago.

For example, we want to know trains position 15min ago. That is 15min ago from now and 45 min after an hour ago timestamp. When we need to mix 2 values, we need to sum them, each multiplied by it's proportion in the final result. Whole sum is 100%, that means that if one value is 25%, then the other one is 100% - 25% = 75%. So we make our formula

```
140 * 0.25 + 56 * (1 - 0.25) = 77

```

77km is the how far away from London our train was 15min ago iw we calculate that using linear interpolation.

Another approach to the case is if we rewrite the formula to be

```
Result = A + (B - A) * alpha

```

It has the same effect, but a slightly different explanation. We take the point A and add to it a difference between points A and B multiplied by the proportion. Repeating our example,

```
140 + (56 - 140) * 0.75 = 77

```

```
  A--------------------I------B------------London
140km                 77km   56km            0km

```

**Part 2: Extrapolation**

Extrapolation means that **we try to predict** something, knowing how it behaved in the past. Let's reuse the same example with the train. We know the train passed -84km (56-140) in last hour, so we can *assume* that in the next hour the train will pass the same, and the next hour, and the next (of course if we assume it passes through London without a stop, that's the weakness of the extrapolation, like any other prediction it's inaccurate). Anyway, if we need to guess the trains position 15 min in the future, we do:

```
Result = B + (B - A) * alpha = 56 + (56 - 140) * 0.25 = 35

```

Train will be 35km to London.

```
  A---------------------------B-----E------London
140km                        56km  35km      0km

```

*Note:*

Interpolation formula can be used to extrapolate, if we allow alpha to be outside of 0..1 range, e.g. for case 2 we can write is as being 25% of time in another direction (alpha becomes negative):

```
Result := A * alpha + B * (1 - alpha)
Result := 140 * -0.25 + 56 * (1 - -0.25) = -35 + 70 = 35

```
> 3 votes

---
Tags: box2d, physics, fixed-timestep
---


# Question
Title: Export rig from one Maya project to another
We are a team creating 3D characters for a game. Each of us is doing a separate character in a separate project. But we need all the characters to have exactly the same rig, and the rigging will be done by a different person. There is a need to speed up the process so we are thinking of doing the rig only once. Is there a way to export a rig from one Maya project and import it on a character in another?

# Answer
Yes. You can export the "rig" into its own file, so you can import it into any other character files as necessary. To do this in a clean way:

1. Make sure the rig is detached from any meshes, and skins are unbound. EDIT: make sure this rig is independent I.e. not connected in any way to any meshes or character objects in the scene that you are exporting it from.
2. Make sure the entire rig is in one unified group in the outliner.
3. Now select this main group, go to edit - select hierarchy.
4. File - export selected, export it as an .ma file. EDIT: in the export selection options box make sure you include history, channels, constraints and expressions to preserve rig behavior.

This would be the rig file. Please note that skinning and blendshapes will change from character to character and so these need to be done for all the characters individually. The common base rig can be reused however.

Hope this was useful.
> 1 votes

---
Tags: maya, rigging
---


title: Maya 3D to CryEngine3 Problem

text:
# Question
Title: Maya 3D to CryEngine3 Problem
I have an object that I am trying to export from Maya 3D to CryEngine3. In Maya the object appears fine but when I export it and place it in-game there are two problems.

1) The roof material seems to dissapear and is just a white surface which reads the standard "replace me" when you walk on it (it's still physicallised as default) and although the outside of the building appears fine (again its a solid object) the inside is "transparent" and you can see through the walls.

(after I render the default phongs)

After the materials are applied (notice the "inside" looks solid) in-game the external walls are solid with the material. However the roof turns white and the inside appears "transparent" yet is still solid and can not be walked through.

If anyone has had this problem and found a solution, or can point me in the right direction I would be grateful for the input.

# Answer
Figured it out... the internal face normals needed to be reversed. For anyone else with the same problem go to the "lighting" tab and deselect two sided lighting. Black surfaces indicate normals that have been reversed.
> 1 votes

---
Tags: maya, cryengine
---


title: OpenGL lighting appears to be clamping

text:
# Question
Title: OpenGL lighting appears to be clamping
I'm experiencing an odd problem where everything placed in front of my light appears black in my scene. This happens on multiple axes. I've searched the depths of the internet to find a solution, but I can't seem to find anything. It's also important to note that this is only happening to my models; the model's normals are fine and dandy. The rest of the scene renders as expected...

Here's how it looks:

Here's how my light is initialized:

```
GLfloat light_ambient[] =
{ 0.2, 0.2, 0.2, 1.0 };
GLfloat light_diffuse[] =
{ 0.8, 0.8, 0.8, 1.0 };
GLfloat light_specular[] =
{ 1.0, 1.0, 1.0, 1.0 };
GLfloat light_position[] =
{ 15.0, 11.0, 10.0, 1.0 };

glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);

glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.4);
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.1);
glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0.0);

glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);

```

Here's how my light's position is set:

```
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60, (double)g_window1Width / g_window1Height, 1.0, 300.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslated(0.0, 0.0, -player.camera.Dist);
glRotated(player.camera.Angle-90, 1.0, 0.0, 0.0);
glRotated(player.camera.Rot, 0.0, 0.0, 1.0);
glTranslated(-player.camera.TgtX, player.camera.TgtY, -player.camera.TgtZ);
glScaled(1.0, -1.0, 1.0);
glEnable(GL_POLYGON_OFFSET_LINE);
glPolygonOffset(g_offset[0], g_offset[1]);

glClearColor(0.0, 0.0, 0.0, 0.0);
glClearStencil(0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

glm::vec4 light_position;
light_position.x = player.mouseMapPos.x - 1;
light_position.y = player.mouseMapPos.y - 1;
light_position.z = player.mouseMapPos.z + 0.5;
light_position.w = 1.0f;

glLightfv(GL_LIGHT0, GL_POSITION, glm::value_ptr(light_position));

```

I can supply more code and information as needed...

# Answer
> 4 votes
Your main issue is that you need to fix your normals. If you want to calculate smooth normals correctly please check my answers here and here. Also make sure that your normals are **normalized**.

Your second issue is your attenuation values, I often get better results with one attenuation type. So try to use one type of attenuation and try to modify its value until you get satisfactory results.

# Answer
> 2 votes
The normals facing away from the camera are shaded black in your setup.

Add more lights into the scene that are shining on parts you want lit up, or set up the lighting with a brighter minimum brightness.

# Answer
> 1 votes
This should be a comment but I cant make them :(.

Anyhow it looks like a normals problem with your model. If you look at the bottom flower in the first picture the lighting is wrong and it looks like the light is coming from behind and above the flower instead of in front it. Try to set the color of each pixel to the value of normal to see if the normals are correct. I do not know how to do this with the fixed pipeline unfortunately.

# Answer
> 1 votes
I'm not sure, but you probably should move code that sets color of light to update frame. As I understand you initialize light color only once at start of program, but it needs to be updated each frame, in accordance with this question.

---
Tags: opengl, c++, lighting
---


title: Chamfered cube geometry generator

text:
# Question
Title: Chamfered cube geometry generator
I'm trying to create a geometry generator for a "Chamfered Cube". I've got the vertices working, but I'm stuck with creating the faces. I don't really know how I could re-arrange my algorithm to create the vertices in the right order for a triangle list / strip / fan / whatever.

This is what I've done so far: starting from the 8 vertices of a normal cube, I "push" out vertices in the shape of an eight of a sphere:

```
//start 0,0,0
var width = 8;
var radius = 3;
var segments = 16;

var half = width / 2;
var segmentStepSize = Math.PI / 2 / segments;

//displacement
var w = Math.sqrt(Math.pow((half-radius),2)*2);

// the 8 original vertex vectors
var startPoints = [
    [ 1,  1,  1],
    [ 1,  1, -1],
    [ 1, -1,  1],
    [ 1, -1, -1],
    [-1,  1,  1],
    [-1,  1, -1],
    [-1, -1,  1],
    [-1, -1, -1]
]

var x, y, z, v, x1, y1, z1, j, k;

var points = [];

for(var i = 0; i < 8; i++) {
    v = startPoints[i];
    x = w * v[0];
    y = w * v[1];
    z = w * v[2];

    for(j = 0; j < segments +1; j++) {

        for(k = 0; k < segments+1; k++) {

            x1 = x + radius * Math.cos(k*segmentStepSize) * Math.sin(j*segmentStepSize) * v[0];
            y1 = y + radius * Math.sin(k*segmentStepSize) * Math.sin(j*segmentStepSize) * v[1];
            z1 = z + radius * Math.cos(j*segmentStepSize) * v[2];
            points.push(x1);
            points.push(y1);
            points.push(z1);

        }
    }
}

module.exports = points;

```

This code results in this: http://requirebin.com/?gist=fdea95e3bfe069d7f363

## Edit

for anyone who's interested: I've shared the code here: https://github.com/ToastCommunicationLab/mesh-primitive-chamfercube

# Answer
> 4 votes
Always start with a triangle list... it's most general and easiest to think about.

You'll end up with four categories of faces:

* cube faces (quad = 2 triangles each)
* edge bevels (quads = 2 triangles each)
* corner bevels (quads = 2 triangles each)
* corner tips (last triangle)

There's different numbers of each of these, so they'll probably be handled code-wise in their own sections.

The beveling process seems to turn each of the 8 original vertices into 3 collections of vertices, one along each edge that touches that particular corner. If you keep track of these (8 * 3 * segments) piles of points, it should be clear sailing to assemble the various faces from them.

One last tip -- don't be ashamed of writing some straight-line code to bang it out. The elegant symmetries and for-loops, if they exist, may become more apparent after doing it the "dumb" way.

---
Tags: algorithm, geometry
---


title: CCMoveBy values on update()

text:
# Question
Title: CCMoveBy values on update()
This is my problem: I have a scheduled update, here I track the movements of my objects (sprites), I move them with `CCMoveBy`, and I need to constantly update the `zOrder`. For setting the `zOrder` I've made a `setZOrder()`, which it takes the actual position of the sprite.

And here is the problem, I get all the X and Y values **after** the object is in the target. I know I get the values after the object is in the new position because I've made a `CCLog`. I can read all the values from the sprite, only when it's in the new position, so everything is well sorted only when the objects are not moving.

How can I get the `CCMoveBy` values on every tick update? (or how can I get the `CCMoveBy` values in "real-time"?)

Here is an idea of my code.

```
this->schedule(schedule_selector(Game::update));

void Game::update(float dt)
{
   setZOrder();
   moveObjects();
}

void Game::setZOrder()
{
  //This function takes the X and Y position and the row and column where the sprite is.
  //Is working good. But I'm getting the "move" action values, after the object is in place.
}

void Game::moveObjects()
{
   for (i=0; i < numChildren; i++)
   {
     CCActionInterval* move = CCMoveBy::create(targetPoint, time);
     object[i]->runAction(move);
   }
}

```

# Answer
> 1 votes
If you want to do measures and move your sprite you need to use `CCSpawn` and `CCCallFunc` to call function that measures. Or even run some animation handler with `scheduleScriptFunc` method

# Answer
> 1 votes
you can use `void update(float deltaTime)` function.

just active it in `initial()` function by `this->scheduleUpdate()` and the override `void update(float deltaTime)`.

```
bool Game::init()
{
...
moveObjects
this->scheduleUpdate()
...

}

void Game::update(float deltaTime)
{
// Do whatever
setZOrder();
}

void Game::moveObjects()
{
   // Here we move object and when they reach target, move then again , and ...
   // meanwhile in update() we are setting their Z Order
   cocos2d::Vector<FiniteTimeAction*> objectMoveAction;
   for (i=0; i < numChildren; i++)
   {
     ActionInterval* move = MoveBy::create(targetPoint, time);
     objectMoveAction.pushBack(move)

   }
   object[i]->runAction(CCSequnce::create(Spawn::create(objectMoveAction), CallFunN([=](){moveObjects()},nullptr));
}

```

I din't test above code and it may have syntax error. notice I use lambda expression and is works with cocos2d v3.x .

Good Luck =)

---
Tags: cocos2d-x
---


# Question
Title: How to avoid duplication using client-server model
I am using a client-server model to write a multiplayer-capable game (in Java). Currently the clients and the server are using the same code to run the game logic, in order to enable client-side prediction. This makes sense to me, since I don't want to have to duplicate my entire codebase to make this work.

However, there are certain things that should only be done by the clients (e.g. send user input to the server, update camera position, play sounds, etc.) and certain things that should only be done by the server (e.g. send messages to the clients, remove entities, etc.).

How can I share the same code between my client and server without peppering it with "if client", "if server", etc.?

**EDIT:** It has been suggested that I should extract all common code into a library and have 2 separate projects - the client and the server - each of which should extend the common code to include custom functionality. But won't this still result in a lot of duplication?

To take an example: let's say I have an Entity class. Whenever an Entity moves, it should play a sound if it's on the client, and send a TCP message if it's on the server. Therefore I create 2 other classes, ClientEntity and ServerEntity, both of which extend Entity. Now all of a sudden my Zombie class, which previously extended Entity, needs to be duplicated across the client and server projects so that the client version can extend ClientEntity, and the server version can extend ServerEntity.

If I have a lot of classes that all extend Entity, then this results in a lot of duplication. What am I missing here? :)

# Answer
As others have said, the first step is separating logic that's shared from logic that's not. While it's great to draw that line wherever it's clear, your addendum illustrates that sometimes you don't have a clean line to split the code down.

So, how do we solve cases where the client and server want to do *semantically* the same thing (play a sound), but take different code paths to do it (actually play it, vs instruct clients to play it)?

It sounds like you presently using a hardcoded `play_sound()` method, like so:

(my Java is rusty, please excuse that I'm writing these examples in Python)

```
class Entity():
    def move(self):
        # update entity's position
        game_engine.play_sound("entity_moved.wav")

entity = Entity()
entity.move()  # will use the game engine's sound engine

```

This locks you into always using the game engine's `play_sound` method. You could subclass entities, as you stated, but there's a better way!

# Component Pattern (a.k.a. Dependency Injection)

The solution is to parameterize the sound component in your `Entity` class, a la the Component Pattern. When you initialize a new `Entity`, you pass into the constructor the sound engine you want to use.

```
class Entity():
    def __init__(self, sound_engine):
        self.sound_engine = sound_engine

    def move(self):
        # update entity's position
        self.sound_engine.play_sound("entity_moved.wav")

entity = Entity(game_engine.sound_engine)
entity.move()  # will still use the game engine's sound engine

```

The benefit of this approach is that the client and server code can initialize `Entity`s with different sound engines.

```
# On the server
class ServerSoundEngine():
    def play_sound(self, sound_file):
        notify_clients(sound_file)

entity = Entity(ServerSoundEngine())
entity.move()  # will notify clients to play the sound, instead of playing the sound itself

```

You can even store which sound engine to use with the rest of your game's in-memory runtime configuration, so you don't need a conditional step when initializing each `Entity`.

```
def initialize_game():
    if is_client:
        config["sound_engine"] = game_engine.sound_engine
    else:
        config["sound_engine"] = ServerSoundEngine()

# ...

entity = Entity(config["sound_engine"])

```

This also makes it much easier to unit test your code; you can use a mock sound engine in your unit tests that only keeps track of whether it was called, and make assertions about whether it was called correctly.

This idea can be taken to your other examples, too: instead of branching on `is_client`/`is_server` all over the place, you can initialize your game with a `RealCamera` or a `FakeCamera`. Initialize a real camera class on clients, or a dummy class with no-op methods when you're on the server, and voila! You've clearly separated what a client does from what a server does, attained high code reuse, and have no code branches once the game is initialized.

As the article suggests, you'll find the Component Pattern helpful in many other areas of your game.

To understand the Component Pattern better, here's Sandi Metz at RailsConf 2015 giving a super cool talk on dependency injection as an alternative to inheritance.

# Observer pattern

You also have the option of taking this one step further and sidestepping the "configure the class" issue entirely. Your sound events may be a good candidate for the Observer Pattern.

With the Observer Pattern, your `Entity`s would broadcast an event (e.g, `ZOMBIE_MOVED`), which your game can detect and handle at a later point while updating the frame. This not only decouples your `Entity`s from any specific sound engine, but also from any particular sound-playing API. It actually decouples your `Entity`s from playing sound entirely - `Entity` movement logic no longer needs to know that playing a sound is a side effect of moving. This keeps your movement code simpler and delineates responsibilities in your code more strongly and clearly.

With this pattern, you would no longer need to configure entities with a `sound_engine`. Also, when writing unit tests, you wouldn't have to write a mock class class anymore - you could just assert that the event was emitted. This all comes at the expense of having one more moving part in your game, and one more layer of abstraction.

(Also see this article for more on the philosophy of decoupling side effects from logic).
> 12 votes

# Answer
The cleanest way is to create a "core" project that includes shared game code.

You can use either interfaces or abstract classes to prepare your game code there and use inheritance \[1\] to extend/implement these classes in either the server or client side.

That way you do not need any if statements to distinguish between client and server code.

You should also make sure you do not rely on complex libraries in these core classes (i.e. there must not be any image reading -\> thats for the client; or db stuff -\> thats server only) in there. If you have game-data classes which both the client and the server can/should with a shared aspect, make it abstract oruse an interface.

\[1\] http://www.homeandlearn.co.uk/java/java\_inheritance.html
> 2 votes

# Answer
Extract any shared code to a library which you maintain separately.

Then implement your client and server as a separate applications which implement anything specific themselves and reference the library for any shared functionality.
> 2 votes

# Answer
The solution I prefer is to put all game-specific logic in the client. The server only acts as an I/O reflector to make sure all clients are up to date. One benefit of this approach is that the same server can serve different games, since it knows nothing about the content of any specific game.

There are a few things that have to be done centrally, such as retain the current client list, and remember the canonical game state, but these are structured as game-neutral services that the clients use.

It works quite well for 60+ different games at Boardspace.net
> 0 votes

---
Tags: java, multiplayer, server, client-server
---


# Question
Title: Formula to measure uv-mapping distortion
Does anyone know a simple way of calculating (offline) the amount a texture is distorted when mapped to a triangle like the following?

```
Vertex   Position       UV Coordinates
A        (Ax, Ay, Az)   (Au, Av)
B        (Bx, By, Bz)   (Bu, Bv)
C        (Cx, Cy, Cz)   (Cu, Cv)

```

I'm expecting two outputs: one scaling factor along each of two perpendicular axes. (These axes may or may not align with the u and v coordinate axes, eg. for a texture that has been stretched diagonally)

For my present purposes I don't need to know the direction of the stretch/compression, just how much of it there is. I do not want a single area scaling factor, because a stretch in one direction plus a compression in the other could cancel out to give a result that is close to equal-area but far from undistorted.

I *think* I can get this by computing a matrix that maps (Bxyz - Axyz) onto ((Buv - Auv), 0) & (Cxyz - Axyz) onto ((Cuv - Auv), 0) (and the triangle normal onto (0,0,1)), then finding its eigenvalues, but it seems like this should simplify or offer some shortcut. Working out all the intermediates on paper gets pretty hairy.

My searches so far are returning a lot of advice on subjectively dealing with distortion using 3D modelling packages, not analytical methods for measuring distortion.

# Answer
> 2 votes
**Edit:** my original solution didn't work. The eigenvalues of the mappping matrix only correspond to the scale factors for special orientation cases.

Fortunately, I've found a solution that seems to hold in general.

If we take a collection of unit vectors in UV space and map them into 3D, they will form an ellipse, whose major and minor axes correspond to the stretch factors we want.

We don't care about the absolute orientation of these vectors after transformation, just how their length changes, according to the equation of an ellipse centered at the origin:

```
A * u*u + B * u*v + C * v*v = l*l

```

So first we need to find the parameters A, B, and C. (I'll rename the vertices to V1, V2, V3 so they don't conflict with the conventional labeling of these coefficients)

Consider the set of edges of the triangle (in both 3D and uv space):

```
E1 = V1 - V3
E2 = V2 - V1
E3 = V3 - V2

```

We can construct a system of equations to find the parameters as follows:

$$ \begin{bmatrix} E1.u * E1.u & E1.u * E1.v & E1.v * E1.v \\ E2.u * E2.u & E2.u * E2.v & E2.v * E2.v \\ E3.u * E3.u & E3.u * E3.v & E3.v * E3.v \\ \end{bmatrix} \begin{bmatrix} A \\ B \\ C \\ \end{bmatrix}= \begin{bmatrix} E1.xyz\cdot E1.xyz \\ E2.xyz\cdot E2.xyz \\ E3.xyz\cdot E3.xyz \\ \end{bmatrix}$$

Note that by construction this is insensitive to the rotation of the triangle in 3D, which is a good start, and doesn't need any normalizations to get there unlike my previous solution.

If the determinant of the coefficient matrix is zero, then the UV triangle is degenerate (at least one of the scale factors is infinite), and needs special-case handling which I'll elide for now.

After solving this by your favourite method (I used Cramer's Rule for a crude test), we have two cases for finding the axis scale factors:

```
float p;
float q;

if(ApproximatelyEqual(A, C))
{
  // Ellipse is symmetrical across the line u=v.
  // (Either theta = PI/4, or B = 0 and scaling is uniform).
  p = A - 0.5f * B;
  q = A + 0.5f * B;
}
else
{
  // Ellipse is non-uniformly scaled and arbitrarily rotated.
  // (Or a rounding error makes it appear slightly so)
  // Find its angle:
  float theta = atan(B/(C - A))/2f;

  // cos squared
  float c = cos(theta);
  c *= c;

  // sin squared
  float s = 1f - c;

  float divisor = 1f/(c - s);

  p = (A * c - C * s) * divisor;
  q = (C * c - A * s) * divisor;
}

// Note that numerical errors can sometimes cause p & q to be slightly negative.
// This isn't meaningful, so clamp to a non-negative value before taking the root.
float scale1 = sqrt(pos(p));
float scale2 = sqrt(pos(q));

```

Although I didn't need it, this calculates the direction of non-uniform stretch too (theta). It does not directly detect reflection, but this can be added by checking the winding of the triangle in uv space.

---
Tags: mathematics, geometry, uv-mapping
---