# Question
Title: What common interface would be appropriate for these game object classes?
**Question**

A component based system's goal is to solve the problems that derives from inheritance: for example the fact that some parts of the code (that are called components) are reused by very different classes that, hypothetically, would lie in a very different branch of the inheritance tree.

That's a very nice concept, but I've found out that CBS is often hard to accomplish without using ugly hacks. Implementations of this system are often far from clean. But I don't want to discuss this any further.

My question is: how can I solve the same problems a CBS try to solve with a very clean interface? (possibly with examples, there are a lot of abstract talks about the "perfect" design already).

**Context**

Here's an example I was going for before realizing I was just reinventing inheritance again:

```
class Human {
public:
    Position position;
    Movement movement;
    Sprite   sprite;
    // other human specific components
};

class Zombie {
    Position position;
    Movement movement;
    Sprite   sprite;
    // other zombie specific components
};

```

After writing that I realized I needed an interface, otherwise I would have needed N containers for N different types of objects (or to use `boost::variant` to gather them all together). So I've thought of polymorphism (move what systems do in a CBS design into class specific functions):

```
class Entity {
public:
    virtual void on_event(Event) {} // not pure virtual on purpose
    virtual void on_update(World) {}
    virtual void on_draw(Window) {}
};

class Human : public Entity {
private:
    Position position;
    Movement movement;
    Sprite   sprite;
public:
    virtual void on_event(Event) { ... }
    virtual void on_update(World) { ... }
    virtual void on_draw(Window) { ... }
};

class Zombie : public Entity {
private:
    Position position;
    Movement movement;
    Sprite   sprite;
public:
    virtual void on_event(Event) { ... }
    virtual void on_update(World) { ... }
    virtual void on_draw(Window) { ... }
};

```

Which was nice, except for the fact that now the outside world would not even be able to know where a `Human` is positioned (it does not have access to its position member). That would be useful to track the player position for collision detection or if `on_update` the Zombie would want to track down its nearest human to move towards him.

So I added `const Position& get_position() const;` to both the `Zombie` and `Human` classes. And then I realized that both functionality were shared, so it should have gone to the common base class: `Entity`. Do you notice anything? Yes, with that methodology I would have a god `Entity` class full of common functionality (which is the thing I was trying to avoid in the first place).

**Meaning of "hacks" in the implementation I'm referring to**

I'm talking about the implementations that defines Entities as simple IDs to which components are dynamically attached. Their implementation can vary from C-stylish:

```
int last_id;
Position* positions[MAX_ENTITIES];
Movement* movements[MAX_ENTITIES];

```

Where `positions[i], movements[i], component[i], ...` make up the entity. Or to more C++-style:

```
int last_id;
std::map<int, Position> positions;
std::map<int, Movement> movements;

```

From which systems can detect if an entity/id can have attached components.

# Answer
First, I would hardly consider the practice of making entities IDs to which a component is attached a "hack," it is rather a conscious design decision that has pros and cons -- none of which are really relevant to your actual problem, though, so I won't comment further except to note that this goes towards Byte56's comment about the subjectivity of the term.

It seems to me that your problem is that you made too large of a leap between stages 1 and 2 of your example. You don't need go directly from unrelated `Player` and `Zombie` types to having them inherit a super-generic interface you will then use for *every type ever* in your game. You just need an interface that covers your immediate needs right now:

```
struct Character {
   const Position & GetPosition () const;

   // ....
};

struct Zombie : Character { /* ... */ };
struct Player : Character { /* ... */ };

```

This allows you to treat all objects in your game that act like humanoid characters -- which have a position in the world, probably have health and speed stats, et cetera -- in a uniform fashion, but doesn't force you to treat other objects (such as bullets, which probably don't need health) that way. Even though a bullet will have a position, it doesn't need to be a `Character` and you don't need to cram it into that inheritance hierarchy at all.

The interfaces a type implements should be based on how that type may be used, not how it actually functions. It's okay to have two different classes that each have a function to get a position that isn't the *same* function. Sometimes you need to use that data in two different ways (consider the circle-ellipse problem, which leverages a common-but-flawed example used to academically demonstrate inheritance). And if you ever need to use that data in the same way, that's when you can consider what to do based on your actual, practical needs at the time.

The principle at work here is that you should evolve your interfaces by making the *least functional* thing that could work. Expose only the data and types you need now, expose only the relationships you need now... *name things accordingly*.

This allows you to control the growth of dependency on the interface more easily, which is more manageable in the long run.
> 4 votes

# Answer
Inheritance is a perfectly valid thing to use where it makes sense and makes your code easier to use. Don't believe that components are just about removing inheritance; they're not. Also don't believe that you have a strong need to avoid inheritance in every case or that components means you shouldn't be using it.

For your design, consider using a virtual interface in `Entity` for optional components. Something like this:

```
class Entity {
public:
  virtual Position* getPosition() { return nullptr; }
  virtual Movement* getMovement() { return nullptr; }
  virtual Sprite* getSprite() { return nullptr; }
};

```

Now your individual game object types can optionally provide any of the known components they need and you can easily query whether a particular object has a component or not by checking if the corresponding getter returns `nullptr`.

```
class Item : public Entity {
  Position m_position;
  Sprite m_sprite;
public:
  virtual Position* getPosition() override { return &m_position; }
  // getMovement() is not overridden as we have no Movement component
  virtual Sprite* getSprite() override { return &m_sprite; }
};

```

If you want to have a system or container that keeps track of all instances of a particular component, you can do something like:

```
void PositionSystem::onAddEntity(Entity* entity) {
  Position* position = entity->getPosition();
  if (position != nullptr)
     registerPosition(entity, position);
}

```
> 1 votes

---
Tags: c++, architecture
---


title: 2D game with 3D collision?

text:
# Question
Title: 2D game with 3D collision?
How do they do this bounce? Looks awfully complicated in 2D.

# Answer
**For bounces...**

If a heightmap was used, then a surface normal would be calculated at each impact point, by sampling local heights.

Otherwise, there is vector-based 3D geometry behind the scenes (literally) that already contains normals information based on its individual surfaces.

Either way, surface normals are used to produce accurate bounce vectors.

**For no bounces...**

This is where you only want the object to roll lazily down the surface. A heightmap's information should be enough to allow this, and is easier than setting up a mesh. You'd still need to perform some sort of interpolation, though, to smooth the motion, since the heights exist at different intervals.
> 2 votes

# Answer
Store 3D collision data with your map, and perform the projectile simulation in 3D using that data.
> 4 votes

# Answer
Behind the scenes, the game works in a semi-3D world (it's most likely limited, e.g. it's just a plane with heights added on top; no complex things such as tunnels, platforms, etc.).

When rendering, this is transformed using a simple projection. For example, you could just use the following translation to get from a 3D world to a 2D screen representation:

```
fx(x, y, z) = x;
fy(x, y, z) = 0.5 * y + z;

```

In this example `x` would be the horizontal coordinate, `y` would be the coordinate facing to the back or the player and `z` would be the height above ground. By multiplying `y` you're essentially changing the camera's angel, while using an orthogonal projection (since there's no perspective correction/depth).

You could as well use the following transformations for `y`:

```
fy_birdseye(x, y, z) = y;
fy_side(x, y, z) = z;

```

Just remember that the game doesn't necessarily simulate a full 3D world. In fact it might be just 2D and such 3D collisions are resolved just in time using a minimal set of 3D calculations (i.e. only the direct Environment is built up with 3D primitives for collision).
> 1 votes

---
Tags: collision-detection, game-mechanics, physics
---


# Question
Title: android: How to apply pinch zoom and pan to 2D GLSurfaceView
I want to apply pinch zoom and panning effect on GLSurfaceView. It is Image editor, so It would not be 3D object. I tried to implement using these following links:
https://groups.google.com/forum/#!topic/android-developers/EVNRDNInVRU
Want to apply pinch and zoom to GLSurfaceView(3d Object) http://www.learnopengles.com/android-lesson-one-getting-started/

These all are links for 3D object rendering. I can not use ImageView as I need to work out with OpenGL so, had to implement it on GLSurfaceView.

Suggest me or any reference links are there for such implementation. \**I need it for 2D only.

I am able to do both now, but where I am getting problem is to set the pivot point while panning can any one help me to set the translation respective to pivot point?

```
Matrix.setIdentityM(mScaleMatrix, 0);
        Matrix.scaleM(mScaleMatrix, 0, scaleX, scaleY, 0);
Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mScaleMatrix, 0);
Matrix.setIdentityM(mTranslateMatrix, 0);
        Matrix.translateM(mTranslateMatrix, 0, deltaX, deltaY, 0);
Matrix.multiplyMM(mProjectionMatrix, 0, mProjectionMatrix, 0,
                    mTranslateMatrix, 0);
Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0);

```

# Answer
> 1 votes
You don't have to scale your GLSurfaceView; instead you should adjust your projection matrix in order to achieve "zooming".

You are most likely using an orthographic projection for your 2D view, so have a look at this thread for a discussion on how to achieve zooming using `glOrtho()`.

---
Tags: 2d, android, opengl-es2
---


# Question
Title: Why does this exported cube have more vertices than I expected?
I'm trying to export `md5mesh` models. Just as a test I decided to export a simple cube (i.e. with 8 vertices). When I opened the `md5mesh` file it lists the following:

```
numverts 24
numtris 12
numweights 24

```

Obviously the number of triangles makes sense: 6 faces * 2 to triangulate = 12.

The model only has one bone so again it even makes sense that there is one weight for each vertex. The question is though, why is the file listing *24 vertices*?

Is the problem the exporter or is this normal for `md5mesh`'s? Is it something that you have to rectify when you come to parsing the file in engine? I don't want to be parsing or drawing duplicated vertices without reason.

I'm guessing it's something to do with shading and normals. Is it a case of listing each vert 3 times, one for each facing normal?

# Answer
If I remember correctly, it's pretty common for 3D packages to create duplicate vertices when exporting. 3D Studio Max definitely did this the last time I looked at it.

I know this can happen when a vertex has more than one set of texture coordinates, which can happen depending on how you texture mapped the cube. I think you can minimise this depending on how you unwrap for texturing.

Ultimately though, unless your model is extremely complicated and there are a massive number of duplicated vertices, I wouldn't worry about it too much.
> 1 votes

# Answer
As Bryan mentioned, it's because the cube is stored as 4 distinct quads. 6 faces * 4 verts/quad = 24 verts.

Figuring out where you can save a vertex or two (by re-using vertices and having an index buffer) may not be worth doing for many reasons.

1. Normals are often different
2. Texcoords are almost certainly different
3. Forcing use of index buffers by the rendering engine isn't always a good idea

So, having a policy of *always* replicating vertices here (ie storing separate tris and never using index buffers) appears to be what they have done here. IB's work great for things like terrain, or environments, but it seems it was decided that they would not be used for MD5 models. It's just an approach and seems to be what worked for them in this particular file format.
> 1 votes

---
Tags: md5mesh
---


title: Nice function for "rolling score up"?

text:
# Question
Title: Nice function for "rolling score up"?
I'm adding to the player's score, and I'm using a per-frame formula like:

```
int score, displayedScore ;// score is ACTUAL score player has,
// displayedScore is what is shown this frame to the player
// (the creeping/"rolling" number)

float disparity = score - displayedScore ;
int d = disparity * .1f ; // add 1/10 of the difference,
if( !d )  d = signum( disparity ) ; // last 10 go by 1's
score += d ;

```

Where

```
inline int signum( float val ){
  if( val > 0 )  return 1 ;
  else if( val < 0 )  return -1 ;
  else return 0 ;
}

```

So, it kind of works where it makes big changes rapidly, then it creeps in the last few one at a time.

But I'm looking for better (or possibly well known?) score-creeping functions. Any one?

# Answer
Tweens work great for this, and any tween library would have what you need.

The function below is what I've used before in a couple of games. It scrolls very quickly at first and then slows down a bit near the end, reminiscent of slot machines.

```
void addToScore( float val ) {
    score += val;

    //  Stop the current tween, in case one is still running.
    TweenLib.stop();

    //  Tween displayedScore to the value of score over the period
    //  of one second with a cubic easing function.
    TweenLib.tween( displayedScore, score, 1.0, Cubic.EaseOut);
}

```
> 6 votes

---
Tags: scoring
---


# Question
Title: How to display a GUI text at run time in unity?
I'd like to display a GUI text at run time in my game for a second, so I want to know if it's possible to add or remove a GUI label to the scene at run time?

# Answer
> 1 votes
* start a coroutine, which first waits for 1 second, and then set a boolean member variable to true (which initially is false)
* in OnGUI =\> if the bool is true show the Label

# Answer
> 2 votes
Is this what you mean?

```
void OnGUI() {
    GUI.Label(new Rect(10f, 10f, 100f, 50f), "YourText");
}

```

Or, in UnityScript (basically the same):

```
function OnGUI() {
    GUI.Label(new Rect(10f, 10f, 100f, 50f), "YourText");
}

```

---
Tags: unity, unityscript
---


# Question
Title: Timing Calculations for Opengl ES 2.0 draw calls
I am drawing a cube in OpenGL ES 2.0 in Linux. I am calculating the time taken for each frame using below function

```
#define NANO 1000000000

#define NANO_TO_MICRO(x) ((x)/1000)

uint64_t getTick()
{
  struct timespec stCT;
  clock_gettime(CLOCK_MONOTONIC, &stCT);
  uint64_t iCurrTimeNano = (1000000000 * stCT.tv_sec + stCT.tv_nsec); // in Nano Secs
  uint64_t iCurrTimeMicro = NANO_TO_MICRO(iCurrTimeNano); // in Micro Secs

  return iCurrTimeMicro;
}

```

I am running my code for 100 frames with simple x-axis rotation. I am getting around 200 to 220 microsecs per frame.

that means am i getting around (1/220microsec = 4545) FPS Is my GPU is that fast? I strongly doubt this result.

what went wrong in the code?

# Answer
Are you calling `glFinish()` after each render pass? That call makes sure that the GPU has actually finished working. OpenGL calls submit the data/command to the GPU and return.

Otherwise, depending on the particulars of your rendering code and the GPU you have, you may get to those figures. Use `glxgears` and see if the values it reports are around your FPS.
> 1 votes

---
Tags: performance, opengl-es2, linux, timing
---


title: GLSL billboard move center of rotation

text:
# Question
Title: GLSL billboard move center of rotation
I have successfully set up a billboard shader that works, it can take in a quad and rotate it so it always points toward the screen. I am using this vertex-shader:

```
void main(){
vec4 tmpPos = (MVP * bufferMatrix * vec4(0.0, 0.0, 0.0, 1.0)) + (MV * vec4(
    vertexPosition.x * 1.0 * bufferMatrix[0][0],
    vertexPosition.y * 1.0 * bufferMatrix[1][1],
    vertexPosition.z * 1.0 * bufferMatrix[2][2],
    0.0)
);

UV = UVOffset + vertexUV * UVScale;
gl_Position = tmpPos;

```

BufferMatrix is the model-matrix, it is an attribute to support Instance-drawing.

The problem is best explained through pictures:

This is the start position of the camera:

And this is the position, looking in from 45 degree to the right:

Obviously, as each character is it's own quad, the shader rotates each one around their own center towards the camera. What I in fact want is for them to rotate around a shared center, how would I do this?

What I have been trying to do this far is:

```
 mat4 translation = mat4(1.0);
    translation = glm::translate(translation, vec3(pos)*1.f * 2.f);
    translation = glm::scale(translation, vec3(scale, 1.f));
    translation = glm::translate(translation, vec3(anchorPoint - pos) / vec3(scale, 1.f));

```

Where the translation is the bufferMatrix sent to the shader. What I am trying to do is offset the center, but this might not be possible with a single matrix..?

I am interested in a solution that doesn't require CPU calculations each frame, but rather set it up once and then let the shader do the billboard rotation. I realize there's many different solutions, like merging all the quads together, but I would first like to know if the approach with offsetting the center is possible.

If it all seems a bit confusing, it's because I'm a little confused myself.

# Answer
I hacked a few lines together and I believe this might get you what I think you want. Basically it all depends on where/when you do the local transformation. You will want to translate the quads to their respective position in clip coordinates, e.g. after the multiplication with the mvp matrix.

```
vec4 tmpPos = mvp * vec4(0.0, 0.0, 0.0, 1.0) + vec4((local_transform * vec4(vPosition,1.0)).xyz,0.0);

```

Where the local\_transform matrix denotes the gl\_InstanceID dependent location of each Quad relative to the rotational center (basically like your bufferMatrix I guess). The rotational center itself would be wherever the model matrix within the mvp matrix would translate the zero vector.

This is what I get with my test application:

On a side note, I got your result with the following line of code:

```
vec4 tmpPos = mvp * local_transform * vec4(0.0, 0.0, 0.0, 1.0) + vec4(vPosition,0.0);

```

And again the result I get in my test:

Edit: Fixed two small mistakes. I mixed up clip coordinates with image space, and also carelessly added a 1.0 to the w-component in said clip coords. in my code above. I have corrected both now.
> 3 votes

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


# Question
Title: Visitor-pattern vs inheritance for rendering
I have a game engine that currently uses inheritance to provide a generic interface to do rendering:

```
class renderable
{
public:
    void render();
};

```

Each class calls the `gl_*` functions itself, this makes the code hard to optimize and hard to implement something like setting the quality of rendering:

```
class sphere : public renderable
{
public:
    void render()
    {
        glDrawElements(...);
    }
};

```

I was thinking about implementing a system where I would create a `Renderer` class that would render my objects:

```
class sphere
{
    void render( renderer* r )
    {
        r->renderme( *this );
    }
};

class renderer
{
    renderme( sphere& sphere )
    {
         // magically get render resources here
         // magically render a sphere here
    }
};

```

My main problem is where should I store the VBOs and where should I Create them when using this method? Should I even use this approach or stick to the current one, perhaps something else?

PS: I already asked this question on SO but got no proper answers.

# Answer
> 7 votes
You should have both, Inheritance and Visitor-Patter. This will be useful when you render all your objects like (c++11):

```
for( auto & prop: proplist ){
    prop->render( renderer );
}

```

The easy way is to store the VBO and other data in the object to be rendered, and the renderer will use this data to draw it.

```
class renderer {
    void renderme( sphere& sphere ){
        // magically get render resources here
        auto & vertexes = sphere->getVertexes();

        // magically render a sphere here
        glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vertexes );

        // ... etc
    }
};

```

E.g: The sphere has both, vertexes, normals and textures. But if the renderer is drawing in wire-frame, only will query the vertexes, but if it's also doing lighting it also will get the normals and textures from the sphere. Also, you can separate it into different renderers, wireframeRenderer and FullRenderer, and pass them as the visitor in different moments. And the Sphere code doesn't change.

# Answer
> 4 votes
My experience is that it's better to have a discrete renderer, and package the renderables as pure data for the most part (with the exception of data accessor methods).

This is for exactly the reasons you've described -- ultimately, rendering is a pipeline, from which each renderable benefits in different ways / at different points. So this way, you can structure the pipeline, and pass the data through that pipeline, with different part of the pipeline applying selectively to each renderable based on what it is.

Yes, the VBOs form part of each renderable object, and you probably want to maintain separate concepts of meshes, models and so on, so that you can copy new vertex data into that VBO on the fly, and the renderer simply picks up those changes and acts on them. It will become clear to you as you tackle it, notwithstanding a couple of conceptual hiccups; every engine is going to have subtly different architectural considerations based on what the engine in question is built to achieve.

# Answer
> 1 votes
Let's first check what is the problem with inheritance in your case:

1. **Introduces tight coupling between classes** making it harder to maintain and optimize.
2. Your use of inheritance doesn't obey Liskov\_substitution principle which states that types and their sub-types should be used interchangeably without altering any of the desirable properties of that program, **for example is sphere used the same as renderer?**

Second what is the visitor pattern when should it be used ?

> Is a way of separating an algorithm from an object structure on which it operates.

Sounds neat right? Well, not quite.. depending on your application you may or may not use it.

**I will use it if:**

* I have a complex structure (tree/graph) that I need to traverse and render and I need to separate the traverse from the actual rendering algorithm.
* I have multiple rendering algorithms and multiple renderable types I want to perform double dispatch.

**I won't use it if I have:**

* Simple structure that I can loop through.
* You only have one rendering algorithm per type for example billboards use an algorithm and 3d meshes use another algorithm.

**My recommendation is:**

* Use an ObjectRenderer that references the actual mesh (aggregation) and submits the actual rendering calls.
* The ObjectRenderer owns VBO so you can map a mesh or multiple meshes/sub-meshes (read:batching) for a single VBO.
* You can make the object ObjectRenderer polymorphic so each ObjectRenderer subtype can implement it's own algorithm ( e.g. BillboardRenderer, ParticlesRenderer, MeshRenderer).
* You can also make separate ObjectRenderer classes not subtype of a base type, and should be handled differently by the Renderer.

```
class ObjectRenderer
{
// or use a list of meshes
ObjectRenderer( Mesh* mesh );

private:
Material* material;
Mesh* mesh;
VBO* vbo;  // the object renderer owns the VBO
};

```

The object renderer is not a singleton, use one instance for a single mesh or group of meshes depending on the actual data. Create another class Renderer that stores a list of the actual ObjectRenderer(s) and can simply call the appropriate algorithm for each ObjectRenderer.

```
Renderer
{

void Render( )
{
  //for each Object call appropraite rendering algorithm.
}

std::vector<ObjectRenderer*> m_renderObjects; // one list in case of polymophic ObjectRenderer

// OR

 std::vector<ObjectRenderer*> m_renderObjects;
 std::vector<ParticlesRenderer*> m_particles;  // multiple list for different types so you can make the Renderer deal with different types differently. (e.g. sorting)
};

```

---
Tags: opengl, c++, architecture, rendering
---


# Question
Title: Making the player walk on walls in box2d
I'm making a game in stencil where players walk form left to right along randomly generated walls. I cant use waypoints, since the walls' shapes and positions are unpredictable.

Here's a descriptive sketch:

The red line is the player's path. The red circles are what I thought might make good waypoints until I scrapped the idea.

# Answer
Depending on what you actually wish to do , either 1) Change the gravitation upon colision with a wall, so it faces "into" the wall.

2) Add high friction for walls, equal 1 to the body fixture. It allows sticking to walls.
> 1 votes

# Answer
You can make a raycast from your character into all all four directions. If you only hit the ground then you don't have to do anything. If you hit a wall or the ceiling you add a weld joint to your character and the wall. You destroy and recreate the joint inside your update loop, so the character can move, but is tied to the wall/ceiling and doesn't fall down. There are still two tricky parts left.

1. Corners: When you come to a corner (two ray casts hit a wall) you must switch the wall on which you create the joint, depending on the direction you are walking to.
2. Walking direction: When you walk around a corner, you must track the direction you are walking to, so you can press forward all the time and follow the shape of the wall.
> 0 votes

---
Tags: box2d, actionscript-3, path-finding, stencyl
---


title: Sprite rotation

text:
# Question
Title: Sprite rotation
I'm using OpenGL and people suggest using glRotate for sprite rotation, but I find that strange. My problem with it is that it rotates the whole matrix, which sort of screws up all my collision detection and so on and so forth. Imagine I had a sprite at position (100, 100) and in position (100, 200) is an obstacle and the sprite's facing it. I rotate the sprite away from the obstacle and when move upwards my y axis, even though the projection shows like it's going away from the obstacle, the sprite will intersect it. So I don't see another way of a rotating a sprite and not screwing up all collision detection other than doing mathematical operations on the image itself. Am I right or am I missing something?

# Answer
> 3 votes
It sounds like you're just getting the order of your matrix operations wrong. Assuming you have a circular collision volume you just want to make sure you rotate your sprite on it's centre axis. To do that you have to first have your sprite centred in the screen either by translating it to the centre or drawing it about the centre. Then you rotate it before you translate it to it's current location.

The only trick is that in opengl does operations in column-major order, which means you apply them in reverse order in code.

so it would be:

```
glPushMatrix();
glTranslatef(...); // lastly translating
glRotatef(...); // second you would rotate
glScalef(...); // if you had a scaling you would apply that first
// sprite drawn about centre
glPopMatrix();

```

This is just a quick stab, if you're using per pixel collision then it's a whole other problem.

---
Tags: opengl, sprites, rotation, lwjgl
---


# Question
Title: An issue with tessellation a model with DirectX11
I took the hardware tessellation tutorial from Rastertek and implemended texturing instead of color. This is great, so I wanted to implemended the same techique to a model inside my game editor and I noticed it doesn't draw anything. I compared the detailed tessellation from DirectX SDK sample. Inside the shader file - if I replace the HullInputType with PixelInputType it draws. So, I think because when I compiled the shaders inside the program it compiles VertexShader, PixelShader, HullShader then DomainShader. Isn't it suppose to be VertexShader, HullSHader, DomainShader then PixelShader or does it really not matter?

I am just curious why wouldn't the model even be drawn when HullInputType but renders fine with PixelInputType.

Shader Code:

```
cbuffer ConstantBuffer {
    float4x4 WVP;
    float4x4 World;       // the rotation matrix
    float3 lightvec;      // the light's vector
    float4 lightcol;      // the light's color
    float4 ambientcol;    // the ambient light's color
    bool isSelected;
}

cbuffer cameraBuffer {
    float3 cameraDirection;
    float padding;
}

cbuffer TessellationBuffer {
    float tessellationAmount;
    float3 padding2;
}

struct ConstantOutputType {
    float edges[3] : SV_TessFactor;
    float inside : SV_InsideTessFactor;
};

Texture2D Texture;
Texture2D NormalTexture;

SamplerState ss {
    MinLOD = 5.0f;
    MipLODBias = 0.0f;
};

struct HullOutputType {
    float3 position : POSITION;
    float2 texcoord : TEXCOORD0;
    float3 normal : NORMAL;
    float3 tangent : TANGENT;
};

struct HullInputType {
    float4 position : POSITION;
    float2 texcoord : TEXCOORD0;
    float3 normal : NORMAL;
    float3 tangent : TANGENT;
};

struct VertexInputType {
    float4 position : POSITION;
    float2 texcoord : TEXCOORD;
    float3 normal : NORMAL;
    float3 tangent : TANGENT;
    uint uVertexID : SV_VERTEXID;
};

struct PixelInputType {
    float4 position : SV_POSITION;
    float2 texcoord : TEXCOORD0;    // texture coordinates
    float3 normal : NORMAL;
    float3 tangent : TANGENT;
    float4 color : COLOR;
    float3 viewDirection : TEXCOORD1;
    float4 depthBuffer : TEXTURE0;
};

HullInputType VShader(VertexInputType input)
{
    HullInputType output;

    output.position.w = 1.0f;

    output.position = mul(input.position,WVP);
    output.texcoord = input.texcoord;
    output.normal = input.normal;
    output.tangent = input.tangent;

    //output.normal = mul(normal,World);
    //output.tangent = mul(tangent,World);

    //output.color = output.color;
    //output.texcoord = texcoord;    // set the texture coordinates, unmodified

    return output;
}

ConstantOutputType TexturePatchConstantFunction(InputPatch<HullInputType,3> inputPatch,uint patchID : SV_PrimitiveID)
{
    ConstantOutputType output;

    output.edges[0] = tessellationAmount;
    output.edges[1] = tessellationAmount;
    output.edges[2] = tessellationAmount;

    output.inside = tessellationAmount;

    return output;
}

[domain("tri")]
[partitioning("integer")]
[outputtopology("triangle_cw")]
[outputcontrolpoints(3)]
[patchconstantfunc("TexturePatchConstantFunction")]

HullOutputType HShader(InputPatch<HullInputType, 3> patch, uint pointId : SV_OutputControlPointID, uint patchId : SV_PrimitiveID)
{
    HullOutputType output;

    // Set the position for this control point as the output position.
    output.position = patch[pointId].position;

    // Set the input color as the output color.
    output.texcoord = patch[pointId].texcoord;

    output.normal = patch[pointId].normal;
    output.tangent = patch[pointId].tangent;

    return output;
}

[domain("tri")]

PixelInputType DShader(ConstantOutputType input, float3 uvwCoord : SV_DomainLocation, const OutputPatch<HullOutputType, 3> patch)
{
    float3 vertexPosition;
    float2 uvPosition;
    float4 worldposition;
    PixelInputType output;

    // Interpolate world space position with barycentric coordinates
    float3 vWorldPos = uvwCoord.x * patch[0].position +
                       uvwCoord.y * patch[1].position +
                       uvwCoord.z * patch[2].position;

    // Determine the position of the new vertex.

    vertexPosition = vWorldPos;

    // Calculate the position of the new vertex against the world, view, and projection matrices.

    output.position = mul(float4(vertexPosition, 1.0f),WVP);

    // Send the input color into the pixel shader.

     output.texcoord = uvwCoord.x * patch[0].position +
                    uvwCoord.y * patch[1].position +
                     uvwCoord.z * patch[2].position;

    output.normal = uvwCoord.x * patch[0].position +
                    uvwCoord.y * patch[1].position +
                    uvwCoord.z * patch[2].position;

    output.tangent = uvwCoord.x * patch[0].position +
                    uvwCoord.y * patch[1].position +
                    uvwCoord.z * patch[2].position;

    //output.depthBuffer = output.position;
    //output.depthBuffer.w = 1.0f;

    //worldposition = mul(output.position,WVP);
    //output.viewDirection = cameraDirection.xyz - worldposition.xyz;
    //output.viewDirection = normalize(output.viewDirection);

    return output;
}

```

Somethings are commented out but will be in place when fixed. I'm probably not connecting something correctly.

# Answer
> 1 votes
Your `HullInputType` structure doesn't include a binding for `SV_Position`. It only includes one for `POSITION`, which isn't a built-in semantic anymore in D3D11. Vertex shaders must write something to `SV_Position` to tell the system where the vertex is.

BTW, the D3D11 debug layer would have given you a warning message about this. You can activate it by passing the `D3D11_CREATE_DEVICE_DEBUG` flag when creating your device. Then error and warning messages will come out in the Visual Studio debug window. There's more stuff you can do with the debug layer described in this blog post.

---
Tags: directx11
---


# Question
Title: Are buffers in OpenGL associated with GLSL programs?
I have two different shader programs in my OpenGL code.

1- renders simple font using freetype
2- simple shader which draw primitive shapes.

I sent both of them some data using buffers, I understood that they are stored on server side, but are they associated with different programs? or any program can use any buffer data by just using gBindBuffer(); ?

# Answer
> 2 votes
Short answer: No they aren't asscoiated with shader programs.

Long answer : Vertex and vertex attributes are stored in buffers which may or may not be located on the GPU memory depending on how you define them and how the driver decides to.

glBindBuffer binds a specific buffer object (referenced by uint) to a specific binding point like GL\_ARRAY\_BUFFER, think of this as how openGL are going to deal with this buffer.

GLSL shader programs take vertices and vertex attributes as input. These attibutes are not passed to the active shader program unless you do the following:

1. Bind the buffer that contains the data. (Assuming they are already stored in the buffer).
2. Query the location of each shader program attribute varialbe so you can bind Attribute Pointer to them in the next step (or just use a predefined locations).
3. Decide how are you going to deference the buffer data using glVertexAttribPointer and where each AttributePointer will be bound using the queried names(uint) from step 2.
4. Perform the actual draw operation.

# Answer
> 0 votes
The latter. You can bind a buffer to a slot. Programs then use these slots as input. They have no direct connection to the buffer itself, but rather to the slot that a particular buffer may be bound to. You can change shaders without changing buffer bindings and you can change buffer bindings without changing shaders.

---
Tags: opengl, shaders, vertex-buffer
---


# Question
Title: Movement of body after applying weld joint
I have two rectangular bodies. I've applied `Weldjoint` successfully on these bodies. I want to move that joined body by applying linear impulse. After weld joint, these two bodies becomes single body right? How do I apply force/impulse on the joined body?

I am using Box2D with LibGDX.

I've tried this:

```
polygon1.applyLinearImpulse(new Vector2(-5, 0), polygon1.getWorldCenter(), true);

```

I thought that if I move `polygon1` then `polygon2` will also move due to my weld joint but it is not working properly.

Why don't they move together after being welded?

below is my code.

```
package com.test.box2d;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.ChainShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.physics.box2d.joints.WeldJointDef;

public class WeldJointTest extends Game{

    World world;
    Box2DDebugRenderer debugRenderer;
    OrthographicCamera camera;
    Body polygon1, polygon2;

    @Override
    public void create() {

        world = new World(new Vector2(0, -10), true);
        debugRenderer = new Box2DDebugRenderer();
        camera = new OrthographicCamera(Gdx.graphics.getWidth() / 10, Gdx.graphics.getHeight() / 10);

        //body def
        BodyDef bodyDef = new BodyDef();
        bodyDef.type = BodyType.DynamicBody;
        bodyDef.position.set(-20, -8f);

        //shape
        PolygonShape polygonShape = new PolygonShape();
        polygonShape.setAsBox(2, 2);

        //fixture def
        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.density = 1;
        fixtureDef.restitution = .2f;
        fixtureDef.friction = .3f;
        fixtureDef.shape = polygonShape;

        polygon1 = world.createBody(bodyDef);
        polygon1.createFixture(fixtureDef);

        // body def
        bodyDef.position.set(-16, -8f);

        polygon2 = world.createBody(bodyDef);
        polygon2.createFixture(fixtureDef);

        //floor body def
        bodyDef.type = BodyType.StaticBody;
        bodyDef.position.set(-40, -50);

        // floor shape
        ChainShape chainShape = new ChainShape();
        chainShape.createChain(new Vector2[]{new Vector2(-100, 40), new Vector2(100, 40)});

        //fixture def
        fixtureDef.shape = chainShape;

        world.createBody(bodyDef).createFixture(fixtureDef);

        WeldJointDef weldJointDef = new WeldJointDef();
        weldJointDef.bodyA = polygon1;
        weldJointDef.bodyB = polygon2;
        weldJointDef.localAnchorA.set(new Vector2(4, 0));
//      weldJointDef.localAnchorB.set(polygon2.getWorldCenter());

        world.createJoint(weldJointDef);
        /*DistanceJointDef distanceJointDef = new DistanceJointDef();
        distanceJointDef.bodyA = polygon1;
        distanceJointDef.bodyB = polygon2;
        distanceJointDef.length = 25;

        world.createJoint(distanceJointDef);*/

        chainShape.dispose();
        polygonShape.dispose();
    }

    @Override
    public void render() {

        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

        debugRenderer.render(world, camera.combined);
        world.step(1/60f, 8, 3);

        Gdx.input.setInputProcessor(new InputProcessor() {

            @Override
            public boolean keyDown(int keycode) {

                switch (keycode) {
                case Keys.LEFT:
                    polygon1.applyLinearImpulse(new Vector2(-5, 0), polygon1.getWorldCenter(), true);
                    break;

                default:
                    break;
                }

                return true;
            }

            @Override
            public boolean touchUp(int screenX, int screenY, int pointer, int button) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean touchDragged(int screenX, int screenY, int pointer) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean touchDown(int screenX, int screenY, int pointer, int button) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean scrolled(int amount) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean mouseMoved(int screenX, int screenY) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean keyUp(int keycode) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean keyTyped(char character) {
                // TODO Auto-generated method stub
                return false;
            }

        });

    }

}

```

from main method.

```
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
        cfg.title = "Body Movement Test";
        cfg.useGL20 = false;
        cfg.width = 800;
        cfg.height = 480;

```

# Answer
> 2 votes
I think I've managed to reproduce your problem - basically your friction is too high/your impulse not enough.

Change your impulse from (-5, 0) to something like (-50, 0), and/or lower your friction coefficient. Seems to work...

Also, on a side note, I wouldn't recommend instantiating and setting your InputProcessor every frame - do it once in your create() method (unless you have reason).

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


# Question
Title: How can I plot points and generate a list of coordinates?
Is there a program that lets me draw, a la pixel art, a map, and give me a list of coordinates and their corresponding colors? For example, I'd like to use a point and click interface to draw this

and then "export" this somehow.

# Answer
> 2 votes
You can write a script or simple program by loading up the image (using PyImage or SDL or the like), loop over all pixels in the image, and print out those which are black (or any other color requested).

Something like this pseudo-code:

```
main(path, color):
 image = LoadImage(path)
 for y in 0 to image.height:
   for x in 0 to image.width:
     if image.GetPixelAt(x, y) == color:
       print x, y

```

---
Tags: game-design, graphics, coordinates
---


# Question
Title: Problem when scaling game screen in Libgdx
Currently, I'm able to scale the screen by applying this bit of code onto an OrthographicCamera

```
Camera.setToOrtho(true, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);

```

But something quite strange is happening with this solution, take a look at this picture of my game below

Seems fine right? But upon further investigation, many components are rendered off by one pixels, and the tiles all are.

Take a closer look

I circled a couple of the errors. Note that the shadow of the warrior I circled appears fine for the other warriors. Also keep in mind that everything is rendered at pixel-perfect precision when I disable the scaling.

I actually thought of a possible source for the problem as I'm writing this but I decided to still post this because I would assume somebody else might run into the same issue.

# Answer
> 7 votes
It turns out my initial suspicions were right. The SpriteBatch draw method takes floats for the X and Y, so I decided to feed it my positions as is, kept as floats. WRONG. It seems that the SpriteBatch class can't round properly or something because when I cast all of the values to integers and then gave it that, everything turned back to normal and is rendering like it should.

---
Tags: java, libgdx
---


title: Updating the jump in game

text:
# Question
Title: Updating the jump in game
I am making a Java game and I want my game to run the same on any FPS so I'm using time delta between each update. This is the update method of the Player:

```
    public void update(long timeDelta) {

        //speed is the movement speed of a player on X axis
        //timeDelta is expressed in nano seconds so I'm dividing it with 1000000000 to express it in seconds

        if (Input.keyDown(37))
            this.velocityX -= speed * (timeDelta / 1000000000.0);

        if (Input.keyDown(39))
            this.velocityX += speed * (timeDelta / 1000000000.0);

        if(Input.keyPressed(38)) {
            this.velocityY -= 6;
        }

        velocityY += g * (timeDelta/1000000000.0); //applying gravity
        move(velocityX, velocityY); /*this is method which moves a player
                                        according to velocityX and velocityY,
                                        and checking the collision
                                    */

        this.velocityX = 0.0;
    }

```

The strange thing is that when I have unlimited FPS (and update number) my player is jumping about 10 blocks. It jumps even higher when the FPS is increasing. If I limit FPS it is jumping 4 blocks. (BLOCK: 32x32) I have just realized that the problem is this:

```
if(Input.keyPressed(38)) {
    this.velocityY -= 6;
}

```

I add -6 to velocityY which increases player's Y proportionally to the update number and not to the time.

But I don't know how to fix this.

# Answer
> 1 votes
You should add a jumpAcceleration. When the player press key(38) you should do

```
this.velocityY -= jumpAcceleration * dt;

```

where dt is timeDelta / 1000000000.0 .
What you do in your code is, you add 6 to the velocityY at every update. So at high FPS (e.x. 300 ) you will subtract 6 * 300 = 1800 from your velocityY, but at a low FPS (e.x. 10 ) you will subtract 60 from your velocityY, at every second. If you want to make your game independent of the FPS you have to add timeDelta there too.
Also search at google for game loops. There is information on how to create a solid and FPS independent game loop for your game.

# Answer
> 0 votes
Simple solution: Only add the jumping speed if you're actually on the ground and/or standing still.

Something like this:

```
if (Input.keyPressed(38) && onGround)
    this.velocityY -= 6;

```

The actual check could be more complicated. For example rather than using a boolean value you could use some counter `canJump` that is by default set to 1 or 2 whenever you're on solid ground. If you try to jump (key pushed down; not just held down!) and the counter is bigger than 0 you apply the velocity and reduce the counter. This way it's rather easy to implement things like double jumps or even triple jumps.

---
Tags: java, platformer, frame-rate, jumping, timestep
---


title: How to make Pokémon White 3D effect?

text:
# Question
Title: How to make Pokémon White 3D effect?
I just wondered how to create a 3D effect similar to Pokemon White/Black? It seems to be not polygon based, but created just with sprites. If the perspective changes the sprites stay sharp and don't get blurred. How can I archive this?

Source: https://www.youtube.com/watch?v=fZEPUPYOnRc&feature=youtube\_gdata\_player

Edit: Wow, two downvotes because I used a video instead of screenshots? Don't get me wrong, I thank you, because you want to help me, but the 3D effect can be better understood in motion. Anyway, here is a screenshot: http://wearearcade.com/wp-content/uploads/2011/03/pokemon-black-white-starter-town.jpg

So, if this is a hardware limitation, how can I archive this o na different hardware, e.g. a HTML5 game? Thank you.

# Answer
> 4 votes
The surrounding is definitely polygon-based. You can tell by the way the perspective of the buildings changes when the player walks through the town. The polygon-count seems to be really low, but it works because the whole look of the game is quite retro. The fixed view-angle also allows them to put most of the geometric detail into the textures, because they only need to look good when viewed from a single direction.

The characters seem to be billboards (polygons which always face the viewer) inserted into the 3d scene. This, too, only works well because the perspective doesn't change much. When the surrounding would be able to rotate fluently but the sprites in it could not, they would immediately start to stand out.

The video quality is too bad to tell how the sprites filter when they zoom. But one way to prevent sprites from blurring too much on zooming in is to use nearest-neighbor interpolation which causes a "pixely" retro-look on close-ups. To prevent them from losing detail when zooming out is to draw them in a much lower resolution than they appear on the screen. This makes sure no pixel gets "swallowed" when zooming out.

To answer your question about how to do this in a HTML5 game: I would recommend you to take a look at WebGL. When 3d programming math (like matrix multiplication) is too complex for you to grasp, there are also various libraries and frameworks like Three.js available to make using WebGL easier.

---
Tags: 3d
---


title: Non OnGUI based progress bar

text:
# Question
Title: Non OnGUI based progress bar
How can I make a progress bar appear in Unity that doesn't make use of the OnGUI functionality in C#?

I'm doing something with an Oculus and the OnGUI stuff doesn't work too well in a stereoscopic setting. I'm open to hear suggestions or try code samples as I can't seem to think of a way to display this in Unity and every google search brings up OnGUI examples.

# Answer
> 1 votes
I think all the normal Unity answers (nGUI, etc.) aren't going to help you. I'm looking into VR stuff now, and standard 2D techniques just don't work well. Ideally you want to put your UI into the world, but adjust its position based on the camera.

Simplest answer I can suggest is to create a simple cuboid Mesh object, parented underneath your OVRCameraController (so it's essentially locked to your head) and positioned such that it's always visible in front of your viewpoint. Then animate its transform over time (e.g. scale it from 0.0 to 1.0 along one axis to make it appear as if it were growing.

Actually, given the lack of frame of reference, a standard progress bar might not be so good. Maybe try a cube which scales down to 0,0,0 (i.e. shrinks and disappears when the progress bar is done). Or maybe have two cuboids, one transparent and sized at 100%, the other sized at 0% and scaling up. When the two cuboids are the same size the progress bar is done.

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


# Question
Title: Improving the efficiency of my bloom/glow shader
I'm making a neon style game where everything is glowing but the glow I have is kinda small and I want to know if there's an efficient way to increase the size of it other than increasing the pixel sample iterations.

Right now I have something like this:

```
float4 glowColor = tex2D(glowSampler, uvPixel);

//Makes the inital lines brighter/closer to white
if (glowColor.r != 0 || glowColor.g != 0 || glowColor.b != 0)
{
    glowColor += 0.5;
}

//Loops over the weights and offsets and samples from the pixels based on those numbers
for (int i = 0; i < 20; i++)
{
    glowColor += tex2D(glowSampler, uvPixel + glowOffsets[i] + 0.0018) * glowWeights[i];
}

finalColor += glowColor;

```

for the offsets it moves up, down, left and right (5 times each so it loops over 20 times) and the weights just lower the glow amount the further away it gets.

The method I was using before to increase it was to increase the number of iterations from 20 to 40 and to increase the size of the offset/weight array but my computer started to have FPS drops when I was doing this so I was wondering how can I make the glow bigger/more vibrant without making it so CPU/Gcard intensive?

# Answer
> 5 votes
There are two common approaches, both of which can be used together or independently. The first assumes you have some kind of "bright pass" that renders the "glow" texture. Because blurring inherently produces low-frequency results, you should be able to reduce the resolution of this pass, so the same number of samples cover a larger fraction of the screen area.

The second approach is to take advantage of the fact that blur is typically separable. You can therefore use a two-pass approach, blurring in only one direction in the first pass (e.g. horizontal), then in another in the second pass (vertical). This reduces the total number of samples from N^2 to 2N, though there is some overhead for multi-pass in general.

There is a third approach, but it does not seem like it would work for your case (since it looks like you're doing colored blurs). This option involves using the Gather method to get 4 samples from one call, reducing the total number of samples required by a factor of 4. This only works for single-channel color, however.

# Answer
> 1 votes
> ```
> if (glowColor.r != 0 || glowColor.g != 0 || glowColor.b != 0)
> {
>     glowColor += 0.5;
> }
>
> ```

could be written as

```
>  if (any(glowColor.rgb))
>  {
>      glowColor += 0.5;
>  }

```

I did't try but this also could work:

```
glowColor += 0.5 * sign(any(glowColor.rgb));

```

---
Tags: xna, shaders, bloom
---


title: HLSL How to flip geometry horizontally

text:
# Question
Title: HLSL How to flip geometry horizontally
I want to flip my asymmetric 3d model horizontally in the vertex shader alongside an arbitrary plane parallel to the YZ plane. This should switch everything for the model from the left hand side to the right hand side (like flipping it in Photoshop). Doing it in pixel shader would be a huge computational cost (extra RT, more fullscreen samples...), so it must be done in the vertex shader. Once more: this is NOT reflection, i need to flip THE WHOLE MODEL.

I thought I could simply do the following:

1. Turn off culling.
2. Run the following code in the vertex shader:

```
input.Position = mul(input.Position, World);

// World[3][0] holds x value of the model's pivot in the World.
if (input.Position.x <= World[3][0])
    input.Position.x += World[3][0] - input.Position.x;
else
    input.Position.x -= input.Position.x - World[3][0];

...

```

The model is never drawn. Where am I wrong? I presume that messes up the index buffer. Can something be done about it?

P.S. it's INSANELY HARD to format code here.

Thanks to Panda I found my problem. SOLUTION:

```
// Do thins before anything else in the vertex shader.
Position.x *= -1;   // To invert alongside the object's YZ plane.

```

# Answer
why don't you use a transformation matrix and pass it into the shader? Flipping can be done with a negative scale value. But maybe misunderstood you, Iam not sure.
> 4 votes

---
Tags: shaders, hlsl, geometry, vertex-shader
---


# Question
Title: Do you need to make a tileset for a platformer?
I've been tasked to make a platformer, I've never made a tiled game before, is this necessary?

I.e. can I just make different child classes of a Sprite class and add place them on the map, adding their own functionality?

I'm using html5 canvas and JS if that makes a difference.

# Answer
No, platformers do not have to be tile based. You can do "free placement" of sprites as well. See these related questions to learn more:

Recommended method towards making custom maps for a 2d game?

How can I get textures on edge of walls like in Super Metroid and Aquaria?

I'll also add the link Seth shared because it's an excellent resource.
> 4 votes

---
Tags: game-design, tiles, html5, html-canvas
---


title: Physics for moving blocks

text:
# Question
Title: Physics for moving blocks
I'm working on a 2D game for windows phone where the player moves blocks around to bounce a laser beams.

I need to create some simple physics for moving the blocks.

For the moment I have a simple collision class, telling me if two rectangles collide. But that's not enough because when I'm moving a block the rectangle/rectangle function doesn't work.

By Doesn't work i mean,I manage the collision but I don't how to stop the block mooving while the user sliding the block.

The collision response for the block I want is if the user tries to slide it on another object, the block should slide up against the other object and not overlap.

How would I go about implementing this functionality?

Some code about how i impletement mooving block

```
{
            Currentposition = Station.Position;

            TouchPanelCapabilities touchCap = TouchPanel.GetCapabilities();
            if (touchCap.IsConnected)
            {
                TouchCollection touches = TouchPanel.GetState();
                if (touches.Count >= 1)
                {
                    Vector2 PositionTouch = touches[0].Position;
                    for (int i = 0; i < ListDragObj.Count(); i++)
                    {
                        if (ListDragObj[i].Shape.Contains((int)PositionTouch.X, (int)PositionTouch.Y))
                        {
                            ListDragObj[i].selected = true;
                        }
                        else
                        {
                            ListDragObj[i].selected = false;
                        }
                        ListDragObj[i].Update(PositionTouch);
                    }
                }
            }
        }

```

# Answer
> 2 votes
I think what you're really asking for is a scheme for the user to interact with the block that feels natural.

If you're just *setting* the position of the block to the position of the finger, you're going to run into some collision and placement issues. It sounds like you might want to try a Force- or Velocity-based approach.

For the Velocity-based approach, when the user 'grabs' a block, give it a velocity in the direction of the 'finger'. Create a deadzone around the block, and set a reasonable minimum and maximum velocity. This way, each frame you can advance the block and check for collisions. If there were collisions, you move the block back by the collision depth, and kill the velocity perpendicular to the collision surface. This will allow it to slide along walls and such, if your finger is inside of it. (It's not uncommon for people to make the mistake of setting the entire velocity to zero, not just the perpendicular component).

For a Force-based approach, rather than setting the velocity in the way I described, set a force on the object that way. This will generate acceleration. You're going to want some damping on the velocity (Friction. In other words, reduce your velocity by a velocity-dependent amount every frame (v \*= (1- c / deltaT )). You probably would want to kill the velocity more quickly when the finger is in the deadzone. This will give the blocks a more springly feel, and you can also play around with varying the friction dependent on the surface if that sort of thing is interesting or relevant to your game.

# Answer
> 0 votes
You need a so called sweep test. Check if the block before its movement is behind the target after its movement. You can use a plane for the in front/behind test, or make the movement in small steps, so you don't miss the target.

---
Tags: xna, c#, windows-phone-8
---


# Question
Title: How to give a ball a following texture trailing effect
How do I draw copies of the leading texture so that there is a line of the leading ball following behind it? (that don't collide)

So far I have tried to create the effect by placing another graphic 2 pixels off the graphic, but I don't see the second ball being drawn.

```
spriteBatch.Draw(ballTexture, ballPos, null, Color.White, 0.0f, new Vector2(Ballpos.X +2, ballPos.Y +2), ballSize, SpriteEffects.None, 0);

```

Thanks.

# Answer
> 0 votes
store the location of the ball last frame and draw that, or if that is too close store the location 5 frames ago

alternatively if you know the direction of the ball use

```
for(int i = 1; i<5; i++)
{
  var drawposition = ball.position - (i * ball.direction);
  var colour = Color.Lerp(Color.White,Color.Transparent,i*(20/100f));
  //SpriteBatch.Draw at drawposition with colour
}

```

where \_time is the time since last frame. although down side of this is that it will not map actual path accurately

just be sure the ball is not so close as to confuse it with the current ball

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


# Question
Title: First frame has a much longer delta time than other frames
I had a problem where my AI moved extreme at the first frame and then normal after that. I then figured out it was my delta. It's about 0.016 seconds (60 fps), but the first frame was about 19000 seconds, which is obviously impossible. Does anybody know what might be happening? Also the delta later on likes to oscillate from 0.01 to 0.03.

```
    long time = Sys.getTime() * 1000 / Sys.getTimerResolution();
    float delta = (time - lastFrame) / 1000f;
    lastFrame = time;
    return delta;

```

That's the delta code.

EDIT: Wow, you guys really like to take the fun out of composing a question with all your editing.

# Answer
The oscillation is a common thing. Likely from CPU scheduling and other processes on the system.

The first frame being very long is an error in your code. Consider what `lastFrame` is set to when the application starts (likely `0`), so for the first frame you're just setting `deltaTime` to the time/1000. You can add a check that if `lastFrame` is `0`, the `deltaTime` is also `0`. Or you can set it to a reasonable value (like the current time), when the application starts. Or you can delay anything that uses `deltaTime` by at least one frame, something like a delayed start.
> 6 votes

---
Tags: lwjgl, frame-rate
---


# Question
Title: Android Can't get two virtual joysticks to move independently and at the same time
```
   @Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub

        float r = 70;
        float centerLx = (float) (screenWidth*.3425);
        float centerLy = (float) (screenHeight*.4958);
        float centerRx = (float) (screenWidth*.6538);
        float centerRy = (float) (screenHeight*.4917);
        float dx = 0;
        float dy = 0;
        float theta;
        float c;

        int action = event.getAction();
        int actionCode = action & MotionEvent.ACTION_MASK;
        int pid = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
        int fingerid = event.getPointerId(pid);
        int x = (int) event.getX(pid);
        int y = (int) event.getY(pid);

            c = FloatMath.sqrt(dx*dx + dy*dy);
            theta = (float) Math.atan(Math.abs(dy/dx));

            switch (actionCode) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_POINTER_DOWN:

                //if touching down on left stick, set leftstick ID to this fingerid.
                if(x < screenWidth/2 && c<r*.8) {
                    lsId = fingerid;
                                    dx = x-centerLx;
                        dy = y-centerLy;
                    touchingLs = true;
                }
                else if(x > screenWidth/2 && c<r*.8) {
                    rsId = fingerid;
                                    dx = x-centerRx;
                                    dy = y-centerRy;
                    touchingRs = true;
                }

                    break;
            case MotionEvent.ACTION_MOVE:

            if (touchingLs && fingerid == lsId) {
                dx = x - centerLx;
                dy = y - centerLy;
            }else if (touchingRs && fingerid == rsId) {
                dx = x - centerRx;
                dy = y - centerRy;
            }

                c = FloatMath.sqrt(dx*dx + dy*dy);
                theta = (float) Math.atan(Math.abs(dy/dx));

                //if touching outside left radius and moving left stick
                if(c >= r && touchingLs && fingerid == lsId) {
                    if(dx>0 && dy<0) { //top right quadrant
                        lsX = r * FloatMath.cos(theta);
                        lsY = -(r * FloatMath.sin(theta));
                        Log.i("message", "top right");
                    }

                    if(dx<0 && dy<0) { //top left quadrant
                        lsX = -(r * FloatMath.cos(theta));
                        lsY = -(r * FloatMath.sin(theta));
                        Log.i("message", "top left");
                    }

                    if(dx<0 && dy>0) { //bottom left quadrant
                        lsX = -(r * FloatMath.cos(theta));
                        lsY = r * FloatMath.sin(theta);
                        Log.i("message", "bottom left");
                    }

                    else if(dx > 0 && dy > 0){ //bottom right quadrant
                        lsX = r * FloatMath.cos(theta);
                        lsY = r * FloatMath.sin(theta);
                        Log.i("message", "bottom right");
                    }

                }
                if(c >= r && touchingRs && fingerid == rsId) {
                    if(dx>0 && dy<0) { //top right quadrant
                        rsX = r * FloatMath.cos(theta);
                        rsY = -(r * FloatMath.sin(theta));
                        Log.i("message", "top right");
                    }
                    if(dx<0 && dy<0) { //top left quadrant
                        rsX = -(r * FloatMath.cos(theta));
                        rsY = -(r * FloatMath.sin(theta));
                        Log.i("message", "top left");
                    }
                    if(dx<0 && dy>0) { //bottom left quadrant
                        rsX = -(r * FloatMath.cos(theta));
                        rsY = r * FloatMath.sin(theta);
                        Log.i("message", "bottom left");
                    }
                    else if(dx > 0 && dy > 0) {
                        rsX = r * FloatMath.cos(theta);
                        rsY = r * FloatMath.sin(theta);
                        Log.i("message", "bottom right");
                    }
                }
                else {
                    if(c < r && touchingLs && fingerid == lsId) {
                        lsX = dx;
                        lsY = dy;
                    }
                    if(c < r && touchingRs && fingerid == rsId){
                        rsX = dx;
                        rsY = dy;
                    }

                }

                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:

            if (fingerid == lsId) {
                lsId = -1;
                lsX = 0;
                lsY = 0;
                touchingLs = false;
            } else if (fingerid == rsId) {
                rsId = -1;
                rsX = 0;
                rsY = 0;
                touchingRs = false;
            }

                break;
            }

        return true;
    }

```

There's a left joystick and a right joystick. Right now only one will move at a time. If someone could set me on the right track I would be incredibly grateful cause I've been having nightmares about this problem.

# Answer
> 1 votes
I can't find a direct problem with your code, but here are a few pointers on dealing with Android Multi-touch Input

* Make sure you **include the uses-feature in your AndroidManifest.xml for multitouch**. I am not sure if it is just a cautionary setting to disable your app on devices that don't support it, or if it actually does activate it on your app:

`<uses-feature android:name="android.hardware.touchscreen.multitouch" />`

* You should probably **handle the `ACTION_XXX` & `ACTION_POINTER_XXX` a bit differently from each other**. The first is given when the primary finger (first) finger touches the screen or last one leaves respectively. The second one is used whenever any extra (called `Non-Primary` by the SDK) finger touches down or up.
* Note that not all pointer touch downs would be reported. To overcome that, **whenever a `ACTION_MOVE` event would fire, first check if that `pointerID` is already existent**, if not, then create it as if it had just landed there
* Lastly, most device screens are VERY sensitive, to the point where there is motion reported, when the user would not even notice moving finger at all (or even intended to). To overcome this, **include a `Movement Threshold` at every movement event, and only consider the finger moved if it exceeds the threshold**

I hope these pointers at least give you a starting point on where to look further into solving your problem

---
Tags: android, joystick
---


title: Brief pause after keypress

text:
# Question
Title: Brief pause after keypress
After i press and hold the key it goes forward once then pauses for a second or less then goes forward on forever. My problem is the brief pause I cant locate the issue. Thanks for your help.

```
    while(game){
        while (SDL_PollEvent(&e)){
            mainChar.manageEvents(e);
        }
        background.renderChar();
        mainChar.renderChar();
        SDL_RenderPresent(ren);

    }
void Character::manageEvents(SDL_Event event)
{
    switch(event.type){
        case SDL_KEYDOWN:
            KEYS[event.key.keysym.sym] = true;
            printf("true");
            handleInput();
            break;
        case SDL_KEYUP:
            KEYS[event.key.keysym.sym] = false;
            printf("false");
            break;
        default:
            break;
    }
}
void Character::handleInput()
{
    if(KEYS[SDLK_a]) {
        dst.x--;
    }
    if(KEYS[SDLK_d]) {
        dst.x++;
    }
    if(KEYS[SDLK_w]) {
        dst.y++;
    }
    if(KEYS[SDLK_s]) {
        dst.y--;
    }
}

```

# Answer
Your problem is that **you are not handling continuous key presses properly**, what you need to do is to move the keys that need to be handled continuously outside the while loop of the SDL\_PollEvent, and make sure to keep the key handling for single key press that do not require holding like "escape" inside the loop. Also make sure to handle them separately not in the same *handleInput* function, for example handleKeyDown (for key hold) and HandleKeyPress (for single hit).

Your code should look like this:

```
while(game){
    while (SDL_PollEvent(&e)){
       mainChar.keyPress(e); // for single key press
    }

    mainChar.continousKeyPress(e); // for continues key presses
    background.renderChar();
    mainChar.renderChar();
    SDL_RenderPresent(ren);
}

```
> 2 votes

---
Tags: c++, movement, input, sdl
---


title: Efficiently rendering to 3D texture

text:
# Question
Title: Efficiently rendering to 3D texture
I have an existing depth texture and some other color textures, and want to process the information in them by rendering to a 3D texture (based on the depth contained in the depth texture, i.e. a point at (x/y) in the depth texture will be rendered to (x/y/texture(depth,uv)) in the 3D texture).

Simply doing one manual draw call for each slice of the 3D texture (via glFramebufferTextureLayer) is terribly slow, since I don't know beforehand to what slice of the 3D texture a given texel from one of the color textures or the depth texture belongs. This means the entire process is effectively

```
for each slice
  for each texel in depth texture
      process color textures and render to slice

```

So I have to sample the depth texture completely per each slice, and I also have to go through the processing (at least until to discard;) for all texels in it.

It would be much faster if I could rearrange the process to

```
for each texel in depth texture
   figure out what slice it should end up in
       process color textures and render to slice

```

Is this possible? If so, how?

What I'm actually trying to do: the color textures contain lighting information (as seen from light view, it's a reflective shadow map). I want to accumulate that information in the 3D texture and then later use it to light the scene. More specifically I'm trying to implement Cryteks Light Propagation Volumes algorithm.

# Answer
> 8 votes
It is very simple to do it in one simple draw call, by iterating every texel in the depth buffer inside the vertex shader. You will choose to draw points, as many as the depth buffer resolution or less, and in the vertex shader you will fetch the depth buffer value and project it into the cube, which the 3D texture covers.
You can choose from the vertex shader to which slice you want to render the point ( e.x. in openGL you pass the slice to the variable gl\_Layer ). Then in the fragment shader, you do whatever calculations you want.
( There is an extension that supports the gl\_Layer in the vertex shader (GL\_AMD\_vertex\_shader\_layer). You can use it if you can or you can have a simple pass through geometry shader that just sets the gl\_Layer value )

---
Tags: opengl
---


# Question
Title: Creating Rectangle-based buttons with OnClick events
As the title implies, I want a Button class with an `OnClick` event handler. It should fire off connected events when it is clicked.

This is as far as I've made it:

```
public class Button {

    public event EventHandler OnClick;

    public Rectangle Rec { get; set; }
    public string Text { get; set; }

    public Button(Rectangle rec, string text) {
        this.Rec = rec;
        this.Text = text;
    }

}

```

I have no clue what I'm doing with regards to events. I know how to use them but creating them myself is another matter entirely. I've also made buttons without using events that work on a case-by-case basis.

So basically, I want to be able to attach methods to the `OnClick` EventHandler that will fire when the Button is clicked (i.e., the mouse intersects Rec and the left mouse button is clicked).

# Answer
> 3 votes
To do this, you need to sample the state of the mouse regularly, and when it's clicked, check the coordinates against the button and see how that goes.

Usually, I write something like this in `Button`:

```
public void Update() { // called every tick
  var mouseState = Mouse.GetState();
  if (this.OnClick != null && mouseState.LeftButton == ButtonState.Pressed && oldState.LeftButton == ButtonState.Released) {
    // Someone's listening, and we have a click
    this.OnClick.Invoke();
  }
  this.oldState = mouseState;
}

```

The core is really:

* Check the mouse state now
* Compare to the old state last tick. If we weren't pressed, and now we are, that's a click.
* Check if anyone's subscribing to our event (`this.OnClick != null`), and if so, notify them of the click.

By the way, your event can use `Action` if you pass no parameters to the subscribers of the click event (C# Forms defaults is to use sender and event args); `Action` can take parameters if you *do* want to send some data over.

Eg. you can make your event `public event Action OnClick`.

# Answer
> 2 votes
For those interested, this is my final (so far) Button class:

```
public class Button {

    public event Action OnClick;
    public event Action OnHover;

    public Rectangle Rec { get; set; }
    public string Text { get; set; }

    public Button(Rectangle rec, string text) {
        this.Rec = rec;
        this.Text = text;
    }

    public void Update(MouseState prev, MouseState cur) { // called every tick
        if (this.OnClick != null && Rec.Contains(cur.X, cur.Y) && cur.LeftButton == ButtonState.Pressed && prev.LeftButton == ButtonState.Released) {
            // Someone's listening, and we have a click
            this.OnClick.Invoke();
        }
        if (this.OnHover != null && Rec.Contains(cur.X, cur.Y)) {
            // Someone's listening, and we have a hover
            this.OnHover.Invoke();
        }
    }

    public void Draw(SpriteBatch spriteBatch, Color btnCol, Color textCol) {
        spriteBatch.Draw(Game1.TheGame.GuiTex, Rec, btnCol);
        Vector2 fontCenter = Game1.TheGame.DebugFont.MeasureString(Text) / 2;
        spriteBatch.DrawString(Game1.TheGame.DebugFont, Text, new Vector2(Rec.Center.X, Rec.Center.Y), textCol, 0, fontCenter, 1f, SpriteEffects.None, 0);
    }
}

```

And here is an example of how it is used:

```
Button[] menuOptions;
int selectedOption = 0;

...

menuOptions = new Button[3] {
    new Button(new Rectangle(x, y, width, height), "New Game"),
    new Button(new Rectangle(x, y, width, height), "Load Game"),
    new Button(new Rectangle(x, y, width, height), "Settings")
};

...

for (int i = 0; i < menuOptions.Length; i++) {
    int j = i; // this is due to the way C# deals with closures and captured variables
    menuOptions[i].OnHover += delegate() { selectedOption = j; };
    menuOptions[i].OnClick += selectOption;
}

...

public void Draw(GameTime gameTime, SpriteBatch spriteBatch) {
    spriteBatch.Begin();
    foreach (Button btn in menuOptions) {
        Color btnCol = (btn == menuOptions[selectedOption]) ? Color.DarkBlue : Color.CadetBlue;
        Color textCol = (btn == menuOptions[selectedOption]) ? Color.White : Color.Black;
        btn.Draw(spriteBatch, btnCol, textCol);
    }
    spriteBatch.End();
}

...

private void selectOption() {
    if (selectedOption == 0) { // New Game
        // do new game stuff
    } else if (selectedOption == 1) { // Load Game
        // do load game stuff
    } else if (selectedOption == 2) { // Settings
        // do settings stuff
    }
}

```

This example is far from perfect and it would have to be adapted to any specific needs, but it should help.

# Answer
> 0 votes
The button WinForms control is able to add themes, rotation and transparency, images and text to C#.NET projects as well as creating rectangle buttons.

---
Tags: c#, xna-4.0, events
---


title: ContentManager in XNA cant find any XML

text:
# Question
Title: ContentManager in XNA cant find any XML
Im making a game in XNA 4 and this is the first time I'm using the Content loader to initialize a simple class with a XML file, but no matter how many guide I follow, or how simple or complicated is my XML File the ContentManager cant find the file; the Debug keep telling me: "A first chance exception of type 'Microsoft.Xna.Framework.Content.ContentLoadException' occurred in Microsoft.Xna.Framework.dll". I'm really confuse because I can load SpriteFonts and Texture2D without a problem ...

I create the following XML (the most basic Xna XML):

```
    <?xml version="1.0" encoding="utf-8" ?>
<XnaContent>
  <Asset Type="System.String">Hello</Asset>
</XnaContent>

```

and I try to load it in the LoadContent method in my main class like this:

```
System.String hello = Content.Load<System.String>("NewXmlFile");

```

There is something I'm doing wrong? I really appreciate your help

# Answer
> 1 votes
The code you have provided works fine.

Create a new XNA 4.0 Windows project. Right click on the *Content* project and add a new item. Choose "XML File". Open that created file and fill it with the content you have in your question.

Then add the line:

```
System.String hello = Content.Load<System.String>("NewXmlFile");

```

To your `LoadContent` method. Be sure that `NewXmlFile` is the filename of the XML file you created, *without* its file extension. For example, if you used the default name given to you when creating the file, above, you should replace `"NewXmlFile"` with `"XMLFile1"`.

Set a breakpoint on the line after your call to `Load`. Run your game, and observe in the debugger that the variable `hello` now contains your string.

---
Tags: xna, c#, xna-content-pipeline, xml
---


title: Grid-Based 2D Lighting Problems

text:
# Question
Title: Grid-Based 2D Lighting Problems
I am aware this question has been asked before, but unfortunately I am new to the language, so the complicated explanations I've found do not help me in the least.

I need a lighting engine for my game, and I've tried some procedural lighting systems. This method works the best:

```
if (light[xx - 1, yy] > light[xx, yy]) light[xx, yy] = light[xx - 1, yy] - lightPass;
if (light[xx, yy - 1] > light[xx, yy]) light[xx, yy] = light[xx, yy - 1] - lightPass;
if (light[xx + 1, yy] > light[xx, yy]) light[xx, yy] = light[xx + 1, yy] - lightPass;
if (light[xx, yy + 1] > light[xx, yy]) light[xx, yy] = light[xx, yy + 1] - lightPass;

```

(Subtracts adjacent values by 'lightPass' variable if they are more bright) (It's in a for() loop)

This is all fine and dandy except for:

The system favors whatever comes first in the for() loop

This is what the above code looks like applied to my game:

On the left side you can see some weirdness going on:

The loop goes top to down then to the right column:

This is how the for() loop goes:

Light provided from my mouse, should be a full light, but is only half:

If I could get some help on creating a new procedural or otherwise lighting system I would really appreciate it!

# Answer
Since your question is kind of broad, I'm going to give a kind of broad answer.

A recursive algorithm is a typical way to approach this. The algorithm "flows" outward until there's no more light to spread. Remember to put in a base case for your algorithm, or you'll never stop lighting. For example, if the next tile being selected is as bright or brighter than the current tile. Since you're likely to have large grids, you'll probably want to implement a list for your recursion instead of using the stack (it'll probably overflow). An example of this might be:

(note this is using the stack based approach, only recommended for shallow recursion, there's an example that's similar to the list approach below)

```
Light(x, y, value)
  (x,y).lightvalue = value
  if(value-1 > 0)
      if((x-1, y).lightvalue < value-1)
          Light(x-1,y,value-1)
      if((x+1, y).lightvalue < value-1)
          Light(x+1,y,value-1)
      if((x, y-1).lightvalue < value-1)
          Light(x,y-1,value-1)
      if((x, y+1).lightvalue < value-1)
          Light(x,y+1,value-1)

```

Clearly your case would be a lot more complex, since you want to account for sky light shining down, you'll have to keep track of if the tile has sky directly above it.

Another option is some kind of cellular automata. So each tile knows its state and can tell neighboring tiles they should update their state. Something like:

```
foreach(tile in tilesToUpdate)
   if(tileToLeft.lightValue > thisLightValue + 1)
       this.lightValue = tileToLeft.lightValue - 1
   else if(tileToLeft.lightValue < thisLightValue)
      tilesToUpdate.add(tileToLeft)
   //repeat for other directions

```

Again, this would need to be modified to allow for your sky light requirement. You'd kick off this algorithm by setting the light value of one tiles and adding it to the list of tiles to update.

You might also find it's more optimal to update all the lighting using your existing method, while making a list of tiles that will likely need to be updated by one of the above methods. These are just very simple examples that would need to be significantly optimized for your use cases, but they're a start.

You can see a related question here where I went into a bit more detail about some aspects of lighting. And another related question that might be useful.
> 1 votes

---
Tags: xna, c#, 2d, lighting, grid
---


# Question
Title: Drawing multiple objects from one Vertex Buffer Object in OpenGL/OpenTK
I am trying to experimenting drawing method using VBO in OpenGL. Many people normally use 1 vbo to store one object data array. I was trying to do something quite opposite which is storing multiple object data into 1 vbo then drawing it. There is story behind why i want to do this. I want to group many of objects as a single object sometime. However my code doesn't do the justice. Following is my pseudo code:

```
//Data
int[] _vBO = new int[1]; //vertex buffer objects

_triangleVertices = new float[]
                  { 0.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, //first triangle lineloop, positions in the middle of the screen.
                    3.0f, 1.0f, 0.0f, 2.0f, -1.0f, 0.0f, 4.0f, -1.0f, 0.0f, //second triangle lineloop, positions on the left side of the first triangle.
                    -3.0f, 1.0f, 0.0f, -4.0f, -1.0f, 0.0f, -2.0f, -1.0f, 0.0f  }; //third triangle lineloop, positions on the right side of the first triangle.

//Setting Up
void init()
{
   GL.GenBuffers(1, _vBO);
   GL.BindBuffer(BufferTarget.ArrayBuffer, _vBO[0]);
   GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(sizeof(float) * _triangleVertices.Length), _triangleVertices, BufferUsageHint.StaticDraw);
   GL.VertexPointer(3, VertexPointerType.Float, 0, 0);
   GL.EnableClientState(Array.VertexArray);
}

//Drawing
void display()
{
    GL.Clear(ClearBufferMask.ColorBufferBit);
    GL.Clear(ClearBufferMask.DepthBufferBit);

    //setting up camera and projection.
    float[] eyes = { 0.0f, 0.0f, -10.0f };
    float[] target = { 0.0f, 0.0f, 0.0f };
    Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView(0.785398163f, 4.0f / 3.0f, 0.1f, 100f);  //45 degree = 0.785398163 rads
    Matrix4 view = Matrix4.LookAt(eyes[0], eyes[1], eyes[2], target[0], target[1], target[2], 0, 1, 0);
    Matrix4 model = Matrix4.Identity;
    Matrix4 MV = view * model;

    GL.MatrixMode(MatrixMode.Projection);
    GL.LoadIdentity();
    GL.LoadMatrix(ref projection);

    GL.MatrixMode(MatrixMode.Modelview);
    GL.LoadIdentity();
    GL.LoadMatrix(ref MV);

    GL.Viewport(0, 0, glControlWindow.Width, glControlWindow.Height);
    GL.Enable(EnableCap.DepthTest); //Enable correct Z Drawings
    GL.DepthFunc(DepthFunction.Less); //Enable correct Z Drawings
    GL.MatrixMode(MatrixMode.Modelview);

    //Draw
    drawTriangleLineLoops();

    //Finally...
    GraphicsContext.CurrentContext.VSync = true; //Caps frame rate as to not over run GPU
    glControlWindow.SwapBuffers(); //Takes from the 'GL' and puts into control
}

void drawTriangleLineLoops()
{
   GL.BindBuffer(BufferTarget.ArrayBuffer, _vBO[0]);
   GL.VertexPointer(3, VertexPointerType.Float, 0, 0);
   GL.EnableClientState(ArrayCap.VertexArray);
   GL.DrawArrays(BeginMode.LineLoop, 0, 3); //drawing first triangle lineloop, first vertex starts at index 0.
   GL.DrawArrays(BeginMode.LineLoop, 9, 3); //drawing second triangle lineloop, first vertex starts at index 9.
   GL.DrawArrays(BeginMode.LineLoop, 18, 3); //drawing third triangle lineloop, first vertex starts at index 18.
   GL.DisableClientState(ArrayCap.VertexArray);
}

```

I expect 3 different triangles to be drawn, but only one was drawn. I don't know what went wrong.

# Answer
> 0 votes
The answer is:

```
GL.DrawArrays(BeginMode.LineLoop, 0, 3);
GL.DrawArrays(BeginMode.LineLoop, 3, 3);
GL.DrawArrays(BeginMode.LineLoop, 6, 3);

```

I guess the enable vertex array treats an element as a memory junk of whatever size you defined a vertex array with GL.VertexPointer coordinate for a vertex.

# Answer
> 2 votes
You are offsetting twice, you are specifying the line loop offset in the call to `VertexPointer`, then again in `DrawArrays`. `DrawArrays` starts drawing from the index specified in the second parameter.

The following calls should be enough:

```
GL.VertexPointer(3, VertexPointerType.Double, 0, lineloop1offset); //starting from the beginning of the array
GL.DrawArrays(BeginMode.LineLoop, lineloop1offset , lineloop1VertexNum  );
GL.DrawArrays(BeginMode.LineLoop, lineloop2offset , lineloop2VertexNum );
GL.DrawArrays(BeginMode.LineLoop, lineloop3offset , lineloop3VertexNum );

```

---
Tags: opengl, vbo, opentk
---


title: Problems with 3D Array for Voxel Data

text:
# Question
Title: Problems with 3D Array for Voxel Data
I'm trying to implement a voxel engine in C++ using OpenGL, and I've been working on the rendering of the world. In order to render, I have a 3D array of `uint16`'s that hold that id of the block at the point. I also have a 3D array of `uint8`'s that I am using to store the visibility data for that point, where each bit represents if a face is visible. I have it so the blocks render and all of the proper faces are hidden if needed, but all of the blocks are offset by a power of 2 from where they are stored in the array. So the block at \[0\]\[0\]\[0\] is rendered at (0, 0, 0), and the block at  is rendered at (1, 1, 1), but the block at \[2\]\[2\]\[2\] is rendered at (4, 4, 4) and the block at \[3\]\[3\]\[3\] is rendered at (8, 8, 8), and so on and so forth.

This is the result of drawing the above situation:

I'm still a little new to the more advanced concepts of C++, like triple pointers, which I'm using for the 3D array, so I think the error is somewhere in there. This is the code for creating the arrays:

```
uint16*** _blockData; //Contains a 3D array of uint16s that are the ids of the blocks in the region
uint8*** _visibilityData; //Contains a 3D array of bytes that hold the visibility data for the faces

   //Allocate memory for the world data
_blockData = new uint16**[REGION_DIM];
for (int i = 0; i < REGION_DIM; i++)
{
    _blockData[i] = new uint16*[REGION_DIM];

    for (int j = 0; j < REGION_DIM; j++)
        _blockData[i][j] = new uint16[REGION_DIM];
}

//Allocate memory for the visibility
_visibilityData = new uint8**[REGION_DIM];
for (int i = 0; i < REGION_DIM; i++)
{
    _visibilityData[i] = new uint8*[REGION_DIM];

    for (int j = 0; j < REGION_DIM; j++)
        _visibilityData[i][j] = new uint8[REGION_DIM];
}

```

Here is the code used to create the block mesh for the region:

```
//Check if the positive x face is visible, this happens for every face
//Block::VERT_X_POS is just an array of non-transformed cube verts for one face
//These checks are in a triple loop, which goes over every place in the array
if (_visibilityData[x][y][z] & 0x01 > 0)
{
    _vertexData->AddData(&(translateVertices(Block::VERT_X_POS, x, y, z)[0]), sizeof(Block::VERT_X_POS));
}

//This is a seperate method, not in the loop
glm::vec3* translateVertices(const glm::vec3 data[], uint16 x, uint16 y, uint16 z)
{
    glm::vec3* copy = new glm::vec3[6];
    memcpy(&copy, &data, sizeof(data));

    for(int i = 0; i < 6; i++)
        copy[i] += glm::vec3(x, -y, z); //Make +y go down instead

    return copy;
}

```

I cannot see where the blocks may be getting offset by more than they should be, and certainly not why the offsets are a power of 2. Any help is greatly appreciated. Thanks.

# Answer
> 3 votes
Things like int\*** are completely the wrong thing to use here. A "triple pointer" is not logically the same thing as a 3-dimensional array. You can just use a plain std::vector and claculate offsets manually with something like z * width * height + y * width + x (with the total size being width * height * depth of course).

Create a vector, resize it, then copy in the right data. If you don't resize first, you must be sure to use `push_back` or `back_inserter`:

```
// or just pass the size to the constructor; same diff
std::vector<int> blocks;
blocks.resize(width * height * depth);

// not idiomatic C++, but it should work
std::memcpy(data.data(), source_array, blocks.size() * sizeof(blocks.at(0));

// better option if you resize first; may or may not be equivalent to memcpy depending on implementation and the PODness of the vector's contained type
std::copy(source_begin, source_end, begin(data));

// and the better option if you don't resize first, though this may resize multiple times internally, and is not the most efficient choice
std::copy(source_begin, source_end, std::back_inserter(blocks));

```

---
Tags: c++, opengl, 3d-meshes, voxels, vertex
---


# Question
Title: Translate extrinsic rotations to intrinsic rotations ( Euler angles )
The problem I have is very frustrating: I am using the Jitter Physics library which gives Quaternion rotations, you can extract the extrinsic rotations but I need intrinsic rotations to rotate in OpenTK (There are other reasons as well so I don't want to make OpenTK use a Matrix)

```
GL.Rotate(xr, 1, 0, 0)
GL.Rotate(yr, 0, 1, 0)
GL.Rotate(zr, 0, 0, 1)

```

**EDIT : Response to the first answer**

```
Like This?

GL.Rotate(zr, 0, 0, 1)
GL.Rotate(yr, 0, 1, 0)
GL.Rotate(xr, 1, 0, 0)

Or This?

GL.Rotate(xr, 1, 0, 0)
GL.Rotate(yr, 0, 1, 0)
GL.Rotate(zr, 0, 0, 1)

GL.Rotate(zr, 0, 0, 1)
GL.Rotate(yr, 0, 1, 0)
GL.Rotate(xr, 1, 0, 0)

GL.Rotate(xr, 1, 0, 0)
GL.Rotate(yr, 0, 1, 0)
GL.Rotate(zr, 0, 0, 1)

I'm confused, please give an example

```

# Answer
> 0 votes
The only way it seems is to plug the matrix into OpenTK Thanks for all the help though.

As to help any others with this problem this is the code

```
            GL.PushMatrix()

            Dim bim As Matrix4
            bim.M11 = Rotation(0)
            bim.M12 = Rotation(1)
            bim.M13 = Rotation(2)
            bim.M21 = Rotation(3)
            bim.M22 = Rotation(4)
            bim.M23 = Rotation(5)
            bim.M31 = Rotation(6)
            bim.M32 = Rotation(7)
            bim.M33 = Rotation(8)
            bim.M44 = 1
            bim = bim

            GL.PopMatrix()
            GL.PushMatrix()

            GL.MultMatrix(Matrix4.CreateTranslation(BlockPos(0) * 50, BlockPos(1) * 50, BlockPos(2) * 50))
            GL.MultMatrix(bim)

```

# Answer
> 1 votes
So extrinsic rotation is generally meant to mean rotation around a fixed axis, while intrinsic rotation is rotation around a moving axis. In the former case the axes around which the rotation occurs are fixed in the spatial reference frame in which the object exists, whereas in the latter case it moves with the body.

You can verify it yourself that **rotations around the axes of a fixed coordinate frame in a certain order is the same as rotations around the axes of a moving coordinate frame in exactly the opposite order**. I suggest verifying this initially with some examples. I like a mug with a face on, but others have used textbooks or 3-legged dogs. Subsequently think how the rotation is applied around the axis in which the object is embedded at the start of its rotation and at its end.

This seems to suggest a very simple solution to your problem: *take the extrinsic rotation amounts and apply them in the opposite order* (thus using them as intrinsic rotations).

---
Tags: rotation, .net, opentk
---


# Question
Title: How to automatically render all opaque meshes with a specific shader?
I have a specular outline shader that I want to be used on all opaque meshes of the scene whenever a specific camera renders. The shader is working properly when it is manually applied to some material. The shader is as follows:

```
Shader "Custom/Outline" {
Properties {
    _Color ("Main Color", Color) = (.5,.5,.5,1)
    _OutlineColor ("Outline Color", Color) = (1,0.5,0,1)
    _Outline ("Outline width", Range (0.0, 0.1)) = .05
    _SpecColor ("Specular Color", Color) = (0.5, 0.5, 0.5, 1)
    _Shininess ("Shininess", Range (0.03, 1)) = 0.078125
    _MainTex ("Base (RGB) Gloss (A)", 2D) = "white" {}
}

SubShader {
    Tags { "Queue"="Overlay" "RenderType"="Opaque" }
    Pass {
        Name "OUTLINE"
        Tags { "LightMode" = "Always" }

        Cull Off
        ZWrite Off
        // Uncomment to show outline always.
        //ZTest Always

        CGPROGRAM
        #pragma target 3.0
        #pragma vertex vert
        #pragma fragment frag

        #include "UnityCG.cginc"

        struct appdata {
            float4 vertex : POSITION;
            float3 normal : NORMAL;
        };

        struct v2f
        {
            float4 pos : POSITION;
            float4 color : COLOR;
        };

        float _Outline;
        float4 _OutlineColor;

        v2f vert(appdata v) {
            // just make a copy of incoming vertex data but scaled according to normal direction
            v2f o;
            o.pos = mul(UNITY_MATRIX_MVP, v.vertex);

            float3 norm   = mul ((float3x3)UNITY_MATRIX_IT_MV, v.normal);
            float2 offset = TransformViewToProjection(norm.xy);

            o.pos.xy += offset * o.pos.z * _Outline;
            o.color = _OutlineColor;
            return o;
        }

        float4 frag(v2f fromVert) : COLOR {
            return fromVert.color;
        }
        ENDCG
    }
    UsePass "Specular/FORWARD"
}

FallBack "Specular"
}

```

The camera used fot the effect has just a script component which setups the shader replacement:

```
using UnityEngine;
using System.Collections;

public class DetectiveEffect : MonoBehaviour {

    public Shader EffectShader;

    // Use this for initialization
    void Start () {
        this.camera.SetReplacementShader(EffectShader, "RenderType=Opaque");
    }

    // Update is called once per frame
    void Update () {

    }
}

```

Unfortunately, whenever I use this camera I just see the background color. Any ideas?

# Answer
I have misunderstood the concept of shader replacement. The replacementTag value of

```
SetReplacementShader(shader: Shader, replacementTag: string): void;

```

must be the tag type only. Then, in the replacement shader I have to set the tag value that I want to replace, as I did before. Any material with this value in the tag will use the replacement shader instead when rendered by the camera with the effect script attached and enabled. The final code of the effect script became:

```
using UnityEngine;
using System.Collections;

    public class DetectiveEffect : MonoBehaviour {

    public Shader EffectShader;

    // Use this for initialization
    void Start () {
        //Notice the "RenderType" tag here.
        this.camera.SetReplacementShader(EffectShader, "RenderType");
    }

    // Update is called once per frame
    void Update () {
    }
}

```

The shader code did not changed. But notice where the tag is set.

```
//...

SubShader {
Tags { "Queue"="Overlay" "RenderType"="Opaque" }
Pass {

//...

```

In my case, any material with a shader with the RenderType tag equals Opaque will be replaced by my shader when rendered by my effect camera.
> 1 votes

---
Tags: unity, shaders, camera
---