# Question
Title: How to: Java Game on Eclipse to Steam Direct
I want to create a game using Java and later put the finished product to Steam Direct.

How does the whole process work after the game is finished and running on Eclipse?

# Answer
> 17 votes
I assume you really want to know two things:

1. Will Steam accept my Java game?
2. What do I need to do to make it work on Steam?

The answer to #1 is "yes." Steam hosts other Java games (like Spiral Knights).

For #2, I suggest you package your game using launch4j. This will provide you with native (Windows, Linux) wrappers around your application. Other benefits include (from their home page):

> The wrapper also provides better user experience through an application icon, a native pre-JRE splash screen, and a Java download page in case the appropriate JRE cannot be found.

You can get the latest version from Maven for your maven/gradle builds.

Also, note: Greenlight is not some magic marketing machine. You have to market your game really, *really* well to get it greenlit.

# Answer
> 2 votes
If your game is running **only** on Eclipse, start by packing the .jar, the assets and all that come with your game and try your game on different OS (or ask other people to do it).

You will have a good return about the technical problems ("game's not working", "laaag") and the gameplay problems ("not funny enough", "what am I supposed to do ?", "boring...").

Then you have to pay a fee, for the Greenlight submission.

In my opinion it is even better if you have a native launcher, but that is a bonus.

---
Tags: java, steam
---


# Question
Title: How to create a regular grid of triangles correctly?
I am trying to create an terrain using opentk/opengl.

I have a problem with the VBO/IBO. I think a picture of the problem is the best way to show it:

I dont understand why the last triangle of a row connects to the first vertices of the row.

Here is the code:

```
int mapSize = 7;
    void CreateVertexBuffer()
    {
        Vector3[] vertices = new Vector3[(mapSize + 1) * (mapSize + 1)];
        short[] indices = new short[ ((mapSize)*(mapSize)) * 6];

        for (int x = 0; x < mapSize + 1 ; x++)
        {
            for (int y = 0; y < mapSize + 1 ; y++)
            {
                int li_offset = x * (mapSize + 1) + y;
                vertices[li_offset] = new Vector3(x / 4.0f, 0 , y / 4.0f);
            }
        }
        int index = 0;
        for (int x = 0; x < mapSize ; x++)
        {
            for (int y = 0; y < mapSize ; y++)
            {
                indices[index + 0] = (short)( x * (mapSize + 1) + y);
                indices[index + 1] = (short)(indices[index + 0] + mapSize + 2);
                indices[index + 2] = (short)(indices[index + 0] + mapSize + 1);

                indices[index + 3] = (short)(indices[index + 0]);
                indices[index + 4] = (short)(indices[index + 0] + 1);
                indices[index + 5] = (short)(indices[index + 0] + 2);

                index += 6;
            }
        }
        GL.GenBuffers(1, out vbo);
        GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
        GL.BufferData<Vector3>(BufferTarget.ArrayBuffer,
                               new IntPtr(vertices.Length * Vector3.SizeInBytes),
                               vertices, BufferUsageHint.StaticDraw);
        GL.GenBuffers(1, out ibo);
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, ibo);
        GL.BufferData<short>(BufferTarget.ElementArrayBuffer,
                               new IntPtr(indices.Length * sizeof(short) ),
                               indices, BufferUsageHint.StaticDraw);
    }

```

How can I make the last row of triangles properly formed like all the others?

# Answer
> 2 votes
Okay, after bug-searching for a while i came up with this, which works just fine.

```
 void CreateVertexBuffer()
    {
        Vector3[] vertices = new Vector3[mapSize*mapSize];

        short[] indices;

        for (int x = 0; x < mapSize; x++)
        {
            for (int z = 0; z < mapSize; z++)
            {
                vertices[x * mapSize + z] = new Vector3(x/10.0f,1.0f,z/10.0f);
            }
        }

        indices = new short[mapSize * mapSize * 6];
        int index = 0;

        for (int x = 0; x < mapSize ; x++)
        {
           for (int z = 0; z < mapSize-1; z++)
           {
                int offset = x * mapSize + z;
                indices[index] = (short)(offset + 0);
                indices[index + 1] = (short)(offset + 1);
                indices[index + 2] = (short)(offset + mapSize);
                indices[index + 3] = (short)(offset + 1);
                indices[index + 4] = (short)(offset + mapSize + 1);
                indices[index + 5] = (short)(offset + mapSize);
                index += 6;
            }
        }

        GL.GenBuffers(1, out vbo);
        GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
        GL.BufferData<Vector3>(BufferTarget.ArrayBuffer,
                               new IntPtr(vertices.Length * Vector3.SizeInBytes),
                               vertices, BufferUsageHint.StaticDraw);
        GL.GenBuffers(1, out ibo);
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, ibo);
        GL.BufferData<short>(BufferTarget.ElementArrayBuffer,
                               new IntPtr(indices.Length * sizeof(short) ),
                               indices, BufferUsageHint.StaticDraw);
    }

```

---
Tags: opengl, terrain, opentk
---


title: Projective texturing and falloff

text:
# Question
Title: Projective texturing and falloff
I quite understand how projective texturing works. I implemented successfully a shader for that following nvidia doc.

The major problem I'm facing is that with that implementation the projector frustum is used only to determine the texture coordinate in projective space, but it doesn't clip anything outside the projective frustum volume.

In other words, if I have a projector pointing toward a object, the texture will be projected on it even if the object is outside its frustum. In addition when projector is almost parallell to the projected object, the texture stretching is too evident and I would like to fade it out.

Now, I'm trying to understand how `Unity` handles their built-in projectors. I found this example. Here's vertex and fragment relevant code:

```
v2f vert (float4 vertex : POSITION)
{
  v2f o;
  o.pos = mul (UNITY_MATRIX_MVP, vertex);
  o.uvShadow = mul (_Projector, vertex);
  o.uvFalloff = mul (_ProjectorClip, vertex);
  return o;
}

fixed4 frag (v2f i) : SV_Target
{
  fixed4 texS = tex2Dproj (_ShadowTex, UNITY_PROJ_COORD(i.uvShadow));
  texS.rgb *= _Color.rgb;
  texS.a = 1.0-texS.a;

  fixed4 texF = tex2Dproj (_FalloffTex, UNITY_PROJ_COORD(i.uvFalloff));
  fixed4 res = texS * texF.a;
  return res;
}

```

I think that `_Projector` matrix is a classical matrix to transform vertices coordinates into projector space. (In fact the fragment just use the transformed coordinates to sample the projected texture).

What I'm really missing is how Unity construct `_ProjectionClip` matrix. The transformed vertex coordinates are used to sample the falloff texture (that I think it is what I really need).

Does anyone know how the `_ProjectionClip` is constructed? Or how to achieve a similar effect?

Note: I did something similar for calculating spotlights falloff, but there I used a single matrix multiplication in the vertex shader to transform vertices into lightspace, and the squared distance in the fragment shader to calculate texture coords for a lookup into the attenuation texture.

# Answer
For clipping pixels outside the frustum, you can use a texture with the border mode enabled and a black border. (Or a black 1-pixel border authored directly in the texture). Alternatively, in an additive blending pass, you can add code to the shader to `discard` the pixel if the UVs are outside the unit square.

For fading the projection out when the projected object is close to parallel, the ordinary lighting N·L factor will mostly take care of this. You can fade things out sooner by biasing the N·L factor a little bit.

As far as the Unity shader goes, my guess is it simply lets you have different scales for the main texture and falloff texture. For instance, the main texture could be some image and the falloff texture might be a white circle fading into a black background, which multiplies with the main texture and restricts it to only appear in that circle. The user could adjust the frusta for the two textures independently.

In other words, the `_ProjectionClip` matrix is simply another classical projection matrix, potentially built with different parameters. It doesn't magically clip anything; it's just that some combination of factors reduces the light color to zero outside the desired frustum.
> 1 votes

---
Tags: unity, textures, shaders, projection
---


# Question
Title: How to resolve OBB collision penetration?
I would think this is a common issue, but I couldn't find an answer that helped me. Help would be appreciated.

In my game I have rectangular objects. They have rotating bounding box, aka not AABB but boxes that rotate with the entity and always match it's exact shape (I think it's called OBB).

When two objects collide, they often penetrate each other a little:

My question is, how can I move the objects out of each other? (Before performing the 'actual' collision handling, i.e. setting velocities etc).

# Answer
The answer is Separate Axis Theorem

Besides detecting collision, with SAT you can easily get the penetration vector and set the velocities with it
> -1 votes

---
Tags: collision-detection, physics, bounding-boxes
---


# Question
Title: 3d rotation of a Gunner unit to shoot the target
I'm developing a scenario to shoot incoming targets by a specific gunner unit, however I'm confused to actual logic of shooting an object with a gun. I'm working in 3D environment. I'v target's position vector i.e `[x,y,z]` and its rotation vector `[x,y,z,angle]`, and also Gun's position vector i.e `[x,y,z]` and its rotation vector `[x,y,z,angle]`. The gun has two components, i.e a `TopDondur` and a set of `Barrels`, both components have the rotation along y-axis, i.e only angel of rotation vector `[0 1 0 angle]` is required to move the Gunner Unit to the target.

What rotataions shuould give the Gunner unit to rotate both `TopDondur` and `Barrels`, i.e `TopDondur` rotates to the target and `Barrels` are to move up/down with respect to that target.

# Answer
> 1 votes
A solution that would work in all cases would be *inverse kinematics*. You may want to look it up, but that is quite a complex topic.

Here is a general solution for your special problem:

I don't really understand how the `TopDondur` and `Berrels` are related (or even what `TopDondur` is supposed to be) so I will for sake of simplicity assume only on "character". I will also assume that orientations are handled as a R3 matrix (you won't get far with angle + axis).

This is basically what I call a "look at" problem and you can solve it similarly to the function with that same name (`gluLookAt`). For this you need a position, a target vector and an up vector. And we basically already have everything:

```
vec3 position = // given by the gunner
vec3 target   = // given by the target
vec3 up       = vec(0, 0, 1); // I assume that
vec3 forward  = normalize(target - position);
vec3 side     = normalize(cross(forward, up));
// ensure that up really is orthogonal to side and up
up            = cross(side, forward);

mat3 orientation = mat3(forward, side, up);

```

Now you have the orientation to face the target. The cheap way would be to automatically apply the orientation to the gunner. You can interpolate the current orientation to "slowly" match the target orientation.

You may want to look at the Matrix and Quaternion FAQ on how to get from an angle axis to a R3 matrix and back. When interpolating you may want to go over quaternions for smooth interpolation.

An alternative would be to convert both the current orientation and the target vector to spherical coordinates. This gives you more fine control over "horizontal" and "vertical" movement. This may be of importance, since you state that you only allow movement along the Y-axis.

---
Tags: rotation, angles, shooter
---


title: projection and matrices

text:
# Question
Title: projection and matrices
Many games do just fine with two projections, that can be represented by a matrix (orthographic and linear perspective). But what about projections that can't be represented by a matrix? Can you please provide some examples of such projections and why they might be used in a game application?

# Answer
Cameras used in graphics applications are most of the time orthographic or mimic a pinhole camera. Both can be represent by a 4\*4 matrix. A special variant would be a camera used for 3D rendering where the optical axis is not in the middle of the resulting image (e.g. parallel shift 3D) - but even they can be represented as a 4\*4 matrix.

Real camera lenses however can work differently (fisheye lenses) or even tho they are designed to mimic a pinhole, they introduce (unintentionally) a pincushion or barrel distortion. These more exact models are used in computer vision (see for example bundler: http://www.cs.cornell.edu/~snavely/bundler/bundler-v0.3-manual.html ).

If a game wants to mimic real lenses and those effects, it should do so as a post-processing pass in a fragment shader as straight lines should get "bended" and only projecting the vertices correctly (and not the fragments that get generated as rasterization later) will introduce artefacts.

The only example I'm aware of where such a distortion is used in games is the pre-distortion in Oculus Rift games to counter the real-world lens distortion of the HMD. But here it can be handled by the SDK and also is not a property of the games camera so it should not be a property of the camera class.

tl;dr: Unless you plan a photography oriented game with perfectly realistic (fisheye) lenses, you can stick with a 4\*4 matrix.
> 1 votes

---
Tags: matrix, projection
---


title: Render character in bounding box

text:
# Question
Title: Render character in bounding box
i'm rendering an attack animation with the following code:

```
currentFrame = attackAnimation[3].getKeyFrame(stateTime, false); //3 : left, 2: right
batch.draw(currentFrame, getX(), getY());

```

This renders the CurrentFrame on the x and y position of the character. This works fine for the right animation as you can see here:

but when i apply the same code for left for example it doesn't draw the character on the correct place and like "pushes himself away" from the bottom left corner and leaving the bounding box.

What am I doing wrong or what am I not seeing?

```
setGameObject(new Sprite(txtIdle[2]));
setSize(getWidth(), getHeight());
setOrigin(getWidth() /2.0f, getHeight() /2.0f);
setPosition(500, 500);

```

this code sets an idle image and the size of the bounding box (and the sprite)

# Answer
It is drawing the bottom-left corner of the texture at the given coordinate (x,y). In the first case, it works because Link's body has an edge to the far left and so he appears inside the box. In the second case, however, the far left side of the texture is the end of the sword, so it places this part in the box and "draws out" from there.

One possible way to fix this would be to render the sword separately from Link's body. The bounding box is just large enough to contain Link, so you could render the sword just outside the bounding box at position `(box corner.x + box width, box corner.y)` when facing right and at `(box corner.x - sword width, box corner.y)` when facing the left.
> 2 votes

# Answer
You could try and set the bounding box size depending on the sprite size. If for some reason your sprites(animation frames) have different sizes, then use the largest one's size.
> 1 votes

---
Tags: libgdx
---


# Question
Title: How to obtain the currently bound texture ID in an openGL ES 2.0 project
In my game, I have:

```
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texID);

```

Where **texID** is an integer returned by my setTexture() method. Let's say, in this instance it's 1.

When I bind my textures during rendering calls, I don't want to bind this texture every single call. Because I use different atlases of various textures and it's pretty wasteful to keep re-binding a texture when it's not required.

So, I would like to do something like this (**Pseudo code**)

```
if (texID != *currentTexture*){
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texID);
}

```

Therefore, if the texture I want to use is the same as the one already bound, the call to re-bind it will be ignored.

I can't work out how to get the ID of the texture that is *currently* bound.

I've tried

```
GLES20.glActiveTexture();

```

But this doesn't return the textureID, it returns the texture Units

Help appreciated

**Edit**

I've tried the suggestion below but I'm getting the folowing errors:

When hovering over the underline, this is the error:

I had searched this site and the wider web for a couple of hours before posting here but couldn't find a proper usage example, just this out of context snippet.

# Answer
You should reconsider whether you really need to do this. Most of the time, querying the GL for such information should be avoided because it has an important performance cost.

Since you are the one doing the `glBindTexture` calls, you could track the resources yourself instead (this is called client state tracking). It could be as simple as having a global `LastBoundTexID` variable.
> 4 votes

# Answer
A very quick google search (2 minutes) reveals that you can get the active binding this way in opengl:

```
GLint whichID;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &whichID);

```
> 2 votes

---
Tags: java, android, textures, opengl-es2, texture-atlas
---


# Question
Title: integrating leaderboard from Newgrounds in flash game
I have made flash game and I want to show a leader board in that game. I have uploaded my game to kongregate.com.

I have made a scoreboard there with the name of **overLoadScore** (overload is the name of my game). i dragged an instance of API Loader component.

in my Main.as file I have the code.

```
var scoreBoard:ScoreBoard = new SoreBoard();
scoreBrowser.scoreBoardName = "overLoadScore";
scoreBrowser.loadScores();
scoreBoard.period = ScoreBoard.ALL_TIME;

```

i am getting the error call to a possibly undefined method ALL\_TIME with reference to static type class ScoreBoard.

although i have provided correct API ID and encryption key.But in the output window i am getting the message. **\[Newgrounds API\] :: No API ID entered in the API Connector component.**

and i have created the scoreBoard which i mentioned earlier but what is this

**\[Newgrounds API\] :: No scoreboards created for this movie.**

# Answer
change the line 1 with

```
var scoreBrowser:ScoreBrowser = new ScoreBrowser();

```

actually i mingled **scoreBrowser** and **scoreBoard**.
> 0 votes

---
Tags: flash, actionscript-3, leaderboards, scoring
---


title: Pygame Scrolling Map

text:
# Question
Title: Pygame Scrolling Map
I have two questions.

I'm working in a rogue-like and I've manage to implement a camera on the player, the camera shows just the players surroundings and is fixed in the side of the windows.

The problem is, when the player is close to the sides of the map there's a black space in the surface. Like so:

# 1) How do I make the camera 'snap' to the side and don't go any further?

To draw the map

* I took the Camera Rect positions \[topleft and bottomright\];
* Converted it to World Position;
* Iterate over it, with a enumerator too;
* Did any lit/visited FOG calcunations with X and Y;
* And Blited in the screen using the enumerators 'i' and 'j'.

Here's the code:

```
topleft = Map.toWorld(camera.rect.topleft)
bottomright = Map.toWorld(camera.rect.bottomright)
for i, x in enumerate(xrange(topleft[0], bottomright[0])):
    for j, y in enumerate(xrange(topleft[1], bottomright[1])):
        tile = mymap.tileAt(x, y)
        object = [obj for obj in Object.OBJECTS if obj.pos == (x,y)]
        if tile:
            lit = field_of_view.lit(x, y)
            visited = field_of_view.visited(x, y)
            graphic = tile.graphic
            if lit:
                color = tile.color
            elif visited:
                color = GRAY
            else:
                color = BLACK
            renderedgraphic = myfont.render(ch, 1, graphic)
            screen.blit(renderedgraphic, Map.toScreen((i + 1, j)))
        if object:
            Draw.drawObject(object[0], Map.toScreen((i + 1, j)))

```

I saw HERE a exemple of this but I couldn't adapt the code to my game because it uses sprites.

I also tried a different approach using just a camera.center position:

in short:

```
class Object():
    def update(self):
        self.relX = self.x - camera.x
        self.relY = self.y - camera.y

class Camera(Object):
    def update(self):
        self.x = self.relX = PLAYER.x
        self.y = self.relY = PLAYER.y

def MapDraw()
    for x in xrange(mymap.width):
        for y in xrange(mymap.height):
            ... # do fov stuff
            tile = Tile.At(x, y)  # get tile instance
            if tile:
                tile.update() # update it's relative position
                screen.blit(renderedgraphic, (tile.relX * TILESIZE, tile.relX * TILESIZE)) # blit the postion to it's relative position

```

This is what happens:

which leads to the next question:

# 2) Is there a better way to create a camera than using this 'hack' of enumerating?

# EDIT: Answer

So after some struggles I tried the old, print whatever I had and found out that I could use the camera.x and camera.y for this.

first I check the distace between camera.x and the optional position in the sides, It was 3 for up and down, 7 to sides.

Then a couple of if-statements fixed this. But since *int*'s aren't very consitent depending on mapsize, cameraview, I found that the camera.rect width and height divided by 2 in world position was the same as (7,3) I was looking for.

Anyway, here's the code for the camera.

```
def update(self):
    self.x, self.y = PLAYER.pos # center camera on player

    self.size = Map.toWorld((camera.rect.width, camera.rect.height)) ## get the ScreenSize of the rect and convert to World Position
    self.size[0] /= 2 # divided each one by two, because the player is in the center.
    self.size[1] /= 2

    if self.x < self.size[0]:  # right
        self.x = self.size[0]
    if self.y < self.size[1]: # up
        self.y = self.size[1]
    if self.x + self.size[0] > mymap.width: # left
        self.x = mymap.width- self.size[0]
    if self.y + self.size[1] > mymap.height: # down
        self.y = mymap.height-self.size[1]

    self.rect = pygame.Rect((self.x * TILESIZE) - CAMERA_WIDTH / 2,
                            (self.y * TILESIZE) - CAMERA_HEIGHT / 2, CAMERA_WIDTH, CAMERA_HEIGHT) # updated the rect

```

Thanks Tyyppi\_77, even tho you provided a small answer, the way you phrased it was just right for me to get it.

# Answer
1) You could make sure that the topleft of the camera would never be smaller than the topleft of the map. And then also check that the bottomright of the camera is never bigger than the bottomright of the map. That should do the trick.

2) Your way seems okay, but camera movement is often acomplished by offsetting the rendered tiles by some varying amount.

I hope this helps.
> 1 votes

---
Tags: camera, pygame
---


# Question
Title: Should all primitives be GL_TRIANGLES in order to create large, unified batches?
Optimizing modern OpenGL relies on aggressive batching, which is done by calls like glMultiDrawElementsIndirect. Although `glMultiDrawElementsIndirect` can render a large number of different meshes, it makes the assumption that all these meshes are made of the same primitives (eg. `GL_TRIANGLES`, `GL_TRIANGLE_STRIP`, `GL_POINTS`).

In order to most efficiently batch rendering, is it wise to force everything to be `GL_TRIANGLES` (while ignoring possible optimizations with `GL_TRIANGLE_STRIP` or `GL_TRIANGLE_FAN`) in order to make it possible to group more meshes together?

This though comes from reading the Approaching Zero Driver Overhead slides, which suggests to draw *everything* (or, presumably, as much as possible) in a single `glMultiDrawElementsIndirect` call.

# Answer
> 3 votes
You don't *need* that fancy `glMultiDrawElementsIndirect`, you can just use `glDrawArraysInstanced`.

Batching is just about lowering draw calls as much as possible.

Triangle strips and triangle fans are used to lower your bandwidth. This means that by using a more memory efficient representation of geometry, you can send less data to the GPU. Please note that this does not mean you send less batches, it just means that your batches can be smaller.

In general for hobbyists and the like draw calls are quite likely going to be the major performance bottleneck in your game, if you have any performance problems at all. I don't think it would be very common for many games to require bandwidth optimizations.

However, as a programmer it might make it simpler for you to lower your draw call count (batch count) if your meshes are all in a similar format.

---
Tags: opengl, 3d, gpu
---


# Question
Title: Obtain linear depth values on FBO and deal with small differences
I've a render target on which I have both a color and a depth attachment. In a second pass I need to run a filter whose width depends on the derivative and values of the depth.

Now, if I try, in the second pass where I'm accessing the texture on which I rendered on previously, to display the depth information all I have is a grey blotch:

https://i.stack.imgur.com/yyi1m.jpg (Don't pay attention to background, I'm showing just non-background values)

Before displaying it I modify it by:

```
float depthValue = texture(depthTexture, uv);
depthValue =(depthValue - 0.1)/0.9;

```

as my near clip is 0.1 and far one is 1.0

Instead, if I run the program with gDEBugger and look at the content of the depth texture what I see is a much cleaner result:

https://i.stack.imgur.com/jYlL4.jpg

Why what I see is totally different? How gDEBugger show the values? Are the value I fetch from the depth texture wrong? Should I render depth values differently?

Moreover, the width of the kernel doesn't really change as it is computed based on depth value and depth derivatives and those two are practically identical, at least judging from what I see. Is there a way to make these differences more marked?

Sorry if it's a dumb question. Thank you.

# Answer
> 1 votes
You are aware that when you sample the depth buffer, what is returned is in ***window-space***, right?

That is the final coordinate space OpenGL transforms into. After projection, GL applies the viewport transformation from NDC -\> window-space, part of which includes depth range. Traditionally, window-space Z is clamped \[**0**,**1**\] and the full range is used; thus **0** is the nearest point and **1** is the farthest.

Your discussion of the near plane at **0.1** and far plane at **1.0** leads me to believe you are discussing a different coordinate space (for instance, if you defined those values in your projection matrix then they are measured in eye-space). In window-space, given the default depth range your near plane is actually **0**.

---
Tags: opengl, depth-buffer
---


title: GA - Genetic Algorithm for Enemy

text:
# Question
Title: GA - Genetic Algorithm for Enemy
So I'm starting a project which aims to make a good AI for my game monsters.

So far I have set up the GA and got some results.

There's two genes, with one chromosome each.

The monster either 'attacks on sight' or 'flee on sight' depending on the gene it got. The fitness function is based upon time alive and the crossover is just eliminating the worst gene.

As expected the 'flee on sight' gene got better result.

What I'm here to ask is what are some good uses of GA in developing AI. Which genes/chromosome/fitnessfunction/crossover should I implement in order to have a challenging AI.

The game is a rogue-like, it's still pretty simple, not much added, so I can make the game around the GA instead of the other way around.

This may be a too broad question, but bear in mind that I don't have any experience in gamedev and AI as a whole.

# EDIT:

To make this question a bit more narrow.

Since my fitness function is just 'survive' it's quite obvious that all the enemy generations would get better at fleeing. So,

What should I put in consideration to a good fitness function.

Damage to the player is also quite one-way solver, a monster-healer which doesn't have any attack power would drop his staff and punch the player.

The perfect fitness function for me should translate to 'make the player struggle', but I don't know what that would mean in the game terms, and specially code terms.

# Answer
I think you have a good start. You certainly have your GA infrastructure in place. Now you need to expand and tweak. You also seem to be missing the part about random new genes, which is important.

I think, at a high level, you need to figure out what kind of actions you want your AI to take. Attacking and fleeing, are they enough?

Since you have a roguelike, I would suggest also incorporating the concept of "damage done to the player" into your fitness function.

The problem with these two chromosomes is that you get an either-or. Instead, you need something with a more range/spectrum. I would try something like "flee after N turns" or "flee when you reach N% health." You can add other ones that incorporate special attacks at certain points.
> 1 votes

# Answer
I think the parameter you are looking for is total number of player deaths in the vicinity of this monster devided by the number of monster deaths (\[area kills\]/\[deaths\]). This means that monsters will run if they know they can't win and will work together to kill of the players rather then just focus on damage output. Note you have a healer so you might want to give him genetic code so that he can heal other monsters, are you going to add more low level genes as well (movement patterns ext.) these could allow monsters to show some really interesting behaviour.

A bit of advice: if you use this method you are going to want to get a large number of real players to let the AI learn form, so why not simply let the game report back which monster with what DNA had players die nearby. If you then automatically process these results you won't have to manually update the game yet the monsters will react to a sort of metagame.
> 0 votes

---
Tags: algorithm, ai
---


title: Volumetric Lighting projects models

text:
# Question
Title: Volumetric Lighting projects models
I've been trying to implement Volumetric Lighting using the code from this tutorial but I've run into some issues, even after basically copypasting the shader code.

I'll just show you what's going wrong.

As you can see, the models seem to be "projected" in the space. At first I tried tinkering with the various variables that the shader requires, but to no avail. In the screenshot I used 0.5f for the decay, exposure, weight and density, with a sample amount of 64.

Any ideas on what might be causing this?

Draw method:

```
    public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
    {
        base.Draw(gameTime, spriteBatch);

    //Set the rendertarget to draw the Blinn-Phong shaded scene to
        GraphicsDevice.SetRenderTarget(renderTarget);
        GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);

        Material material = new Material();
        material.DiffuseColor = Color.Red;
        material.AmbientColor = Color.Red;
        material.AmbientIntensity = 0.2f;
        material.SpecularColor = Color.White;
        material.SpecularIntensity = 2.0f;
        material.SpecularPower = 25.0f;

    //Draw all the models
        foreach (ModelData m in models)
        {
            ModelMesh mesh = m.Model.Meshes[0];
            Effect e = mesh.Effects[0];

            e.CurrentTechnique = e.Techniques[m.Technique];
            material.SetEffectParameters(e);
            this.camera.SetEffectParameters(e);
            e.Parameters["World"].SetValue(world * m.Transform);
            e.Parameters["WorldInverseTransposed"].SetValue(Matrix.Transpose(Matrix.Invert(world * m.Transform)));
            e.Parameters["CameraEye"].SetValue(new Vector4(this.camera.Eye, 0));
            // TODO: LightSource Color + Intensity
            e.Parameters["LightSources"].SetValue(lightPositions);

            mesh.Draw();
        }

    //Restore the rendertarget to the backbuffer and clear it.
        GraphicsDevice.SetRenderTarget(null);
        GraphicsDevice.Clear(Color.Black);

    //Pass the standard variable to the spriteBatch vertex shader.
    //The vertex shader isn't used (for as far as I can tell at least) but because the standard
    //vertex shader for spriteBatch is compiled in 2_0 and the God Ray shader in 3_0 I had to implement it
    //manually in order to compile it in 3_0.
        Matrix projection = Matrix.CreateOrthographicOffCenter(0,
        GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, 1);
        Matrix halfPixelOffset = Matrix.CreateTranslation(-0.5f, -0.5f, 0);
        postProcessing.Parameters["MatrixTransform"].SetValue(halfPixelOffset * projection);

    //Setup all the required data for the shader
        postProcessing.CurrentTechnique = postProcessing.Techniques["Technique1"];
        Vector3 lightPosition = Vector3.Transform(lightPositions[0], world * camera.ViewMatrix * camera.ProjectionMatrix);
        postProcessing.Parameters["lightPosition"].SetValue(new Vector2(lightPosition.X, lightPosition.Y));
    postProcessing.Parameters["Tex"].SetValue(renderTarget);
        postProcessing.Parameters["exposure"].SetValue(0.5f);
        postProcessing.Parameters["decay"].SetValue(0.5f);
        postProcessing.Parameters["weight"].SetValue(0.5f);
        postProcessing.Parameters["density"].SetValue(0.5f);

    //Draw the renderTarget to the screen at the size of the viewport so it fits the screen
        spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, SamplerState.PointWrap, DepthStencilState.Default, RasterizerState.CullNone, postProcessing);
        spriteBatch.Draw(renderTarget, new Rectangle(spriteBatch.GraphicsDevice.Viewport.X, spriteBatch.GraphicsDevice.Viewport.Y, spriteBatch.GraphicsDevice.Viewport.Width, spriteBatch.GraphicsDevice.Viewport.Height), Color.White);
        spriteBatch.End();

    //Restore some of the changes spriteBatch.Begin() made to the graphics device so the 3D render won't break
        GraphicsDevice.BlendState = BlendState.Opaque;
        GraphicsDevice.DepthStencilState = DepthStencilState.Default;
        GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;
    }

```

Shader:

```
sampler2D renderTarget;

#define SAMPLE_AMOUNT 64

Texture2D Tex;
float2 lightPosition;
float exposure;
float decay;
float weight;
float density;

SamplerState State = sampler_state
{
    Texture = <Tex>;
    MipFilter = Point;
    MinFilter = Linear;
    MagFilter = Linear;
    AddressU = Wrap;
    AddressV = Wrap;
};

float4x4 MatrixTransform;

//The default vertex shader of the spriteBatch, implemented manually so it can be compiled in 3_0
void SpriteVertexShader(inout float4 color    : COLOR0,
                        inout float2 texCoord : TEXCOORD0,
                        inout float4 position : SV_Position)
{
    position = mul(position, MatrixTransform);
}

//Copypasted from the tutorial, only changed some variable names
float4 main(float2 texCoord : TEXCOORD0) : COLOR0
{
  // Calculate vector from pixel to light source in screen space.
   half2 deltaTexCoord = (texCoord - lightPosition.xy);
  // Divide by number of samples and scale by control factor.
  deltaTexCoord *= 1.0f / SAMPLE_AMOUNT * density;
  // Store initial sample.
   half3 color = tex2D(State, texCoord);
  // Set up illumination decay factor.
   half illuminationDecay = 1.0f;
  // Evaluate summation from Equation 3 NUM_SAMPLES iterations.
   for (int i = 0; i < SAMPLE_AMOUNT; i++)
  {
    // Step sample location along ray.
    texCoord -= deltaTexCoord;
    // Retrieve sample at new location.
   half3 sample = tex2D(State, texCoord);
    // Apply sample attenuation scale/decay factors.
    sample *= illuminationDecay * weight;
    // Accumulate combined color.
    color += sample;
    // Update exponential decay factor.
    illuminationDecay *= decay;
  }
  // Output final color with a further scale control factor.
   return float4( color * exposure, 1);
}

technique Technique1
{
    pass Pass1
    {
    VertexShader = compile vs_3_0 SpriteVertexShader();
        PixelShader = compile ps_3_0 main();
    }
}

```

# Answer
Keep in mind that this effect only works well if you are facing the light source because essentially it is the lightsource which you have to do a radial blur on. In your scene the light is neither facing the camera nor is the lightsource visible itself (or maybe just out of the view frustum). For the best results you have to render your light volume with colors on and the rest of your scene black so that solid objects will block incoming light (their colour value is not accumulated into the blur).

By the way, I use 35,0.90f,0.2f,0.999f,0.2f values for NUM\_SAMPLES,Density,Weight,Decay,Exposure parameters with the same effect and it looks quite convincing with the rendering technique described above.
> 0 votes

---
Tags: xna, 3d, lighting, volumetric-light
---


# Question
Title: Convert Screen coords to World Coords LIBGDX
I'm working on a tile based platformer game in libgdx. I'm having trouble getting the actual touch input coordinates when the aspect ratio of device is different from the virtual fixed aspect ratio that I'm working on. I'm using a virtual resolution of 480x800. All the rendering work and camera work is being done in GameRenderer class and the input is being handled in InputHandler class. I've tried implementing the camera.unproject() method but it won't do any good. I've added the unproject method in GameRenderer class since my camera is defined here. Then I've sent the screen touch coords from the InputHandler class to the GameRenderer class and returned the converted coords back to InputHandler.

I'm posting the relevant code from both classes.

GameRenderer:

```
public class GameRenderer
{
    public static OrthographicCamera cam;
    private ShapeRenderer shapeRenderer;
    private SpriteBatch batcher;
    private static Player player=GameWorld.getPlayer();

    private static final int VIRTUAL_WIDTH = 800;
    private static final int VIRTUAL_HEIGHT = 480;
    private static final float ASPECT_RATIO = (float)VIRTUAL_WIDTH/(float)VIRTUAL_HEIGHT;
    private Rectangle viewport;
    public static Vector2 crop = new Vector2(0f, 0f);
    public static float scale = 1f;
    public static int Case=0;
    public static float width;
    public static float height;
    public static float w;
    public static float h;

    public GameRenderer(GameWorld world)
    {
        cam = new OrthographicCamera();
        cam.setToOrtho(true, 800, 480);
        batcher=new SpriteBatch();
        batcher.setProjectionMatrix(cam.combined);
        shapeRenderer = new ShapeRenderer();
        shapeRenderer.setProjectionMatrix(cam.combined);
    }

    public void render()
    {
        cam.update();
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

        height=Gdx.graphics.getHeight();
        width=Gdx.graphics.getWidth();

        float aspectRatio = (float)width/(float)height;

        if(aspectRatio > ASPECT_RATIO)
        {
            scale = (float)height/(float)VIRTUAL_HEIGHT;
            crop.x = (width - VIRTUAL_WIDTH*scale)/2f;
            Case=1;
        }
        else if(aspectRatio < ASPECT_RATIO)
        {
            scale = (float)width/(float)VIRTUAL_WIDTH;
            crop.y = (float)(height - VIRTUAL_HEIGHT*scale)/2f;
            Case=2;
        }
        else
        {
            scale = (float)width/(float)VIRTUAL_WIDTH;
        }

        w = (float)VIRTUAL_WIDTH*scale;
        h = (float)VIRTUAL_HEIGHT*scale;

        viewport = new Rectangle(crop.x, crop.y, w, h);

        Gdx.gl.glViewport((int) viewport.x, (int) viewport.y, (int) viewport.width, (int) viewport.height);

        switch(GameWorld.state)
        {
            case Running: renderRunning(); break;
            case GameOver: renderGameOver(); break;
            case Paused: renderPaused(); break;
            default: break;
        }

    }

    public static Vector3 unprojectCoords(Vector3 coords)
    {
        cam.unproject(coords);
        return coords;
    }

}

```

InputHandler:

```
public class InputHandler implements InputProcessor
{

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button)
    {

        Vector3 coords=new Vector3(screenX,screenY,0);
        Vector3 coords2=GameRenderer.unprojectCoords(coords);

        screenX=(int) coords2.x;
        screenY=(int) coords2.y;

        switch(GameWorld.state)
        {
            case Running:
            {
                if(GameRenderer.jumpButton.isTouchDown((int)screenX, (int)screenY))
                {
                    if(player.isJumped() == false)
                    {
                        player.jump();
                        if(!GameWorld.soundMuted) AssetLoader.jump.play(AssetLoader.SOUND_VOL);
                    }

                }

        return false;
    }

    @Override
    public boolean keyDown(int keycode)
    {
        switch(GameWorld.state)
        {
            case Running:
            {
                if(keycode==Keys.SPACE)
                {
                    if(player.isJumped() == false)
                    {
                        player.jump();
                        if(!GameWorld.soundMuted) AssetLoader.jump.play(AssetLoader.SOUND_VOL);
                    }
                }

                if(keycode==Keys.LEFT)
                {
                    leftDown=true;
                }

                if(keycode==Keys.RIGHT)
                {
                    rightDown=true;
                }

                if(keycode==Keys.CONTROL_RIGHT)
                {
                    player.shoot();
                }
                break;
            }

            default: break;
        }

        return false;
    }

}

```

# Answer
Try using this `Camera:unproject` method:

`unproject(Vector3 screenCoords, float viewportX, float viewportY, float viewportWidth, float viewportHeight)`

from the documentation:

> Function to translate a point given in screen coordinates to world space. It's the same as GLU gluUnProject, but does not rely on OpenGL. The x- and y-coordinate of vec are assumed to be in screen coordinates (origin is the top left corner, y pointing down, x pointing to the right) as reported by the touch methods in Input. A z-coordinate of 0 will return a point on the near plane, a z-coordinate of 1 will return a point on the far plane. This method allows you to specify the viewport position and dimensions in the coordinate system expected by GL20.glViewport(int, int, int, int), with the origin in the bottom left corner of the screen.
> 6 votes

---
Tags: libgdx, coordinates, screen
---


# Question
Title: Multiple clicks required before listener is called
I have a screen with multiple stages (pre-game, game, pause) and on the game stage I have a pause button. This is implemented as:

```
public class PauseButton extends Actor {
    private NumberzGame m_game;
    private TextureRegion m_pauseButton;
    private int m_buttonSize;

    public PauseButton(NumberzGame game, Stage stage, int size) {
        super();

        m_game = game;
        m_buttonSize = size;
        m_pauseButton = createPauseButton();

        setWidth(m_buttonSize);
        setHeight(m_buttonSize);
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        Color color = getColor();
        batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
        batch.draw(m_pauseButton, getX(), getY());

        super.draw(batch, parentAlpha);
    }

    private TextureRegion createPauseButton() {
        Pixmap map = new Pixmap(m_buttonSize, m_buttonSize, Format.RGBA8888);
        map.setColor(ColorUtils.colorFromHex(NumberzGame.COLOR_BACKGROUND));
        map.fill();

        int radius = (m_buttonSize / 2) - 4;
        map.setColor(ColorUtils.colorFromHex(NumberzGame.COLOR_SOUND_BUTTON_BACKGROUND));
        map.fillCircle(m_buttonSize / 2, m_buttonSize / 2, radius);
        map.setColor(ColorUtils.colorFromHex(NumberzGame.COLOR_SOUND_BUTTON));

        int width = 2 * radius - 10;
        int height = width;
        int xpos = (m_buttonSize - width) / 2;
        int ypos = (m_buttonSize - height) / 2;

        Pixmap pause = m_game.getAssets().get(NumberzGame.ID_PAUSE_PIXMAP, Pixmap.class);
        map.drawPixmap(pause, 0, 0, pause.getWidth(), pause.getHeight(), xpos, ypos, width, height);

        TextureRegion result = new TextureRegion(new Texture(map));
        map.dispose();

        return result;
    }
}

```

In the screen class I have the following code to add the pause button to the game stage:

```
m_pauseButton = new PauseButton(getGame(), m_gameStage, NumberzGame.PLAY_BUTTON_WIDTH);
m_pauseButton.setX(width - NumberzGame.PLAY_BUTTON_WIDTH - NumberzGame.MARGIN);
m_pauseButton.setY(height - NumberzGame.PLAY_BUTTON_WIDTH - NumberzGame.MARGIN);
m_pauseButton.addListener(new ClickListener() {
    @Override
    public void clicked(InputEvent event, float x, float y) {
        m_state = GameState.PAUSED;
        getGame().getWorld().pauseWorld(true);
    };
});
m_gameStage.addActor(m_pauseButton);

```

When I run the application the first click on the pause button properly pauses the game and after I resume the game, I need to press the pause button twice to have it trigger.

What am I missing here?

# Answer
> 1 votes
First thing: I see that you are using a stage from scene2D. A better way to go about this pause button is to use the scene2Dui class TextButton. You can customize it with a pixmap to make it look pretty much the same.

As for your current problem, I am speculating that the problem might be that the ClickListener doesn't detect the mouse release because you are switching screens simultaneously. Try using a ChangeListener.

---
Tags: libgdx
---


# Question
Title: Re-using one texture for multiple OpenGL Quads
I've been looking over my code and I'm just wondering, when I set a texture for say, 20 quads that need to use the same texture, it seems as though I'm creating a new texture each time...... surely this isn't efficient?

How can I make sure that 20 quads that use the same texture do just that, use only 1 rather than creating 20 copies of it?

I just can't work out how I can do this. I know I can change the texID after applying the texture so that all quads that use the same texture, will have the same Texture ID, but this isn't really the issue I'm facing.

Of course, I may be completely misunderstanding how OpenGL deals with textures and my code may be OK :-/

**Code:**

```
    public void setTexture(GLSurfaceView view, Bitmap imgTexture){
        this.imgTexture=imgTexture;
        //Create program from Utils class
        iProgId = Utils.LoadProgram(strVShader, strFShader);
        //Return location of u_basemap
        iBaseMap = GLES20.glGetUniformLocation(iProgId, "u_baseMap");
            //Return location of attribute variables
        iPosition = GLES20.glGetAttribLocation(iProgId, "a_position");
        iTexCoords = GLES20.glGetAttribLocation(iProgId, "a_texCoords");
        //Return usable texture ID from Utils class
                texID = Utils.LoadTexture(view, imgTexture);

}

```

And....

```
public static int LoadTexture(GLSurfaceView view, Bitmap imgTex){

    //Array for texture
    int textures[] = new int[1];
    try {
        //Return texture name in textures Array
        GLES20.glGenTextures(1, textures, 0);
        //Bind textures
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0]);
        //Set parameters
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
        GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);

        //Apply the texture to the image loaded
        GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, imgTex, 0);

        //clamp the texture
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T,GLES20.GL_CLAMP_TO_EDGE);
    } catch (Exception e){
    }
    //Increase texture count by one
    textureCount++;
    return textures[0];
}

```

**Edit**

I've attempted the suggestion below (just calling `glBindTextures()`) however, I'm not having any luck. Clearly I'm not understanding this correctly.

Lets say I have 2 sprites, Object1 and Object2.

I call the following:

```
object1.setTexture(this, myAtlasTexture); //Calls setTexture (See above)

```

This works and sets the texture on this sprite, so I can now draw it.

Now I want object2 to use the same texture. So I don't want to call this again and create a new texture (**I believe this is a bad idea**) - I simply want to use the texture that was previously created when I called `setTexure` on object1.

So, instead of calling setTexture on object 2, I do the following:

```
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureIDOfObject1);

```

(Note `textureIDOfObject1` is just that, I just query object1 to obtain its texture ID).

# Answer
So I worked out how to do this:

Lets say I have `object1`, `object2`, `object3` etc.... and these objects all use a common texture.

I call my `setTexture` method (as detailed in my question) for `object1` and then, instead of calling `setTextures` on the remaining objects, I created a new method and called that instead.

```
public void bindExistingTexture(int textureToBind){

        //As before
        iProgId = Utils.LoadProgram(strVShader, strFShader);
        iBaseMap = GLES20.glGetUniformLocation(iProgId, "u_baseMap");
        iPosition = GLES20.glGetAttribLocation(iProgId, "a_position");
        iTexCoords = GLES20.glGetAttribLocation(iProgId, "a_texCoords");

        //Here, instead of creating and loading another texture, we simply bind an existing texture
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureToBind);
        //And update the texID value used in rendering methods
        texID = textureToBind;

}

```

So, it's pretty much the same method, but instead of:

```
texID = Utils.LoadTexture(view, imgTexture);

```

I simply re-bind an existing texture and update the local variable to match.

My call would look something like this:

```
    object1.setTexture(this, myAtlasGraphic);
    object2.bindExistingTexture(object1.texID);

```

This has greatly reduced my app loading time.
> 2 votes

---
Tags: java, textures, opengl-es2
---


# Question
Title: Animate from end frame of one animation to end frame of another Unity3d/C#
So I have two legacy FBX animations; Animation A and Animation B.

What I'm looking to do is to be able to fade from A to B regardless of the current frame A is on.

Using animation.CrossFade() will play A in reverse until it reaches frame 0, then play B forward.

What I'm looking to do is blend from the current frame of A to the end frame of B. Probably via some sort of lerp between the facial position in A and the facial position in the last frame of B.

Does anyone know how I might be able to accomplish this? Either via a built in function or potentially lerping of some sort?

EDIT: Does anyone perhaps know of a way to read bone positions of an animation at a certain frame? Perhaps if I could read that I could fake animations by doing Vector3 lerps.

# Answer
So what I ended up doing was using AnimationUtility.GetAllCurves(clip) to cache animation curve data from each AnimationClip in the editor. Once you serialize this data you can build to whatever platform you want.

What you do is take the animation curve data for a given animation, and using the key.time and key.value Keyframe variables create a new AnimationClip using only the frame you want to blend from and a second AnimationClip using only the frame of another animation that you want too blend to.

You then use animation.AddClip(); on this temporary clip, then crossfade between the two. Giving you a seamless fade from any point of one animation to any point in another.

The code for this project is private. However, if anyone else having this problem needs further help or guidance feel free to contact me at tim@terabytetim.com
> 0 votes

# Answer
You need to make 'dummy' animations that are just the last frames of each animation, and blend between those.

The animation system will try to play an animation if it is not playing, so if you just want to blend between the last frames of two animations, you need the animations to be loops only containing the last frame.
> 0 votes

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


title: Adapting DirectX samples to SlimDX

text:
# Question
Title: Adapting DirectX samples to SlimDX
I'm trying to learn DirectX and SlimDX but I'm having a terrible time getting started.

I'm taking the Triangle tutorial and trying to add color and transformations.

Starting with controlling color, I've updated the .fx file to the following:

```
cbuffer cbPerObject
{
    float4x4 gWVP;
};

struct vsInput
{
    float4 positionLS   : POSITION;
    float4 color        : COLOR;
};

struct vsOutput
{
    float4 positionCS   : POSITION;
    float4 color        : COLOR;
};

struct psInput
{
    float4 positionCS   : POSITION;
    float4 color        : COLOR;
};

vsOutput VShader(vsInput input)
{
    vsOutput output;

    output.positionCS = input.positionLS; //mul(position, gWVP);
    output.color = input.color;

    return output;
}

float4 PShader(psInput input) : SV_TARGET
{
    return input.color;
}

```

And the code updates limited to the following lines:

```
// create test vertex data, making sure to rewind the stream afterward
var vertices = new DataStream(16 * 6, true, true);
vertices.Write(new Vector4(0.0f, 0.5f, 0.5f, 1f));  // What is W (of POSITION)
vertices.Write(new Color4(.8f, 1f, 0f, 0f));        // What should it's value be?
vertices.Write(new Vector4(0.5f, -0.5f, 0.5f, 1f));
vertices.Write(new Color4(.8f, 0f, 1f, 0f));
vertices.Write(new Vector4(-0.5f, -0.5f, 0.5f, 1f));
vertices.Write(new Color4(.8f, 0f, 0f, 1f));
vertices.Position = 0;

// create the vertex layout and buffer
// Thanks to Mārtiņš Možeiko for fixing these next lines
var elements = new[] {
    new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
    new InputElement("COLOR", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0)
};

var layout = new InputLayout(device, inputSignature, elements);
var vertexBuffer = new SlimDX.Direct3D11.Buffer(device,
    vertices,
    (int)vertices.Length,
    ResourceUsage.Default,
    BindFlags.VertexBuffer,
    CpuAccessFlags.None,
    ResourceOptionFlags.None,
    0);

```

After a few other attempts at using SV\_POSITION, COLOR, and SV\_TARGET in the wrong spots, it finally executes without error; **however, the triangle does not appear.**

1. Please help me get the triangle working again with this updated shader.
2. Sample code for SetConstantBuffer() for populating gWVP for standard perspective.

Thanks!

# Answer
> 2 votes
elements array sould look like this:

```
// create the vertex layout and buffer
var elements = new[] {
    new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
    new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
};

```

or

```
// create the vertex layout and buffer
var elements = new[] {
    new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
    new InputElement("COLOR", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0)
};

```

The last element is not an index of element. It is offset in bytes from beginning of vertex.

# Answer
> 1 votes
What helped me was changing the InputElement format of the Position.

From

```
Format.R32G32B32A32_Float

```

to

```
Format.R32G32B32_Float

```

# Answer
> 0 votes
I had same problem and it was caused by a bad stride between vertex elements.

Check your `vertexBufferBinding`:

```
device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new
    VertexBufferBinding(vertexBuffer, 32, 0));

```

---
Tags: c#, shaders, directx11, slimdx
---


# Question
Title: How to determine the visibility of a single vertex, given a viewpoint?
I have a 3D triangle mesh, and I want to know, given a viewpoint (defined by a model, view and projection matrix), if a certain vertex is visible or not.

My approach was to render the mesh using standard software rasterization (I can't use OpenGL/DX), i.e. project all the triangle vertices to screen-space, then loop through each triangle's bounding-box and rasterize/shade the pixels inside the triangle (using barycentric coordinates). I'm also using a z-Buffer here, and the rendering works fine.

To find out if a certain vertex point is visible, my naive idea was then to just project that vertex from 3D to 2D using the same matrices, and comparing the z-value I get for that pixel to the value in the z-Buffer.

However, this approach does not work, I get vertices flagged as visible that should be invisible and vice versa.

I believe this is because of the following: When I render the triangles, I loop over the bounding-box of the triangle and set the color and depth value by interpolating a value between the 3 triangle vertices, using barycentric coordinates. Thus, the depth value written to the z-buffer for a given point (x, y) on screen is a linear combination of the z-value of the 3 vertices that make up the triangle. In contrast to that, when I project the single vertex later, I render the exact point, independent from any triangles, and thus get a different z-value for the same (x, y) location on screen.

Is my assumption on why it is not working correct, and how would I correctly determine the visibility of a vertex in the mesh?

**Update**: Let me clarify what's going on with this picture:

Let's say v0 = (1.1, 1.1), v1 = (6.7, 2.1), v2 = (3.7, 6.7) after projection to screen-space. When rendering/rasterizing the triangle, I have a loop

```
for x = 1 to 7 // from floor(min(v0.x, v1.x, v2.x)) to ceil(max(v0.x, v1.x, v2.x))
    for y = 1 to 7 // same for y
        current_pixel_center = (x+0.5, y+0.5); // we want calculations to use the center of pixels
        alpha = ..., beta = ..., gamma = ...; // calculate the barycentric weights for current_pixel_center
        if all 3 bary. weights > 0 // means the pixel is inside the triangle
            z_value_of_curr_pixel = alpha * v0.z + beta * v1.z + gamma * v2.z;
            // Do the z-test and then draw the pixel at position (x, y), and set the z-buffer at (x, y) to the new value 'z_value_of_curr_pixel'

```

So the pixel at position (1, 1) in my drawing gets some color and z-value based on the barycentric weights calculated for this point, it is close to v0 so probably something like alpha = 0.95, beta = 0.02, gamma = 0.03.

Now, in contrast to that, I am later interested in knowing if the single vertex v0 is visible (I don't have any information about triangles at that point). So I project the vertex v0 which will land at (1.1, 1.1) in screen space and end up with a z-value as well. However this z-value will be different than the one that is in the z-buffer for this pixel, because the z-value in the z-buffer has been calculated using the barycentric weights of the triangle for the middle point of the triangle. So I can't determine if the vertex v0 is visible or not.

To rephrase: The z-value in the z-buffer is from the red dot in the image (produced when rendering the triangle), and it is different from the z-value of the projection of the vertex v0 which is exactly at position v0.

# Answer
> 1 votes
The assumption you've made is that depth is linear in screen space. This is true for orthographic projection. If you're using a perspective projection this assumption no longer holds true for 3 dimensions.

For classic perspective projection you must interpolate the reciprocal of depth in screen space in order to account for the division by the w component that occurs due to the nature of perspective projection. So you need to interpolate 1/depth in screen space. If you need depth at a particular location it can be inverted after interpolation occurs.

Assuming you understand these details then the implementation you described of a depth buffer should work just fine.

# Answer
> 0 votes
Rasterization will never give you precise results because of subpixel inaccuracies like the one you described. You can of course improve accuracy by increasing resolution. You can also bias the result to make either false positives or false negatives more likely.

To get a more accurate answer you can use ray tracing techniques. This will also be slower unless the polygon count is low. You want to cast a ray from the camera to the point and do ray-triangle intersection tests on all triangles. You can reduce the number of triangles to test by using spatial subdivision on the triangles (e.g. a k-d tree).

---
Tags: 3d, rendering, projection, depth-buffer, visibility-determination
---


title: Dialog Title Does Not Fit

text:
# Question
Title: Dialog Title Does Not Fit
I successfully added my own font to the default .json file and it displays, however I get some weird sizing issues. Specifically when I try to create a Dialog. This is what it looks like:
*Ignore the fact that that says "and"*
As you can see, the title does not fit and the button seems a bit big... This is how I create the dialog:

```
Dialog d = new Dialog("Error", RBResources.gameSkin);
        d.add(new Label("You cannot continue and empty game.", RBResources.gameSkin));
        TextButton b = new TextButton("Ok", RBResources.gameSkin);
        d.button(b);
        d.show(this);

```

This is how the skin is initialized:

```
gameSkin = new Skin(Gdx.files.internal("skins/uiskin.json"));

```

All I did to add the font was create the font with Hiero, add it to directory with the .json, and change the BitmapFont file reference from "default.fnt" to "text.fnt" (text is what I called the font).

**EDIT**
I tried changing the font size to 32 (before it was 48) and this is what it gives me:
The title still exceeds the boundaries of the title box. Does that mean, in the .png file containing the different button states and other Drawables, that I have to manually adjust the window Drawable to fit the title or is this a bug?

# Answer
So what I had been thinking has been confirmed: The dialog is built with a single NinePatch so you need to adjust the size of the title bar manually within the .atlas file and .png file.

***EDIT***
This will basically be a little *How to use a JSON file with LibGdx* tutorial.
LibGdx has a very useful Class called `Skin`. It allows you to have a .json file along with a .atlas file and .png image to very easily define the styles used in making `Button`s, `TextButton`s, `Dialog`s, etc.

**LibgGdx Default Skin**

1. JSON File
2. ATLAS File
3. ATLAS Image Pack
4. Font File
5. Font Image

**How the JSON File Works**
The JSON file contains a listing of different class types and their parameters. In this question's case we'll look at the `Dialog` style. Because the dialog is a subclass of `Window` it uses a `WindowStyle` (not all subclasses of other classes do this), so we have to look through the JSON file for `WindowStyle`.

```
com.badlogic.gdx.scenes.scene2d.ui.Window$WindowStyle: {
default: { titleFont: default-font, background: default-window, titleFontColor: white },
dialog: { titleFont: default-font, background: default-window, titleFontColor: white, stageBackground: dialogDim }
},

```

As you can see, dialog is the is the style type used for `Dialog`s, while default is used for regular `Window`s. Most of the attributes are self-explanatory, but what you need to know is that the fonts are always declared within the JSON file, at the top. You can add as many as you like, just make sure to include the .fnt file and .png image of the font within the same folder as the JSON file, and correctly reference them. You can easily make fonts using `BitmapFont` generators like Hiero which can be found here: https://github.com/libgdx/libgdx/wiki/Hiero. Colors are also created at the top of the JSON file, just underneath the fonts. You can create as many as you like. `stageBackground` is the color that will cover the rest of the stage while the dialog is shown. In this case it is `dialogDim` which is defined as a `TintedDrawable` in the JSON file. The last attribute is a reference to an image in the ATLAS Image Pack.

**How the ATLAS File Works**
The ATLAS file is basically a collection of references to `TextureRegion`s within the ATLAS image pack. Many of them are self-explanatory and the rest can be understood through a bit of trial and error, but for now we'll focus on the references to the dialog box pieces. `default-window` references to this bit in the ATLAS file:

```
default-window
  rotate: false
  xy: 1, 20
  size: 27, 29
  split: 4, 3, 20, 3
  orig: 27, 29
  offset: 0, 0
  index: -1

```

These fields can be a little confusing and I don't understand them all either, but what you need to know is that `rotate` should always remain false, unless you know when it shouldn't. `xy` is the x and y location, *in pixels* of the `TextureRegion` within the ATLAS image pack. `size` is the x size and y size, *in pixels*. `split` is how the `TextureRegion` should be split (not applicable for all ATLAS references), you find out more about how those numbers work here: https://github.com/libgdx/libgdx/wiki/Ninepatches. `orig` is, as far as I know, always the same as `size`. `offset` should always remain at 0, 0 unless you have a reason of having the region be offset from the `xy` location at the start. And an `index` of -1 means that this region is within the same ATLAS image pack as the rest of the regions.
**How to Use This**
Now you can easily make your own modifications. Just find the style you wish to add your own to, copy the syntax of the one you want to change (or change the default directly), add your own name for it, and add your own ATLAS references. Within the ATLAS file and image pack you can also add your own regions. You can likely also add your own attributes for different classes other than styles, because the Skin class seems to be a light wrapper on top of a JSON reader that allows styles to be easily read.
I hope this was all understandable :)
> 5 votes

---
Tags: java, libgdx, fonts
---


# Question
Title: What are the reasons for MMOs to have level caps?
In many MMOs players character progression is artificially capped, e.g. by level 60 or 90 or 100 or whatever. Why do MMOs have these level caps in the first place? Why not just allow characters to continue to arbitrary levels with a mathematically designed leveling system that keeps the leveling experience interesting and endless?

*Answers to this question may help us to see the reason behind the feature and decide **if** and **how** this should be implemented in our MMOs.*

# Answer
> 6 votes
This is not a problem specifically related to MMOs; single-player games often have level caps as well, and the fundamental reason for introducing them is the same.

It's much easier and more practical to balance for a *fixed* range of progression than an *infinite* one.

You postulate that one could just implement a "mathematically designed leveling system that keeps the leveling experience interesting and endless" but this is *much harder* to do than it is to say (assuming you still want "fun"). Essentially all this is doing is finding power curve that isn't *too* shallow or *too* steep and using that curve to scale a player's statistics.

This is not likely to remain interesting for a long time. It lacks variety. It's just numbers getting increasingly bigger, and while that may entertain a few people for a little while you will eventually reach the point where the numbers are too big to be effectively comprehensible (42,132,927,189,100 strength) and don't have an appreciable impact (you might deal 92,101,626,001,292 damage per second at level 67,192 but enemies your level have a similarly inflated HP score, so it still takes you the same amount of time to actually kill them as a level 67 player).

Players are usually engaged by progression that introduces *variety* and *choice* (for example in the array of abilities they can chose from). A secondary effect in the introduction of choice is the ability to *plan*, to elect abilities or skills or gear that synergizes with itself in a particular way. While many games end up with some of those synergies organically, at least a good portion of them are initially planned for; it's much harder to ensure that sort of opportunity for fun exists in a system where abilities are randomly-generated and made available.

A system with procedurally-generated progression breakpoints is totally possible. It's hard to tune into something fun, though, because the more procedural variety you introduce the less designer control for fine-tuning you have. This means the designer is often forced to balance against the potential components of an ability set, not the abilities themselves. For a concrete example of such a thing in a small (non-infinite scale), consider the original Guild Wars and its expansion chapters. Each chapter introduced a large new set of skills, and player progression was mainly measured in skills and not level (which was capped at 20). Balancing for that combinatorial explosion was *extremely difficult* and allowed several undesirable, unbalanced (both over and under powered) combinations at times. That's why Guild Wars 2 chose to go with a much more directed and focused system.

A fully-procedural progression breakpoint system would be interesting, but nobody's tried/done it well yet -- and besides, assuming a perfect implementation of such a thing, you wouldn't necessarily need *levels* at all at that point.

---

There is a related discussion, and that is about capping *lower* than you eventually expect to allow (for example, how Diablo 3 initially capped you at 60, and GW2 at 80). This allows you to still design for a fixed range of progression but also expand that range somewhat -- offering new rewards and other such carrots -- to players who purchase expansions at a later day. WoW also does this, of course, but like the above it is not strictly anything to do with MMOs.

# Answer
> 6 votes
It's easier to think about what would happen in absence of a level cap in a generic mmo:

**First Reason:**

Players could become spread across the infinite level range, meaning less interaction between players.

Here's a quote from a study which analyzed a 1,356-million-packet trace of ShenZhou Online, a mid-sized commercial MMORPG:

> Our major findings are as follows...Players who have a higher degree of social interaction tend to participate much longer. This suggests that game companies could increase the “sticki- ness” of games by encouraging, or even forcing, team playing. Furthermore, the duration of group play correlates with a group’s size and the network distance between players.

http://www.researchgate.net/publication/220851577\_Design\_Implications\_of\_Social\_Interaction\_in\_Online\_Games

**Second Reason:**

The second reason is that having vastly overpowered opponents/griefers (also known as killers in Bartle's taxonomy of player types) can lead to frustration, dissatisfaction and abandonment of the game. In the case of PVP MMOS this could happen as newer players are *repeatedly* and *unavoidably* killed by high level characters. In PVE MMOS this could happen as high level characters kill-steal lower level characters.

**Third Reason:**

Players can become tired of randomly generated content. I believe one reason for this is because it's hard to programmatically create differences in kind (extra credits video on youtube) or a longterm storyline/narrative to keep the player interested.

# Answer
> 1 votes
All the other answers are very good but seem to miss one important aspect to level cap.

Reaching the level cap means the start of the end-game.

For example, in World of Warcraft, reaching the level cap meant you would be able to join all the other players with the end-game content like 20/40 player Raids, world boss events, etc.

The 'real' game in these type of MMOs only begins at the level cap, so players can compete equally, and after that only gear/weapons are important, and no longer your base level stats.

# Answer
> -1 votes
i have played wold of warcraft, and other mmorpg's regularly, and the general consensus i usually get when i ask people why a level limit is necessary is:

1. High leveled people killing low level people is to frustrating/unfair for many people.
2. eventually nothing in the game could stand up to your avatar's high level. this creates no challenge, and can turn into a mundane experience. However this could be counteracted by creating enemies so powerful you'd never beat them without help/CO-OP, or insane level grinding.
3. a finite level gives players a sense of accomplishment when they reach that level. it also allows them to go thru the fable'd end game content without worrying about assigning skill points, or racking EXP. (sounds weird i know, but it's what people say.)
4. some people i've talked to( Around 40 or 50) want level cap's to be abolished so there can have something to do. these people are in the minority as most people like the level cap's.
5. Game developers want level cap's to control the flow of a game's progression, (both in long term and short term), and to match players together more easily fo CO-OP play.

That's most of what i've heard,and experienced worth mentioning. hope it helps.

on a side note: im a hardcore gamer and would be very happy if level cap's went extinct. "Hint-Hint"

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


# Question
Title: Loading a stream/asset on Android MonoGame without ContentManager
In the game I am developing, I have created a serializable class that generates a .map file for saving and loading levels. In XNA, this works great using the following code:

```
FileStream fileStream = new FileStream(filePath,
                FileMode.OpenOrCreate);
BinaryFormatter formatter = new BinaryFormatter();
MapInfo data = (MapInfo)formatter.Deserialize(fileStream);

```

Unfortunately, in android it appears that the filePath ends up at the device's root (argument being passed in as "Content/maps"). After some research, I came across this page from xamarin that explains how to properly load assets from the asset folder. However, this action takes place in a separate namespace from my main activity, and so far have not found a way to access the Assets.Open() function.

any other ways to load that asset?

UPDATE: After playing around some more, I ended up trying to pass the Assets property of the main activity down through function calls, loading the file this way:

```
Stream fileStream = androidGame.Assets.Open(filePath);
BinaryFormatter formatter = new BinaryFormatter();
MapInfo data = (MapInfo)formatter.Deserialize(fileStream);

```

SADLY, the file still does not load. Looking at the variables in debug shows the correct address for the activity contained in the variable androidGame, but says Open is an "Unknown member"

**UPDATE WITH WORKING SOLUTION:**

In case anyone comes across file loading issues in Monogame **Android**, this is what I ended up doing:

First, make sure you copy/reference your files in the correct dir of your android build. This should appear somewhere under Assets/Content/yourfile.file or subfolder.

Then, check the properties of the file and select "AndroidAsset" for build options and "Copy if newer" for output.

Finally, open the stream using the Assets property of your main activity. This can be accessed using your Microsoft.Xna.Framework.Game class in this way:

```
Stream fileStream = Game.Activity.Assets.Open(path);

```

Turns out my issue was not the stream itself, but the deserialization which could not open a .dll in android (overlooked that one...). I ended up switching to XML serialization, since the binary serialization is build dependent

# Answer
> 2 votes
I believe you can use TitleContainer.OpenStream in MonoGame for a platform independent way of reading and writing files.

See the XNA documentation for reference:

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.titlecontainer.openstream.aspx

The thing you still have to be careful of is case sensitivity and formatting the path correctly. Otherwise I think it's relatively straightforward.

EDIT: Actually the XNA documentation is pretty sparse so here's an example that should give you the right idea. If your file is in the Content folder and you've set it to Content / Copy if newer in properties.

```
var filePath= Path.Combine(Content.RootDirectory, "FileName.dat");
using(var stream = TitleContainer.OpenStream(filePath))
{
    BinaryFormatter formatter = new BinaryFormatter();
    MapInfo data = (MapInfo)formatter.Deserialize(stream);

    // do your thing here
}

```

---
Tags: xna, c#, android, monogame, xamarin
---


# Question
Title: I don't understand why one of my vbo is overwritten by another
to create a vbo I use this function:

```
    public void loadVBO(){
        vboID = GL15.glGenBuffers();
        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboID);
        GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buf, GL15.GL_STATIC_DRAW);
        // Put the position coordinates in attribute list 0

        GL20.glVertexAttribPointer(0, 4, GL11.GL_FLOAT,
        false,4*4+4*4+4*4+2*4 , 0);
        // Put the color components in attribute list 1
        GL20.glVertexAttribPointer(1, 4, GL11.GL_FLOAT,
        false,4*4+4*4+4*4+2*4 , 4*4);
        GL20.glVertexAttribPointer(2, 4, GL11.GL_FLOAT,
        false,4*4+4*4+4*4+2*4 , 4*4+4*4);
        // Put the texture coordinates in attribute list 2
        GL20.glVertexAttribPointer(3, 4, GL11.GL_FLOAT,
        false,4*4+4*4+4*4+2*4 , 4*4+4*4+4*4);

        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
    }

```

to display a vbo I use this function:

```
    public void displayVBO(){
            GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vboID);
            GL20.glEnableVertexAttribArray(0);
            GL20.glEnableVertexAttribArray(1);
            GL20.glEnableVertexAttribArray(2);
            GL20.glEnableVertexAttribArray(3);
            GL11.glDrawArrays(GL_TRIANGLES, 0, buf.capacity());
            GL20.glDisableVertexAttribArray(0);
            GL20.glDisableVertexAttribArray(1);
            GL20.glDisableVertexAttribArray(2);
            GL20.glDisableVertexAttribArray(3);
            GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
    }

```

So when I call map.loadVBO() and then ocean.loadVBO(), I think the second call overwrite the first vbo I don't know how ...

When I call map.display() and ocean.display(), I have the ocean draw 2 times ....

Thanks.

# Answer
> 1 votes
`GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vboID);`

This line only makes sense if you replace `GL_ELEMENT_ARRAY_BUFFER` with `GL_ARRAY_BUFFER`, since you used `vboID` as an ARRAY\_BUFFER to upload data to it in your `loadVBO` function.

---
Tags: opengl, vbo
---


# Question
Title: Why is my Simplex Noise appearing in four columns?
I'm trying to make a `Texture` out of Simplex noise, but it keeps appearing like this regardless of how big or small `scale` is:

The following code is used to produce the image's color date:

```
private Color[,] GetSimplex() {
    Color[,] colors = new Color[800, 600];

    float scale = colors.GetLength(0);

    for (int x = 0; x < 800; x++) {
        for (int y = 0; y < 600; y++) {
            byte noise = (byte)(Noise.Generate(x / scale, y / scale) * 255);
            colors[x, y] = new Color(noise, noise, noise);
        }
    }

    return colors;
}

```

# Answer
I think it could be one of these three things, or a combination of them (from likely to unlikely)

* There are errors in Noise.Generate()
* X and Y are not random at all and thus poor seed values for the noise
* Truncating the output of Noise.Generate() to a byte reduces entropy. Coincidentally a float has 4 times as much bits as a byte.
> 1 votes

---
Tags: c#, sfml, simplex-noise
---


# Question
Title: Nullpointerexception when loading resources in openGL ES 2.0 Android project
**Overview**

My splash screen starts by display a 'loading' dialogue and then kicks off an **asyncTask** (The loading dialogue is derived from the standard Android View class)

Within the **doInBackground** method of the asyncTask, all of my quads / sprite objects are created and other values set etc.

When the code gets to **onSurfaceCreated**, it loads all of the textures and runs the game.

The texture loading happens in **onSurfaceCreated** because it has to be done on the GL Thread.

Now, on a nice fast tablet, it all works great and it's all very stable. However, when I run it on an old handset, it (intermittently) crashes all over the place with **nullpointerexceptions**.

**Reason**

What's happening is on the slower device, the **asyncTask** is running and (due to the asynchronous nature of it), continues to run in the background while the main code moves on to the **onSurfaceCreate** method of the GLRenderer, there it attempts to apply textures to objects that don't yet exist because the asyncTask is still doing it's business.

**How best to proceed?**

What are some methods I can implement that would allow me to **guarantee** that the async has done it's stuff before attempting to affect any of the objects that it creates?

Is there a way to 'halt' the GLThread until the asyncTask has finished? I've been told in the past to use a separate thread or an async for loading resources, but I'm confused as to how to handle it correctly and keep everything sync'd between it and the GL thread (if "sync'd" is the correct term in this context).

Any help would be appreciated.

**Code example**

*Showing onCreate and doInBackground from Activity Class*

```
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //Request full screen
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        super.onCreate(savedInstanceState);

        //Create a displayMetrics object to get pixel width and height
        metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        width = metrics.widthPixels;
        height = metrics.heightPixels;

        //Create splash-screen object and pass in scaled width and height
        splash = new SplashScreen(MainActivity.this, width, height);

        //Create dialog that will show splash-screen
        loading_dialog = new Dialog(MainActivity.this,android.R.style.Theme_Black_NoTitleBar_Fullscreen);

        //Create and set View
        myView = new MyGLSurfaceView(MainActivity.this);

        //Create a copy of the Bundle
        if (savedInstanceState != null){
            newBundle = new Bundle(savedInstanceState);
        }

        //Create splash object

        goSplash = new DisplaySplash(newBundle);
        goSplash.execute(); //Start asyncTask

        setContentView(layout);

    }

```

*And....*

```
    @Override
    protected Void doInBackground(Void... params) {
        createObjects();
        initialise();
        return null;
    }

```

*Showing onSurfaceCreated from GLRenderer Class*

```
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {

    //Eek! Running before AsyncTask has finished on slower devices! :(
    res.loadResources();
    res.setTextures();
    res.RecycleBitmaps();

}

```

# Answer
You could wait for the `asyncTask` to finish by waiting for it in `onSurfaceCreated` using the get() method. This will be a blocking call though, so you might as well do your loading directly in `onSurfaceCreated` and manually update the progress display after each item is loaded.

But in case you want to keep using `asyncTask` it will go something like this:

```
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {

   goSplash.get();    // waits indefinitely for asyncTask to finish

   // at this point, the asyncTask should be finished, unless an exception
   // was thrown - which you should probably handle :)

   res.loadResources();
   res.setTextures();
   res.RecycleBitmaps();
}

```

You could also use the alternate get() method which allows you to set a timeout for the wait operation, but since you **have to** wait for it to finish it wouldn't serve much purpose.
> 1 votes

---
Tags: java, android, multithreading, loading
---


# Question
Title: How do I procedurally generate level like in Dino Run, or Tiny Wings?
I'm looking to create a game like Dino Run, where I will need to create large slopes for a level, procedurally generated. How do I go about this?

Do I have to make certain predefined pieces of level that I can connect to each other? How do I make this fully procedural?

I'm using Sprite Kit if it makes any difference.

# Answer
You essentially want to experiment with various noise functions, such as Perlin Noise. The various parameters you choose, and how you interpolate the information, will give you vastly different results.

As for how you transform the information into graphics, it'll vary. In Tiny Wings, there's clearly a foreground image that's 'cutout' above the noise function. Additionally a line gets drawn along the function to give the appearance of a border. In Dino Run, since the style is so simple, it's essentially filling the area below the function with a solid colour. Then sprinkle other stuff like trees and rocks around the level with some other noise function.

I don't have experience with Sprite Kit, so I wouldn't know if implementing it that way would be practical; I'd personally write a custom shader to draw it, using OpenGL ES.
> 2 votes

---
Tags: procedural-generation, spritekit
---


# Question
Title: Problem with moving player through a secript by a set distance
I am currently trying to add a sort of "dash"-ability to my sidescroller.

What I try to do, is to let the player press a key where a simple key-press causes the player to move quickly into one direction by a predefined distance. During that dash, the character controller is disabled so the player is not able to cancle the dash itself. after the dash, the character controller is enabled again and the dash ability is disabled, so to say on cooldown. Though the "predefined distance" is what isn't working.

The code for it I have so far is as following. I have a script for choosing the animations and reacting to key Input, this script includes the following in it's Update method ("a" and "d" are set for the Dash). pstats is my object for the variables in the Player-script.

```
        float dashing = Input.GetAxis ("Dash");

    if (Input.GetKey ("a") && pstats.dashUsable)
    {
        pstats.DashLeft();
    }
    if (Input.GetKey ("d") && pstats.dashUsable)
    {
        pstats.DashRight();
    }
    if (!pstats.dashUsable)
    {
        dashing = 0.0f;
    }

```

My Playerscript contains:

```
    public bool dashUsable = true;
public bool dashUsing = false;
public bool attacking = false;

private IEnumerator WaitForNextDash() {
    yield return new WaitForSeconds(1.0f);
    dashUsable = true;
    Debug.Log("WaitForNextDash Done");
}

private IEnumerator WaitForDashToEnd() {
    yield return new WaitForSeconds(1.0f);
    Debug.Log ("dashUsable being changed");
    dashUsable = false;
    dashUsing = false;
    attacking = false;
    controller.enabled = true;
    StartCoroutine (WaitForNextDash ());
    Debug.Log("WaitForDashToEnd Done");
}

// The two lines below are to create the proper facing-direction for the player
Quaternion targetf = Quaternion.Euler(0, 270, 0);
Quaternion targetb = Quaternion.Euler(0, 90, 0);

public void DashLeft()
{
    attacking = true;
    dashUsing = true;
    controller.enabled = false;
    Debug.Log ("Dash-Left-Skill in use");
    transform.rotation = Quaternion.Slerp (transform.rotation, targetf, Time.deltaTime * 5000.0f);
    transform.position = Vector3.MoveTowards (transform.position, Vector3.right * -100f, 20 * Time.deltaTime);
    StartCoroutine (WaitForDashToEnd ());
}

public void DashRight()
{
    attacking = true;
    dashUsing = true;
    controller.enabled = false;
    Debug.Log ("Dash-Right-Skill in use");
    transform.rotation = Quaternion.Slerp(transform.rotation, targetb, Time.deltaTime * 5000.0f);
    transform.position = Vector3.MoveTowards (transform.position, Vector3.right * 100f, 20 * Time.deltaTime);
    StartCoroutine (WaitForDashToEnd ());
}

```

(Sorry for the large blocks of Code, but I thought to better include both)

The problem now is that instead of one button press causing a movement by a set distance... like 100 on the x-axis, the player moves as long as the key is hold. Also, the cooldown for some reason is direction dependant, meaning, if I dash to the right, the cooldown works for the right side, though I can dash to the left directily after without cooldown.

What I am trying to get is to have the WaitForDashToEnd to have a duration that fits the duration of the dash movement itself, I can fix that up as soon as I have the actual dash working. Since the dash movement doesn't work as intented yet, the "stun" during the dash isn't fully functional yet either, but that should more or less fix itself once the dash works.

So... how can I manage to have the dash work as a movement over a predefined distance, no matter how long the key is held?

edit: on a sidenote, during dash, the player is oddly lifted a bit above the ground, is there a way to fix that too? In either case, the dash itself has priority.

# Answer
> 1 votes
Firstly you can change `Input.GetKey()` to `Input.GetKeyDown()` This ensures that the action only happens during the press and doesn't recall the `pstats.DashLeft();` or `pstats.DashRight();` Every frame. I think the rest of your logic is sound. but then again my knowledge of unity's C# libraries is a little rusty.

Edit:

I would assume that

`transform.position = Vector3.MoveTowards (transform.position, Vector3.right * -100f, 20 * Time.deltaTime);`

only happens over one frame. Consider moving it to an update function like

```
void Update()
{
    if(dashUsing)
    {
        if(dashingRight)
            transform.position = Vector3.MoveTowards (transform.position, Vector3.right * -100f, 20 * Time.deltaTime);
        else
             transform.position = Vector3.MoveTowards (transform.position, Vector3.right * 100f, 20 * Time.deltaTime);
    }
}

```

I always use the update to listen for movement states and then move when the states are true. you can then use coroutines to manage timers for toggling the states and standard methods to do things like calculate the dash to position etc.

hope that helps.

Edit:

Try something like

```
transform.position = Vector3.MoveTowards (transform.position, Vector3.right * transform.position.x-5f, 20 * Time.deltaTime);

```

# Answer
> 0 votes
Going to put this in a new "answer" to prevent it from getting lost in the comments, plus since I hope to get the full solution this way.

So, is it possible to like... define a new vector3 in the way of (pseudocode)

```
New Vector3 = CurrentLocation + 5 on the X-Axis

```

And then use that new vector3 on the target for the MoveTowards?

If that's possible, putting both the new vector3 declaration and the MoveTowards into the same part in the Update method, should be a possible solution. Though I am not sure how to really declare a vector3 properly.

So the Main-problem now is to define the vector 3 with the current position of the player and increase the X-axis value.

After that I somehow need a collision with it... not only to avoid moving through walls, but also to have enemies react accordingly when being hit by the dash.

---
Tags: c#, unity, movement, input, scripting
---


title: How can I mod Minecraft 1.7.9?

text:
# Question
Title: How can I mod Minecraft 1.7.9?
I've looked up a lot of tutorials on YouTube and all of them only work for versions of Minecraft prior to 1.7.9.

I first got a Minecraft Coder Pack (MCP) off of this website, but then realized that only decompiles Minecraft 1.6.4. Then I found a more recent MCP (that's not on the website for some reason) and it is version 9.03, downloaded here. This decompiles Minecraft version 1.7.2 (when I followed this video's instructions, I run the decompile.bat file and it says `Json file not found in C:\Users\mike\AppData\Roaming\.minecraft\versions\1.7.2\1.7.2.json`).

Basically I can't decompile Minecraft 1.7.9, but I can decompile older versions. However, I don't have any older versions downloaded onto my computer. I have only 1.7.9.

Then I tried using Forge, but realized that most videos were using versions of Minecraft prior to 1.6.4, meaning they use the bin folder that does not exist anymore. Even after trying to figure that out as well, the decompiling would never work. I tried to do what this video did, but couldn't replicate it. Then I finally looked at this video about using Forge and I could replicate it, but this didn't decompile Minecraft. It just set up a workspace in Eclipse that I'm not sure how to use.

**TL;DR**

**I can decompile Minecraft 1.6.4 and 1.7.2 but I can't decompile version 1.7.9. Should I download an older version of Minecraft, wait for an MCP for 1.7.9, or something else? Is there something I'm missing, where I actually can decompile and mod Minecraft 1.7.9?**

# Answer
According to MCP 9.03 RC1 for Minecraft 1.7.2:

> This version of MCP works for Minecraft 1.7.2 only. A version for newer 1.7.x version will be released eventually.

Even if you do modify the ***~\conf\version.cfg*** file to look for 1.7.9 versions it fails (version 1.7.9 contains Twitch integration that 1.7.2 does not). I dare say there are many other significant differences from 1.7.2 to 1.7.9. It looks like we will just have to wait until the **MCP** people do their magic.
> 3 votes

---
Tags: minecraft-modding
---


# Question
Title: How to modify Game1.cs out of an object it contains?
Assuming I Have a `List<SomeClass> myList;` in my Game1-class. It also contains an object of `SomeOtherClass otherClass;`. How would I modify `myList` (Add/Remove) out of the `otherClass`'s logic? Or in other words how to get access to the Game1-instance in this situation?

# Answer
> 1 votes
2 ways.

1. Pass Game1 as a parameter to SomeOtherClass and store it as a reference. This will allow you to modify the list by going parentGame.myList.Add(SomeClass);. This requires myList to be public. Alternatively, use wrapper methods around myList (eg parentGame.AddToList(SomeClass);)
2. Declare myList as public static, then you can go Game1.myList.Add(SomeClass);.

However, I don't recommend 2, as it goes against what statics are meant to be used for. 1 is probably the safer way to go, and more convenient and coder friendly (not to mention safer). Statics can be hard to remove later on down the line.

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


# Question
Title: Where to place cards drawn from a deck of cards to a tableau
I've never written card games before and am currently coding up a simple card game, I have a deck of cards and they need to be shuffled (done) and then draw from the top deck into a tableau (centre of table) from which the user(s) can pick from.

The only issue is I'm not sure how I can figure out where the cards drawn from the top deck go to.

Let's say the draw deck is drawn at 100,100.

Let's say the tableau starts at 200,200 and can have 6 cards in them.

How do I know where the cards are going to appear on screen within the tableau?

My current thoughts are that we fill the tableau "empty" card objects at set X/Y co-ordinates so that I know without having to do too much programming where the cards should go to.

But I'm not sure if this is the best way to do it because of screen sizes, etc.

ie: Tableau. A card width is 50, and the distance between them is 20

```
> Card slot #1 = 200,200 (State: Empty)
> Card slot #2 = 270,200 (State: Empty)
> Card slot #3 = 340,200 (State: Empty)

```

So the first card drawn would animate from 100,100 to 200,200 and change it's state to `Filled` The second to 270,200, changing its state The third to 340,200, changing its state And so on..

But I'm still unsure if using hard number co-ordinates is really the best way forward, especially if the screen sizes change; or even if there's a better way to animate cards from a draw pile to a tableau.

My question therefore is -- how do I make the computer know where to put cards drawn from a deck of cards to a tableau?

Many thanks

# Answer
> 0 votes
Method I am using is adding a scalar in my camera's view matrix. This scalar is the comparison between the device's screen size and the size I made the game for. For this to work you do need to be able to access your device's screen size in your code.

Even in games with no screen movement I have a camera running in the background. Usually a basic camera (C# XNA example) for games without screen movement. Then I add a little method which would look like the following:

```
void AdjustScreenSizeScalar(float screenSizeX, float screenSizeY)
{
    screenSizeScalarX = screenSizeX / /* Your expected screen size X here */
    screenSizeScalarY = screenSizeY / /* Your expected screen size Y here */
}

```

And for creating your view scalar you can do the following:

```
//scalar = your normal scale stuff
viewScalarX = scalarX * screenSizeScalarX;
viewScalarY = scalarY * screenSizeScalarY;

```

After that just make sure that all your objects use the view of the camera. How to do that depends on your code. But once you do that you can use your normal positioning stuff and the game will adjust itself when the screen size is different than the 'expected' size.

Hope this helps!

---
Tags: card-game
---