title: undeclared Identifier error

text:
# Question
Title: undeclared Identifier error
I am learning computer graphics using opengl and c++. when I am trying to run my code It shows the following error:

'myDisplay' undeclared identifier. Although thats already declared. please help me as I am new to OGL and c++.

```
#include<iostream>
#include<fstream>
#include<string>
#include<glut.h>
#include "RGBA.h"

using namespace std;

int screenWidth= 640;
int screenHeight= 480;

RGBApixmap pix[2];

int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(screenWidth, screenHeight);
glutInitWindowPosition(30,30);
glutCreateWindow("Mario and Bhoot");

pix[0].readBMPFile("bg.bmp");

pix[1].readBMPFile("marioStanding.bmp");
pix[1].setChromaKey(192,192,192);

glutDisplayFunc(myDisplay);
glutMainLoop();

return 0;

}

void myDisplay(void)
{
glClearColor(0.035,0.050,0.274,0);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1,0,0);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,20,0,20);

glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_EQUAL,1.0);

glPixelZoom(1,1);
glRasterPos2i(-20,-20);
pix[0].mDraw();

glRasterPos2i(-18,-20);
glPixelZoom(1.5,1.5);
pix[1].mDraw();

//glBegin

glutSwapBuffers();
}

```

# Answer
> 1 votes
As @Sean Middleditch said, In C/C++ you must declare functions before tu use them:

```
#include<iostream>
#include<fstream>
#include<string>
#include<glut.h>
#include "RGBA.h"

using namespace std;

void myDisplay(void);
int main(int, char**);
glutSwapBuffers();

int main(int argc, char** argv)
{
...

```

Ordering functions work also, but I think it is not a good programming practice:

```
myDisplay(void)
{
...
}
int main(int argc, char** argv)
{
...
}
...

```

When there is a circular dependence of two function (A() call B() and B() call A) for any recursive algorithm, ordering functions is not possible.

In this case, the prototype declaration is the only solution. Mix both solution is ugly/problematic. Also, getting all declarations into a .h file has many advantages.

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


title: Can JOGL help me learn OpenGL?

text:
# Question
Title: Can JOGL help me learn OpenGL?
I've decided to learn OpenGL. I worked through several tutorials. I've found it far too complex performing a simple task like doing sprite animation in openGL.

Now I read about JOGL which seems to be more accessible. So I actually have two questions.

1. Can JOGL help me understand OpenGL better?
2. Also important to me, will I be able upload my JOGL applications to Greenlight, MS-marketplace etc.?

# Answer
1. No. JOGL is a wrapper library for OpenGL, which means it simply gives you access to the OpenGL api. So whether or not you use JOGL, you still have to know and use the OpenGL methods.
2. Greenlight supports jar files, I believe Windows Marketplace doesn't, as it's only for apps.

One benefit of using JOGL or LWJGL is that it gives you access to helpful classes like classes for spritesheets, textures, images, rendering, keyboard / mouse input etc. But that way you don't actually learn OpenGL like you should. It is an option though.

But yeah, switching from XNA to OpenGL might me a struggle. XNA is designed mostly for students (and very easy to use so everyone can make games with it after a little research). With XNA you use XNA render features, but in OpenGL you have to do *everything* yourself.
> 2 votes

---
Tags: opengl, jogl
---


# Question
Title: Inventory structure for games like Dragon Warriors
I'm wandering what would be a suitable way of storing items in inventory. Many games have an inventory that stores different items with its quantity. For example, \[ "Herbs" x5, "Torch" x2, ..\].

so I came up with a data structure like this in Java;

HashMap\> inventory // where Integer -\> item id, ArrayList -\> there are same items stored in the list

but I thought Is this a good way to store items even if the number of items in each list becomes larger (x99 items) ?

or should I just store the quantity of items instead of storing objects in list? in this case, is using tuple going to be ok? like HashMap\>

# Answer
Store quantities, not instances. There is zero value in having 99 instantiated torches in an inventory. All you need to know is that you have torches and how many of them.

A `HashMap` works, but it's not ideal; if it's the easiest thing for you, though, I would go with that for now. Another option that might be even easier to just keep a single array of quantities, where each item has a unique small integer ID. For instance, torch might be #17. Then you can just set array index 17 to 0 if you have no torches, and a positive number when you have some quantity.

The advantage of the array is that since the list is ordered, you can generate an index of items in the inventory (items with quantity \> 0) quite easily, which will mesh well with the UI in most of these kinds of games.
> 2 votes

# Answer
In previous games, the solution I've used is similar to this:

How should I handle collectable/droppable/stackable items in an inventory?

```
class ItemStack {
  Item item;
  int count;

  // ...public methods here...
}

```

Stacks are very easy to work with and also allow you to have instances of the items
> 0 votes

---
Tags: java, data-structure
---


# Question
Title: Fine-tuning parallaxing objects in 2D games
I'm making a 2D platformer game and I'm having a hard time figuring out how to fine-tune parallaxing objects in-game quickly enough. Problem is I don't even know how to make it faster, so I'm basically looking for standard approaches.

Currently I place a parallaxing object just like a normal static doodad somewhere on a level and then define the parallax offset multipliers (horizontal and vertical). Then I spend from five to ten minutes moving the camera around the location finding three values that satisfy me. So when placing each object takes that long, you start thinking of a way to make it faster, but unfortunately, I couldn't come up with anything better than what I have, so I'd like to learn about other approaches and possibly improve mine with that knowledge.

What are the usual approaches to placing and tuning the parallaxing objects in 2D games?

# Answer
It sounds like what you're after is a way to streamline and optimise your workflow.

I would take the approach of defining various levels of foreground and then assigning each foreground element an index. You would then use your horizontal and vertical multipliers on a collection of sprites that have been assigned to a certain layer.

Example:

This obviously depends on how you're going about loading your sprites. If you're loading and positioning individual sprites, this is a time consuming process regardless of whether you're dealing with parallax or not.

Depending on the scale of the worlds that you are creating, it might be worth considering building some sort of SDK for yourself; to make the process of creating these worlds easier for you.
> 2 votes

---
Tags: 2d, parallax-scrolling
---


# Question
Title: How do network applications get around firewalls?
Forgive me if this comes off as naive; I've only a cursory understanding of network communications.

My work has a public and very restrictive network - (they appear to block everything that isn't approved) - and yet I've seen people accessing many games (World of Warcraft for example). I don't imagine that the network admins made any explicit exceptions for these applications - but when I tried to develop a networked prototype with services like 'Photon Server' or 'Adobe's RTMFP' they all fail from the office due to the network restrictions (can't establish connection).

Is there some kind of work around that applications like WoW employ that distinguish them from an anonymous networked app I've built myself? (Some kind of fallback channel maybe?)

I appreciate that there might not be enough information here for an answer, but any insights would be welcome.

Thank you!

# Answer
The topic of "getting around" firewalls is not as easy as it sounds.

To make it simple, no program can consistently get around *all* firewalls, and no firewall can consistently stop *all* undesired applications.

A firewall is simply an element you place in a point in your network, to **analyze** packets, and based on a set of **rules**, **act** upon them.

Depending on the hardware and software that a firewall uses, a firewall can be set to do very simple tasks, to extremely complex ones. So let's see those bolded words up there:

1. **Analyze**: If you remember networking 101, data in a network is layered. When you ask the stackexchange servers to show you this page, the stackexchange server gets:

* An HTTP request (application layer)
    * Inside a TCP segment (transport layer)
    * Inside an IP datagram (internet layer)
    * Most likely inside an Ethernet frame (link layer)

Firewalls can be set to analyze network traffic at any layer, and for all layers, there are different things that can be analyzed. For example, a firewall that can analyze data at the transport layer, will most likely be able to read TCP flags, TCP ports, among others.

Usually, the higher the layer at which a firewall can analyze, the more complex and expensive it becomes.
2. **Rules**: Once the data to analyze is set, a bunch of rules are created. Once again, rules can be very simple, or very complex. The more complex rules can be set, the more complex and expensive the firewall becomes. Examples of rules are:

* Allow outgoing TCP segments for TCP port 80
    * Block incoming TCP segments where the flags include SYN, but not ACK
    * Allow incoming TCP segments for TCP port 22, only for 10.5.20.4
    * Block outgoing TCP segments for TCP port 80, where the stream does not look like an HTTP request
    * Block incoming and outgoing UDP datagrams on port 4658, from 10 AM to 8 PM. Log all blocked traffic

Depending on the type of firewall, the type of stuff you can include on a rule can be either very simple or very complex
3. **Act**: Finally, when a rule is hit, a decision is made, and something is done with the data. Usually, data is either allowed or blocked. However, some firewalls also let you log the data, delay it, modify it, or some more esoteric options.

So, the important thing to notice here is that each firewall has a different configuration, and there are as many configurations as there are firewalls around.

That said, there are some *common* firewall settings, which a game can be coded to get around of. For example, many firewalls block all incoming traffic for which there are no active connections (as in most home wireless routers). A simple way around this is to make all connections start from the client.

Other common rules are to block all traffic that is not TCP port 80. A way around this is to make a game that uses port 80.

However, for every way around a rule, there is another possible rule to catch it, and for all rules, there are ways around it. So really, it's a cat-and-mouse game.

In conclusion, there is no way to get around *all* firewalls. Some games are made to get around some *common* firewall rules, and some others are made to get around some more complex ones. How they do it is completely up to the game creators, how the game works, and the type of rules they want to get around. Sometimes it will work, sometimes it won't/
> 7 votes

# Answer
The firewall usually can't tell what application the connection is initiated from. Hence, if something like World of Warcraft is able to connect to its server on port 80 (HTTP), it will succeed, as the firewall will be unable to distinguish it from normal web browsing.

The developers of such applications often choose such ports for servers for this reason - it will reduce the number of cases that firewalls get in the way.
> 1 votes

# Answer
According to http://www.adobe.com/uk/products/adobe-media-server-extended/rtmfp-faq.html RTMFP uses UDP. http://www.exitgames.com/Photon/Unity also suggests that Photon Server only uses UDP.

World of Warcraft uses TCP.

I wouldn't be surprised if your firewall simply doesn't allow UDP through.
> 1 votes

# Answer
Its likely that not the firewall settings of your client machine are the problem, but the ones of the machine, where you run your server. For WoW you just install the client and Blizzard hosts the servers, so they care about the server side firewall settings, but when you run your own server, then you have to care about the server side firewall settings.

For Photon Server you can read at http://doc.exitgames.com/photon-server/Requirements/#cat-getting\_started, which ports to open on the server side.

You could also just register a free account for Photon Cloud, where you don't have to setup or host the server yourself, and see, if you can connect to the Photon Cloud from your workplace. If that works fine, than your problems are most definitely caused by the server side firewall settings.
> 0 votes

---
Tags: networking
---


# Question
Title: Dealing with sprite loading and setting in an entity-component system
I've just started using an entity-component system for the first time and I'm having trouble making some decisions.

Currently I've got a SpriteComponent that holds a sprite, a ContentManagerComponents that holds an instance of a content manager so systems can load the content they need, and a SpriteSystem that requires both components and only has a method to set the sprite, possibly loading it beforehand (sprite rendering and animating is taken care of by other systems).

This kinda looks good, but my main concern is... how is a system that's not SpriteSystem supposed to set the sprite?

Here are my options, as I see them:

* Have systems that need to change the sprite comunicate with SpriteSystem somehow. Probably a bad idea since it introduces a dependency between systems (?).
* Move the method to set the sprite to SpriteComponent. Problem is, the method needs a content manager to load the sprite if needed.
* Get rid of ContentManagerComponent and give SpriteComponent a content manager. But the content manager doesn't only load sprites.

Any help is appreciated.

# Answer
Lazy loading!

Add a method to SpriteComponent to let it store the name of the new sprite to load, then let the SpriteSystem load the actual data whenever it comes into play.

To smooth out the loading laggies, preload.
> 3 votes

---
Tags: component-based, entity-system
---


title: Sound upsample using SDL

text:
# Question
Title: Sound upsample using SDL
We have managed to play audio files using SDL's Mix\_PlayMusic function. The problem now we need to do some upsampling for one audio to match the other so that both have same duration. Any idea how to resolve this issue.

# Answer
Do you want the pitch to warp with the speed?

---

Yes: Then you want time stretching.

This is simply interpolating / combining samples to generate the same overall waveform in a different number of samples. The obvious nearest neighbor approach will cause severe aliasing but technically works. To make it sound better one can use a higher order function like sinc interpolation.

---

No: Then you want time *scaling*.

This is usually boiling down the sound to a procedural / time domain representation, it is an active area of research and doesn't sound perfect. The common techniques are:

1. Phase Vocoder
2. Time Domain Harmonic Scaling

---

EDIT: Your question is WAY out of scope for SDL. If you just want a library (instead of understanding what you are doing) then try SoundTouch or Rubber Band.
> 1 votes

---
Tags: sdl
---


# Question
Title: Model a chain with different elements in Unity 3D
I have to model, in unity 3D, a chain that is composed of various elements. some flexible, some rigid. The idea is to realize a human-chain where each person is linked to the other by their hands.

I've not tried to implement it yet as i've no idea on what could be a good way to do it. In the game i've to manage a lot of chains of people... maybe also 100 chains composed of 11-15 people. The chain will be pretty simple and there won't be much interaction... Probabily some animation of the people one at time for each chain and some physic reaction (for example pushing a people in a chain should slightle flex the chain)

the very problem of this work is that in the chain each object is composed by flexible parts (arms) and rigid parts (the body) and that the connection should remain firm... just like when people handshake... hands are firm and are the wrists to move.

i can use C4D to model the meshes.

i know this number may cause performance problems, but it's also true i will use low-poly versions of human. (for the real it won't be human, but very simple toonish characters that have harms and legs). So actually i'm trying to find a way to manage this in a way it can work, the performance will be a later problem that i can solve.

If there is not a fast 'best-practiced' solution and you have any link/guide/doc that could help me in finding a way to realize this is, it would be very appreciated anyway if you post it.

thanks

# Answer
One approach could be to use a mass spring system, such for dynamic cloth, or a simplification of it. In this case the chain would abstract all other parts of persons except of the arms. With the mass spring system you could calculate the force applied on each arm and move persons accordingly (using a threshold value you could even make an horror movie by letting people be ripped off... gross). To let other parts of a person interact, you could model persons with bones and constraints and use inverse kinematics to let the body respond for the applied forces.
> 1 votes

---
Tags: unity, models, rope-physics
---


# Question
Title: Using quaternions, how do I determine if an object is upside down from an original rotation?
Imagine this scenario: An object is laying flat on a horizontal surface, from this an original rotation is determined. Then the object is moved, and at some point flipped upside down and put back down on the table, throughout this a second rotation is continuously updated.

I need a way to determine if the rotation is now pointing downwards compared to the first rotation. This rotation is updated using data from a gyroscope and an accelerometer.

# Answer
As Byte56 noted in a comment, you should just be able to read the object's current orientation (i.e., its rotation matrix) off of the gyroscope, and the problem is much easier to solve that way. Regardless of how you have the object's orientation, the key is to find the 'transformed' version of whichever axis (presumably Y or Z) corresponds to your upwards direction and to determine whether it points in the opposite direction from the original axis; the condition for the latter is just that the dot product between the two is less than zero. Since the axis is generally a basis vector, you don't even need to look at a full dot product; just the appropriate component. So, for instance, assuming that your vertical axis is Z, if the device's current rotational transformation is stored in a quaternion q then the pseudocode might look something like:

```
Vector vNewZAxis = q.rotateVector(Vector(0,0,1));
bool bIsFlipped = (vNewZAxis[2] < 0);

```

If you have your transformation encoded as a matrix, then this simplifies even further (since then the rotation is simply a column extraction), and the code ends up looking something like:

```
bool bIsFlipped = (mOrientationMatrix[2][2] < 0);

```
> 2 votes

# Answer
I resolved it I think - I will however accept Steven Stadnicki's answer but here's how I did it for posterity:

Using the quaternion, with its parts called `q0 q1 q2 q3`.

Calculate the direction of gravity, `gx gy gz` using this:

```
gx = 2 * (q1*q3 - q0*q2);
gy = 2 * (q0*q1 + q2*q3);
gz = q0*q0 - q1*q1 - q2*q2 + q3*q3;

```

`gz` will then be positive if in the upright position, and negative if facing upside down.
> 0 votes

---
Tags: rotation, c, quaternion
---


# Question
Title: Is this a good way to handle different game screens?
While developing my game I am often asking myself if my way of handling different game screens (MainMenu, Game, Ending, Highscore) is a good one. I am currently using only one activity. The game loop is running in this class. The currently active screen gets a update and paint method called from this loop like this:

```
while (running) {
    if (!holder.getSurface().isValid())
        continue;

    float deltaTime = (System.nanoTime() - startTime) / 1000000000.0f;
    startTime = System.nanoTime();

    if (deltaTime > 0.315) {
        deltaTime = (float) 0.315;
    }

    game.getCurrentScreen().update(deltaTime);
    game.getCurrentScreen().paint(deltaTime);

    Canvas canvas = holder.lockCanvas();
    canvas.getClipBounds(dstRect);
    canvas.drawBitmap(framebuffer, null, dstRect, null);
    holder.unlockCanvasAndPost(canvas);
}

```

One problem I am often facing is that the screen classes aren't activities, so I am unable to start a `DialogFragment`, as an example, because it needs a `FragmentActivity`. Since these classes are just instantiated the `FragmentActivity` never gets started.

If I need a dialog, I am currently just making an `Activity` to a custom dialog.

How would you handle a game framework? Are there any good examples out there?

# Answer
What you are doing is fine and will work.

Like your example, games are rather often structured as a Finite State Machine.

Since you are doing Android, however, take a look at LibGdx, and in particular Scene2D.

There is no real need to roll your own, unless you are using it as a learning experience.
> 2 votes

---
Tags: java, android
---


# Question
Title: Voxel Face Crawling (Mesh simplification, possibly using greedy)
Edit: This is just for my own learning experience, it is NOT for performance reasons that I ask this question.

This is in regards to a Minecraft-like terrain engine. I store blocks in chunks (16x256x16 blocks in a chunk). When I generate a chunk, I use multiple procedural techniques to set the terrain and place objects. While generating, I keep one 1D array for the full chunk (solid or not) and a separate 1D array of solid blocks.

After generation, I iterate through the solid blocks checking their neighbors so I only generate block faces that don't have solid neighbors. I store which faces to generate in their own list (that's 6 lists, one per possible face/normal). When rendering a chunk, I render all lists in the camera's current chunk and only the lists facing the camera in all other chunks. I do this by storing all 6 lists in one buffer, then I simply change what ranges I draw.

Using a 2D atlas with this little shader trick Andrew Russell suggested, I want to merge similar faces together completely. That is, if they are in the same list (same normal), are adjacent to each other, have the same light level, etc. I know I will still end up with rectangles, but it should easily reduce my vertices count by 50% or better if my estimations are correct.

My assumption would be to have each of the 6 lists sorted by the axis they rest on, then by the other two axes (the list for the top of a block would be sorted by it's Y value, then X, then Z).

With this alone, I could quite easily merge strips of faces, but I'm looking to merge more than just strips together when possible. I've read up on this greedy meshing algorithm, but I am having a lot of trouble understanding it.

So, my question: **To perform merging of faces as described (ignoring whether it's a bad idea for dynamic terrain/lighting), is there perhaps an algorithm that is simpler to implement?** I would also quite happily accept an answer that walks me through the greedy algorithm in a much simpler way (a link or explanation).

I don't mind a slight performance decrease if it's easier to implement or even if it's only a little better than just doing strips. I worry that most algorithms focus on triangles rather than quads and using a 2D atlas the way I am, I don't know that I could implement something triangle based with my current skills.

PS: I already frustum cull per chunk and as described, I also cull faces between solid blocks. I don't occlusion cull yet and may never.

\*Edit: I have implemented my own little technique, which probably has a name, but I simply go through my 6 lists which are sorted by the axes they rest on, followed by block type, and then by lighting level. I iterate through them, creating new rectangles as I go and grow them simultaneously (with a heavy bias towards a certain axis). It is definitely not optimal, but it is indeed quite fast and it does lower my vertex count by close to 50% on average. Byte56's comment is the closet I think to a real answer, but I can't select that for the answer/bounty.

Here is my fast and simplistic way I'm handling this problem AFTER generating the full initial terrain without much of any optimization. Assuming all squares given are the same image, light level, normal, etc.. each color is a different quad I would render. With my lists sorted the way they are, this is a very easy/fast approach.

# Answer
> 4 votes
You only want to do strips, or at the very best, rectangles. There are no other shapes that will be solvable or useful to you.

I would also like to point out that by keeping 6 lists per chunk, that at any point you're going to be using 5 lists from the chunks in cardinal directions, and at least 3 in every other one. You're wasting time here, when not only can the video card do this optimisation for you, but even if you did it yourself, you would be better off keeping all the faces in one place, and comparing the normal to the direction to the camera (Research DOT product of vectors).

CaptainRedMuff's links on Greedy meshing that you've already seen is THE answer to your problem. It should also be apparent from that that you will end up with "Stripy" meshes, but they are perfectly effective, and coming with something more optimal will be more complicated, and you have expressed that the greedy mesh is already too complicated.

If you're having performance issues with a single chunk, it makes me think something else is greatly wrong.

My first guess would be that you are calling a draw operation way too often. You can only tell the graphics card to draw between 50 and 400~ times per second, depending on hardware. How many calls to either .setData or .draw\____Primitives are you making?

# Answer
> 0 votes
The article that you link to doesn't actually give an algorithm for generating the mesh; it states a way to evaluate possible solutions.

Generally, though, the article gives a good summary: 1) the naive solution is bad, 2) there's an optimal solution, but it will be both time-consuming to write and to run, 3) a quick culling gives much better results (and this is all Minecraft itself does), and finally 4) there might be a smarter solution (the greedy algorithm).

The "solution" that you imply in the image in your question *is* the greedy algorithm. It seems your question is "did I implement his solution correctly?" to which I must answer "he didn't give a solution; you just solved this yourself."

Can your solution be better? Meh. Sure. Probably not worth it. I think occlusion culling or LOD would be better next steps. Minecraft wastes a good number of cycles drawing the surface even when you're underground, as well as drawing vast networks of cave and mine systems when you're on the surface. Once you've got a good mesh breakdown, yeah, getting rid of obscured surfaces can be a good thing -- but (e.g.) generally it's faster to let your video card do backface culling than to do it on the CPU.

---
Tags: xna, performance, 3d-meshes, terrain
---


# Question
Title: Offloading processing to a remote server in a game engine?
What kinds of processes can you offload to a remote server in a game engine?

I'm thinking of making a real time multiplayer RTS, like Starcraft for example.

I was trying to offload as many processes as possible onto a remote server to:

1) Practice the techniques involved in order to offer a responsive gaming experience while taking advantage of the latest cloud processing techniques.

2) To make an engine that's the most platform independent possible.

I've already thought of a couple of things that could be processed remotely:

1. AI (Path finding)
2. Volumetric particle effects (Smoke after an explosion)
3. Loading between levels?

I'm also most curious about the following things being possible:

1. Rendering
2. Physics

If anybody has any knowledge to share about this subject I'd very much appreciate some guidance.

# Answer
> 4 votes
The problem is latency.

at 30fps, you get 33ms to do all of your *work*. Its highly unlikely that you'll have to time to farm things off to a remote server, and get things back within a frame boundary. And thats before you deal with unstable network conditions, overloaded servers, network dropouts, etc etc.

Basically anything that needs to update within that frame boundary will be out. AI, physics, even particle effects.

Path finding you could potentially do off-client. But that also implies that you can farm off the entire local state of the game at the time to do it. It's going to be far easier and more performant to do it locally, even if you do it over the course of multiple frames locally. Which is a good point to bring up. You can always process things over multiple frames on the local CPU. Tasks like pathfinding are often done this way.

The problem will always be latency, and the time it takes to transfer enough of your local state somewhere else to be able to get them to do calculations for you. Doing it locally over the course of multiple frames offsets the second problem.

You could conceivably do theses kinds of tasks on a "server" of a client / server architecture to mitigate the "state" problem as much as possible, but this will put additional load on your C/S system (and usually the idea is that your "server" is very lightweight so you can run a hell of a lot of them on a single box). And you'll still suffer latency issues.

# Answer
> 2 votes
You *can* offload anything. You *shouldn't* try to offload certain things if you want a smooth game. For instance, physics is generally run on *both* the client and server in order for the client to predict where objects will move to compensate for the lag between the server's simulation state reaching the service. Likewise with graphics. Certainly the rise in streaming video games has shown that you can still get away with such processing on the server; you could just stream your game if that's what you're looking for. Loading between levels *must* be on the client assuming the client needs to load something almost by definition.

However, I consider offloading to the client as a step *up* from cloud computing. If the idea of the cloud is to have scalable elastic computing power then being able to "tap into" the computing power of your players is what the cloud was before "cloud" was even a buzzword.

Being portable doesn't necessitate offloading code to a server. It just means writing portable code. These days, you can compile C++ into standards-compliant JavaScript, with WebGL and other services across multiple browsers. Game engines like Unity target a wide variety of platforms. You can be quite widely portable without paying a bazillion in server costs.

Also don't forget that users tend to reject online-only games that aren't inherently online games. See the outcry on Sim City or before that Assassin's Creed or so on. If you're making an online game where the game has no value without being connected in itself, that's one thing, but if you're making a single-player experience you *really* don't want to make a server required to play.

---
Tags: cloud-computing
---


# Question
Title: Accounting for waves when doing planar reflections
I've been studying Nvidia's examples from the SDK, in particular the Island11 project and I've found something curious about a piece of HLSL code which corrects the reflections up and down depending on the state of the wave's height.

Naturally, after examining the brief paragraph of code:

```
// calculating correction that shifts reflection up/down according to water wave Y position
float4 projected_waveheight = mul(float4(input.positionWS.x,input.positionWS.y,input.positionWS.z,1),g_ModelViewProjectionMatrix);
float waveheight_correction=-0.5*projected_waveheight.y/projected_waveheight.w;
projected_waveheight = mul(float4(input.positionWS.x,-0.8,input.positionWS.z,1),g_ModelViewProjectionMatrix);
waveheight_correction+=0.5*projected_waveheight.y/projected_waveheight.w;
reflection_disturbance.y=max(-0.15,waveheight_correction+reflection_disturbance.y);

```

My first guess was that it compensates for the planar reflection when it is subjected to vertical perturbation (the waves), shifting the reflected geometry to a point where is nothing and the water is just rendered as if there is nothing there or just the sky:

Now, that's the sky reflecting where we should see the terrain's green/grey/yellowish reflection lerped with the water's baseline. My problem is now that I cannot really pinpoint what is the logic behind it. Projecting the actual world space position of a point of the wave/water geometry and then multiplying by -.5f, only to take another projection of the same point, this time with its y coordinate changed to -0.8 (why -0.8?).

Clues in the code seem to indicate it was derived with trial and error because there is redundancy. For example, the author takes the negative half of the projected y coordinate (after the w divide):

```
float waveheight_correction=-0.5*projected_waveheight.y/projected_waveheight.w;

```

And then does the same for the second point (only positive, to get a difference of some sort, I presume) and combines them:

```
waveheight_correction+=0.5*projected_waveheight.y/projected_waveheight.w;

```

By removing the divide by 2, I see no difference in quality improvement (if someone cares to correct me, please do). **The crux of it seems to be the difference in the projected y, why is that?** This redundancy and the seemingly arbitrary selection of -.8f and -0.15f lead me to conclude that this might be a combination of heuristics/guess work. **Is there a logical underpinning to this or is it just a desperate hack?**

Here is an exaggeration of the initial problem which the code fragment fixes, observe on the lowest tessellation level. Hopefully, it might spark an idea I'm missing. The -.8f might be a reference height from which to deduce how much to disturb the texture coordinate sampling the planarly reflected geometry render and -.15f might be the lower bound, a security measure.

# Answer
This technique is bound to have this artefact, and that is why most of the time when it is used, we apply a vertical shift into the lookup to do like if the actual reflection plane was half a meter above its real position. Yes it has the drawback of not having a perfectly matching reflection, but it is preferable to holes.
> 1 votes

---
Tags: mathematics, directx, hlsl, reflection-rendering
---


# Question
Title: Is there a proper way to come up with random numbers?
In my game I have some powerUps which are gain when enemy is killed. Is there a proper way to come up with random numbers?

here is what i am thinking:

```
double rand = Math.random();

if(if (rand < .001){ // 1 in 1000 chance
    //powerUp1
}
if(rand < .20){   // 1 in 5 chance
    //powerUp2
}
if(?){
    //powerUp3
}
if(?){
    //powerUp4
}

```

is there a better way?

# Answer
I'm new to gamedev.se so I can't comment yet, but I think what you're trying to ask is

> How does one get a boolean answer with a certain probability?

If that's the case, then it's easy. You just do exactly what you're doing already. Except that you're going to want to put it into a function if you plan on having more than a couple of powerups:

```
// Returns true <percent> of the time.
public static bool Chance(double percent)
{
    percent /= 100;
    return Math.Random() < percent;
}

```
> 4 votes

---
Tags: random
---


# Question
Title: How do I make a health bar that drains when the player takes damage? C#/XNA
I've drawn a Health Bar before and had it drain/refill on a button press using if statements and rectangles.

First I loaded the image, then I set a new rectangle to be equal to the image's height and width.

```
        greenHealth = Content.Load<Texture2D>("GreenHealth");
        redHealth = Content.Load<Texture2D>("RedHealth");
        blackHealth = Content.Load<Texture2D>("BlackHealth");
        jumpGuy = Content.Load<Texture2D>("JumpGuy");
        enemyBlock = Content.Load<Texture2D>("Block");

        greenRectangle = new Rectangle(0, 0, greenHealth.Width, greenHealth.Height);
        redRectangle = new Rectangle(0, 0, redHealth.Width, redHealth.Height);
        blackRectangle = new Rectangle(0, 0, blackHealth.Width + 5, blackHealth.Height + 5);

```

Then I set it to drain/refill based on key presses -

```
  public void healthDrain()
    {

        if (Keyboard.GetState().IsKeyDown(Keys.Space))
        {
            greenRectangle.Width -= 2;
        }

        if (Keyboard.GetState().IsKeyDown(Keys.Space))
        {
            redRectangle.Width -= 1;
        }

        if (Keyboard.GetState().IsKeyDown(Keys.L))
        {
            redRectangle.Width = greenRectangle.Width;
        }

        if (Keyboard.GetState().IsKeyDown(Keys.R))
        {
            greenRectangle.Width += 1;
        }

        if (greenRectangle.Width > blackRectangle.Width - 4)
        {
            greenRectangle.Width = blackRectangle.Width - 4;
        }

    }

```

The Result is a Health Bar that can be drained/refilled -

The problem arises when I want the health to drain/refill based on the Player Health, which I set to 100. I do not know how to properly implement this and attempts at it have resulted in it functioning incorrectly, like the health draining on its own, or not moving at all.

I intend to have the player take damage when in contact with the yellowish-green block in the image. I did this using rectangles and an if statement with rectangle.Intersect.

```
        if (jumpRect.Intersects(enemyRectangle))
        {

            playerHealth--;

        }

```

I tried having the health bar's width be equal to the playerHealth value but it didn't work and I'm unsure of how to make it work correctly.

I do hope I was able to make this easy for someone to help me solve.

# Answer
> 2 votes
I'd rather implement any rolling value (such as the health example) with two values that with with the health bars width. I'd call them something like:

```
int actualHealth;
int visibleHealth;

```

In the beginning you can set both to the same value:

```
public ResetHealth(int health) {
    actualHealth = visibleHealth = health;
}

```

And when you want to do a "hit" on the value you only change the "actual" value.

```
public Hit(int damage) {
    actualHealth -= damage;
}

```

In your update method you also should update the "visible" value to go toward the "actual" value. The effect will be that the value is decreasing over time until it hits the actual value.

```
// in your update code:
if (actualHealth < visibleHealth) {
    visibleHealth -= 1;
}
else if (actualHealth != visibleHealth) {
   // Make sure we don't go over
   visibleHealth = actualHealth;
}

```

In your render method you only need to do one thing. Draw the bar according to the `visibleHealth` value, while in your game logic you only look at the `actualHealth`. In your case the green health bar's width is based on `actualHealth` and the red bar's width is based on `visibleHealth`. In your case it'll be something like this:

```
int fullWidth = // the full width of the bar ;
greenHealthBar.Width = (actualHealth / 100) * fullWidth;
redHealthBar.Width = (visibleHealth / 100) * fullWidth;

```

If you're wondering how this calculation works, you can do the following thought experiment:

```
// health:   0 => (0 / 100) * fullWidth   = 0    * fullWidth = 0
// health:  25 => (25 / 100) * fullWidth  = 0.25 * fullWidth
// health:  50 => (50 / 100) * fullWidth  = 0.5  * fullWidth
// health:  75 => (75 / 100) * fullWidth  = 0.75 * fullWidth
// health: 100 => (100 / 100) * fullWidth = 1    * fullWidth = fullWidth

```

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


title: Logic for selecting random rewards

text:
# Question
Title: Logic for selecting random rewards
I am making a RPG game and I am seeking a bit of information on how to grant players random rewards, such as game items, weapons, gold, etc... after defeating a monster, or a NPC of some kind. The items would be pre made and already existing. I am not sure on what is the best way to approach this kind of system. Any tips of advice will be appreciated on the matter.

# Answer
> 3 votes
Well... you need to determine how your game's going to do it.

Thinking back on my days of playing Ocarina of Time, it always seemed to me that when I was low on health, turning some bushes into salad would reliably heal me up. If I was at full health, it would always drop rupees...

Divine intervention (aka game design) aside, under the hood it's all done with probabilities. Use the random number generator to make a probability function like `probability(percent)` that returns `true` `<percent>` of the time. Then it's just a matter of, when the enemy is vanquished, run its `drop` function or something similar.

```
void Drop()
{
    // Sometimes you want to drop one kind of item, but not the other kinds
    if( probability(20) ) {
         // 20% of the time.
         weaponDrop("common"); // Determines (using probabilities) which weapon to drop
    } else if( probability(20) ) {
         // 16% of the time
         itemDrop();
    } else {
         // 64% of the time
         goldDrop(10, 25); // Drop between 10 and 25 gold pieces
    }

    // Sometimes you want it to drop items regardless of what else you've dropped
    if(probability(.1)){
         weaponDrop("Super Cool Rare");
    }

    // Sometimes you want specific drops to always happen.
    dropDungeonMap();
}

```

I don't know what your game looks like in terms of the code structure, but the point is that it works on probabilities. Keep in mind that `if(20%)` implies that all the `else` branches *combined* have a probability of 80%.

---
Tags: java, android, game-mechanics
---


# Question
Title: How should I calculate the score in Minesweeper: 3BV or 3BV/s?
I'm designing a minesweeper game, and I'm a bit confused as to how to calculate the score.

The objective of my game is to reveal all the non-flagged boxes. Marking the flag must not count toward the score. Just showing the number of seconds required to complete a board seems obsolete as I have a variable board size which is decided by the user. I studied the Wikipedia page on Minesweeper regarding the two scoring techniques.

But I don't understand how to calculate the 3BV. Is it just the number of left clicks done by user done during the game, or is the 3BV the minimum number of clicks required to complete the board? Also how can 3BV/s be judged: does a higher or lower score give a higher ranking?

### Regarding my implementation

I used an integer array with all zeros and 9 designating a mine position. When a user click in the grid I calculate the nearby cells and then display the appropriate number and if he clicks on cell with value 9 then game is over.

# Answer
> 7 votes
The 3BV score is essentially counting the number of clicks required to reveal all non-mine squares.

A Minesweeper board is essentially an m\*n array. To calculate the 3BV, you will need to process the cells in this array in a particular order, so you will need to be able to mark each cell after you process it (so you don't process it multiple times). Then, use the following two procedures:

```
Count3BV:

  For each empty ("0") cell C:
    If C has already been marked, continue.
    Mark C. Add 1 to your 3BV count.
    Call FloodFillMark(C).
  For each non-marked, non-mine cell:
    Add 1 to your 3BV count.

FloodFillMark(C):

  For every non-marked neighbor N of C (diagonal and orthogonal):
    Mark N.
    If N is an empty cell, call FloodFillMark(N).

```

(EDIT: There was a small typo above.) (EDIT: Added pseudo-function indentation.)

As for 3BV/s, that is just the 3BV score divided by the time the player used to solve the puzzle. Since each 3BV point represents a separate action, higher scores are better (you perform more actions per second).

EDIT: As an example, I'm going to use the one from Wikipedia, which looks like this:

```
0000002M
0000013M
110113M3
M101M3M2
11011222
0000001M
00122222
001MM2M1

```

The algorithm works by marking cells after they have been processed. To visualize that, I will be using a * to indicate a processed cell, and a . to indicate a non-processed cell. Hence, we start with these markings:

```
........
........
........
........
........
........
........
........

```

We're going to start by processing the top-left cell. This is an empty (blank or 0) cell, so we start a flood fill marking all blank cells connected to this one, as well as all non-blank cells directly adjacent to these. We start by marking the cell we're processing:

```
*.......
........
........
........
........
........
........
........

```

The flood fill takes many steps, and exactly how the intermediate steps look depend on exactly how you implement the flood fill. Ultimately, however, it ends up looking like this:

```
*******.
*******.
******..
.***....
*******.
*******.
*******.
***.....

```

That's all one big region, so that just adds 1 to our 3BV calculation.

Since there are no blank cells left, all we need to do is count the number of non-marked, non-mine cells. Those cells are placed at the locations marked #:

```
*******.
*******.
******.#
.***.#.#
*******#
*******.
*******#
***..#.#

```

There are 7 such cells, so we add a total of 7 to the count, leaving a result of 8.

Now, you've mentioned that your representation only contains 0 and 9 (where 9 is a mine). That is, however, just going to change how you determine whether or not a cell is empty - the algorithm is the same. In your case, a cell is empty if the cell and all of its neighbors are all 0.

---
Tags: scoring, minesweeper
---


# Question
Title: How to make a TCP Client Server in java over multiple Networks
So I am trying to write server code for my game, and I am kinda running in a wall. I have seen oracles example for a server and client, but how do I allow it to connect to computers outside my network? Pretty much I'm trying to do the following

Client presses a key to move 1 unit to the left, the server receives the Client's input, checks if any modification is made, if there is send Client back to where they started.

The problem I have is how do I connect a Server and Client on separate internet connections?

# Answer
> 1 votes
The big problem of P2P connections is the **NAT** mechanism:

A gammer PC is probably before a router that use NAT technology, that is, the IP for Internet is not the same that he IP the PC have (local network). NAT change the connection port to work, so listening is not possible.

Solutions:

1. The user need to configure a PORT forwarding, like for emule and other similar software.
2. Any connection is done against a server that does not use NAT, but that is not P2P but client-server.

Connecting to a local server or any one in Internet is the same: you need the **IP** and the **Port** of the listenning server, connect to it/send or receive data/close connetion.

# Answer
> 0 votes
You're going to need to know the IP address of the server and use that as the "host" in your client. Just web-search "what's my IP" from the computer running the server and you can get it.

---
Tags: java, networking, client-server
---


# Question
Title: Detecting if a point is inside a rectangle
I have mouse coordinates in 2D game (x and y) and a rectangle (x, y, width, height). How do I determine if the point is in the rectangle? I do not have any code to post here. I'm just searching for help.

# Answer
While Zhen's example code is perfectly fine, I'd use one big expression (might not be possible based on your actual language):

```
bool pointInRectangle(Rectangle rect, Point point) {
    return p.x >= r.x && // point is right of the left edge
           p.y >= r.y && // point is below the top edge
           p.x <= r.x + r.w && // point is left of the right edge
           p.y <= r.y + r.h; // point is above the bottom edge
}

```

Of course, the whole orientation depends on your coordinate system (e.g. is positive y downwards or upwards). Also using `>=` and `<=` over `>` and `<` determines whether the edges of the rectangle are considered to belong to the actual rectangle.
> 6 votes

# Answer
Pseudocode:

```
function check( r, p )
    if( p.x < r.x or p.x >= (r.x + r.width) ) then return false
    if( p.y < r.y or p.y >= (r.y + r.height) ) then return false

    else return true

```
> 2 votes

---
Tags: intersection
---


# Question
Title: Seek Steering Behavior with Target Direction for Group of Fighters
I am implementing steering algorithms with group management for spaceships (fighters). I select a leader and assign the target positions for the other spaceships based on the target position of the leader and an offset. This works well. But when my spaceships arrive they all have a different direction. I want them to keep to look in the same direction (target - start).

I also want to combine this behavior with a minimum turning radius that is based on the speed. The only idea I have is to calculate a path for each spaceship with an point before the target position, so the ships have some time left to turn into the right position. But I dont know if this is a good idea. I guess there will be a lot of rare cases where this can cause a problem.

So the question is, if anybody knows how to solve this problem and has some (simple code) or pseudocode for me or at least some good explanation.

# Answer
> 1 votes
Assuming this is a 2D game, then I read something in *Game Coding Complete* that may be of interest.

What you need to know is the point you are trying to steer toward (such as a point behind the "leader" of the squadron or an enemy fighter's location), the fighter's current position, and a unit vector (2D vector with a length of 1) pointing 90 degrees to the right of the space ships current heading. This is commonly referred to as the "right vector."

Next, calculate the unit vector that points from the fighter's current location to its target location. Note that it's very important that both the right vector and the vector pointing toward the target location have a length of 1 (floating point inaccuracies like 0.99999997 or 1.00000002 are fine), otherwise the next step won't work.

Next, calculate the dot product of the two vectors like this:

```
Dot_Product = (VecA.X * VecB.X) + (VecA.Y * VecB.Y)

```

If the dot product is less than zero, then the target location is to the fighter's left. If the dot product is greater than zero, then the target location is to the fighter's right. If the dot product is zero, or close to it, then the target location is directly in front of or directly behind the fighter.

You can steer you fighter according to this. Note that a greater speed will result in a larger turn radius, assuming you turn at the same rate, in degrees per second, regardless of velocity.

This solution takes advantage of an interesting property of the dot products of unit vectors (2D or 3D). The closer to pointing in the same direction the two vectors are, the closer to 1 the dot product gets. The closer to pointing in the opposite direction the two vectors are, the closer to -1 the dot product gets. If the dot product is zero, the vectors are at a right angle to each other.

---
Tags: ai, path-finding
---


# Question
Title: Rendering Texture Quad to Screen or FBO (OpenGL ES)
I need to render the texture on the iOS device's screen or a render-to-texture frame buffer object. But it does not show any texture. It's all black.

(I am loading texture with image myself for testing purpose)

//Load texture data

```
UIImage *image=[UIImage imageNamed:@"textureImage.png"];

    GLuint width = FRAME_WIDTH;
    GLuint height = FRAME_HEIGHT;

    //Create context
    void *imageData = malloc(height * width * 4);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(imageData, width, height, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);

    //Prepare image
    CGContextClearRect(context, CGRectMake(0, 0, width, height));
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), image.CGImage);

    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

```

Simple Texture Quad drawing code mentioned here

//Bind Texture, Bind render-to-texture FBO and then draw the quad

```
const float quadPositions[] = {  1.0,  1.0, 0.0,
                                -1.0,  1.0, 0.0,
                                -1.0, -1.0, 0.0,
                                -1.0, -1.0, 0.0,
                                 1.0, -1.0, 0.0,
                                 1.0,  1.0, 0.0 };
const float quadTexcoords[] = { 1.0, 1.0,
                                0.0, 1.0,
                                0.0, 0.0,
                                0.0, 0.0,
                                1.0, 0.0,
                                1.0, 1.0 };

// stop using VBO
glBindBuffer(GL_ARRAY_BUFFER, 0);

// setup buffer offsets
glVertexAttribPointer(ATTRIB_VERTEX, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), quadPositions);
glVertexAttribPointer(ATTRIB_TEXCOORD0, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), quadTexcoords);

// ensure the proper arrays are enabled
glEnableVertexAttribArray(ATTRIB_VERTEX);
glEnableVertexAttribArray(ATTRIB_TEXCOORD0);

//Bind Texture and render-to-texture FBO.
glBindTexture(GL_TEXTURE_2D, GLid);

//Actually wanted to render it to render-to-texture FBO, but now testing directly on default FBO.
//glBindFramebuffer(GL_FRAMEBUFFER, textureFBO[pixelBuffernum]);

// draw
glDrawArrays(GL_TRIANGLES, 0, 2*3);

```

**What am I doing wrong in this code?**

P.S. I'm not familiar with shaders yet, so it is difficult for me to make use of them right now.

# Answer
> 1 votes
`glDrawArrays(GL_TRIANGLES, 0, 2*3)` won't draw anything because you do not have any shaders attached. OpenGL ES 2 does not have a fixed pipeline, therefore you need to implement your own shaders. You can use GLKit's GLKBaseEffect as a shader or better write you own.

I recommend you the following series of tutorials as a starting point: http://iphonedevelopment.blogspot.com/2010/11/opengl-es-20-for-ios-chapter-4.html

---
Tags: textures, iphone, ios, opengl-es, frame-buffer
---


# Question
Title: Pixel size for clips in retro NES-like game?
I'm making a retro videogame, currently I'm using 32px x 32px tiles for the map and 64px x 32px for the characters.

However the game looks extremely small, I could increase the tile size to something like 64px but it seems dumb since I would have to scale all the images (I don't care about adding more definition for the characters than this).

So my question is, should I increase the tile sizes or do it in 32px and zoom/scale the images depending on screen size? Is this how games like Super Mario Bros. do it?

# Answer
Conclusion: Zoom/Scale the image.

Reasoning:

The NES and SNES zoom/scale the image to the screen. The games, however, never needed to. They had a number of sprites they could use, that where a fixed width/height. Those sprites would be referenced to and placed throughout the larger image, which was the resulting image for the game screen. If you recall the size of those pixels, it was a small image (It sound's like you have a similar image.) That image was *automatically* stretched across the screen for the gamer to see.

Just increasing the tile size wouldn't be enough. If that's how you go about it, then when it's rendered on a bigger screen, the whole thing just becomes small again. On top of that, if you aren't going to use the extra detail, then it's a wast of resources, Having more pixels to process, needing more RAM to store it, and the moment the Computer monitor get's bigger/higher-res your game becomes a tiny little picture again.
> 0 votes

# Answer
Two parts: you don't need to scale up your source assets, and you don't need to scale them based on screen size.

First, your assets may be drawn at any size on screen; they aren't limited to their own resolution. Their appearance when scaled is a function of how they are sampled by the graphics hardware while rendering a 2D quad. If you want the retro look, that implies that you want them to retain their "pixelyness" when scaled up. The method for that is nearest-neighbor interpolation.

That wikipedia is pretty sparse, but the general idea is that each element in the pixel shader takes its color from one and only one pixel in the source texture, rather than an interpolation of multiple close pixels (which would result in a blurry image). i.e., the source is not antialiased.

Here's an example. Disregard the rotated and re-scaled images, this was taken from a mostly unlreated blog article about texture sampling by Shawn Hargreaves, the former XNA project lead.

I don't know what the equivalent SDL setting would be, perhaps commenters can fill in that blank for me. But in XNA, this is accomplished by setting the texture sampler state to `SamplerState.PointClamp`, which is a high-level abstraction of a config options for the graphics hardware.

The second part of my answer is about scaling to screen size. I don't think you should do this on a per-sprite basis. You *might* need to scale the whole rendering of your game to match screen resolution, but this should be independent from your individual tiles. Your tiles should be scaled relative to your game window, not the screen itself. I think this distinction is important; you don't want to have to detect screen size for every tile you draw.

It would be better to draw an item at an appropriate size in world coordinates, and scale your camera's view to show it in proper proportion to the screen.

### Edit: one good example

In the The Platformance:... games, the zoom levels show all the same graphics, but at varying zoom levels. Close up, the images are intentionally blocky. But in the wide view, they appear like any other 2d art.
> 0 votes

---
Tags: c++, sdl
---


title: Hook into League of Legends client

text:
# Question
Title: Hook into League of Legends client
I would like to write a small software which will hook into the League of Legends client and record my performances and store them locally, because Riot only stores last 10 matches. Is there some way through which I can trigger an event when I finish a game ? For those who know, I would like it to work similarly to League Recorder, but it will record only your final stats (KDA, Gold, Creep Score, etc.). I was thinking of searching for the client in the process list, and doing some checks by getting the last 10 matches, but I don't know of any way to see which user is logged in and how to download the history. I'm currently not bound to any languages, and I can work in C++/C#/Java.

# Answer
I don't know much about how league if written, but you could always gather the information from the Launcher since it records the last 10 games, and you just record every one after that. Once you gather the information you need you can organize it into a table and average it out etc.

Since Leagues Client uses Adobe Air, you could really just create a script in a simple Memory Editor like Cheat Engine and Gather the information like that.

**The above approach is certainly against Leagues EULA, so while it is available be aware that you risk getting banned**

I don't know much programming other than java, but I'm sure if you wanted you could poll the information from Lolking using HTTP connections in java and reading the website
> 0 votes

---
Tags: c++, c#, java, networking
---


# Question
Title: Move Player on Mouse click in update loop
I'm trying to move my player when clicking the right button on the mouse. The problem is that my player is just standing and "shaking" in the top left corner.

Any idea?

```
package game;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;

import javax.swing.JLabel;

public class Player {
    private Rectangle playerRec;
    float x, y;
    PlayerJLabel playerJLabel;
    int worldX = 800;
    int worldY = 600;
    int targetX, targetY;

    public Player(int posX, int posY, int size){
        playerRec = new Rectangle(posX, posY, size, size);
        x = posX;
        y = posY;

        playerJLabel = new PlayerJLabel();
        playerJLabel.setBounds(0, 0, 800, 600);

        Game.screen.add(playerJLabel);
    }

    public void update(float timeSinceLastFrame){

        if (Mouse.isMouse(MouseEvent.BUTTON3)) {
            targetX = Mouse.getX();
            targetY = Mouse.getY();
        }

        if ((targetX != 0 && targetX != x) && (targetY != 0 && targetY != y)) {
            float dx = (float) (targetX-x);
            float dy = (float) (targetY-y);

            // normalize
            float length = (float) Math.sqrt(dx*dx+dy*dy);
            dx/=length;
            dy/=length;

            // add speed
            x = dx * timeSinceLastFrame * 300;
            y = dy * timeSinceLastFrame * 300;

            // Move the player
            playerRec.x = (int) x;
            playerRec.y = (int) y;

        }

    }

    private Rectangle getRec(){
        return playerRec;
    }

    public class PlayerJLabel extends JLabel{
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.RED);
            g.fillRect(getRec().x, getRec().y, getRec().width, getRec().height);
        }
    }

}

```

Edit: I have a GameState method which calls the player update() method and a repaint() method which repains the whole scene.

GameState update method:

```
@Override
public void update(float lastFrame) {
    player.update(lastFrame);
}

```

Game repaint method:

```
public void repaint() {
            // screen is a JFrame Object
    screen.repaint();
}

Main class

package game;

public class Main {

    public static void main(String[] args) {
        Game game = new Game("Mein erstes Spiel", 800, 600);

        long lastFrame = System.nanoTime();

        while(game.isRunning()) {
            long thisFrame = System.nanoTime();
            float timeSinceLastFrame = ((float)(thisFrame-lastFrame))/100000f;
            lastFrame=thisFrame;

            game.nextState();
            game.update(timeSinceLastFrame);
            game.repaint();
        }

    }

}

```

Update 2:

I updated my code to:

```
        // Move the player
        x = playerRec.x += (int) (dx * timeSinceLastFrame * 500);
        y = playerRec.y += (int) (dy * timeSinceLastFrame * 500);

```

My player is moving, but not at the same speed and not very smooth: http://screencast.com/t/pv5M9Un4QhFR

# Answer
> 5 votes
I do know.

```
    // add speed
    x = dx * timeSinceLastFrame * 300;
    y = dy * timeSinceLastFrame * 300;

    // Move the player
    playerRec.x = (int) x;
    playerRec.y = (int) y

```

Is effectively the same as saying

```
    // Move the player
    playerRec.x = (int) (dx * timeSinceLastFrame * 300);
    playerRec.y = (int) (dy * timeSinceLastFrame * 300);

```

You may instead wish to do:

```
    // Move the player
    playerRec.x += (int) (dx * timeSinceLastFrame * 300);
    playerRec.y += (int) (dy * timeSinceLastFrame * 300);

```

You needed +=, not =.

Happens to me all the time.

---
Tags: java
---


# Question
Title: HTML5 Canvas Parsing image into tileset while preserving transparency
I'm trying to import a Tiled Map Editor JSON file into my HTML5 canvas game but I'm having trouble with separating out the tileset image into separate images while preserving the transparency.

Currently I'm using a temporary canvas element and the `getImageData()` and `putImageData()` functions to grab specific parts of the tileset image and push the separate "tile" image into an array.

I understand that `putImageData()` renders the Image Data pixel by pixel, thus filling the transparent pixels with the background color of the page, but I can't figure out exactly how to fix this.

You can see the problem here:

Here's the code:

```
(function() {

var tilesets = [];
var tiles = [];
tiles.push(null);

tmxJSON = {

    map: null,

    load: function(jsonFile) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                // Call function for next step in process
                tmxJSON.parse(xhr.responseText);
            }
        }
        xhr.open("GET", jsonFile, true);
        xhr.send();
    },

    parse: function(json) {
        map = eval("(" + json + ")");

        tmxJSON.loadTilesetImages();

    },

    loadTilesetImages: function() {

        var successCount = 0;
        var errorCount = 0;

        for (var ts = 0; ts < map.tilesets.length; ts++) {

            var image = new Image();
            image.addEventListener("load", function() {
                successCount++;
                if (successCount + errorCount == map.tilesets.length) {
                    tmxJSON.separateTiles();
                }
            });
            image.addEventListener("error", function() {
                errorCount++;
                alert("error loading: " + map.tilesets[ts].image);
            });
            image.src = map.tilesets[ts].image;

            tilesets.push(image);

        }

    },

    separateTiles: function() {

        for (var ts = 0; ts < tilesets.length; ts++) {

            var tileCanvas = document.createElement("canvas");
            var tileContext = tileCanvas.getContext("2d");

            tileCanvas.width = tilesets[ts].width;
            tileCanvas.height = tilesets[ts].height;

            tileContext.drawImage(tilesets[ts], 0, 0);

            var nTilesX = tilesets[ts].width / map.tilewidth;
            var nTilesY = tilesets[ts].height / map.tileheight;

            for (ty = 0; ty < nTilesY; ty++) {
                for (tx = 0; tx < nTilesX; tx++) {
                    var x = tx * map.tilewidth;
                    var y = ty * map.tileheight;

                    var imageData = tileContext.getImageData(x, y, map.tilewidth, map.tileheight);

                    tiles.push(imageData);
                }
            }
        }
        tmxJSON.drawTiles();
    },

    drawTiles: function() {

        for (var l = 0; l < map.layers.length; l++) {
            var x = 0;
            var y = 0;
            if (map.layers[l].type === "tilelayer") {
                for (var d = 0; d < map.layers[l].data.length; d++) {

                    if (d % map.width == 0 && d != 0) {
                        y += map.tileheight;
                        x = 0;
                    }

                    if (map.layers[l].data[d] != 0) {
                        context.putImageData(tiles[map.layers[l].data[d]], x, y);
                    }
                    x += map.tilewidth;
                }

            }
        }

    }
};

}());

```

EDIT: Alright I've taken the advice of Mokosha and changed the putImageData to drawImage using a separate canvas, but I'm coming up with this error:

```
GET http://storrdev.com/tmxJSON/[object%20HTMLCanvasElement] 404 (Not Found)

```

This is something I was running into before when I tried something like this... and the reason I abandoned it. What is happening? I printed all the x and y coordinates for each tile and they all appear to load just fine until the last one... I'm so confused!

Here's the updated code:

```
(function() {

var tilesets = [];
var tiles = [];
tiles.push(null);

tmxJSON = {

    map: null,

    load: function(jsonFile) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                // Call function for next step in process
                tmxJSON.parse(xhr.responseText);
            }
        }
        xhr.open("GET", jsonFile, true);
        xhr.send();
    },

    parse: function(json) {
        map = eval("(" + json + ")");

        tmxJSON.loadTilesetImages();

    },

    loadTilesetImages: function() {

        var successCount = 0;
        var errorCount = 0;

        for (var ts = 0; ts < map.tilesets.length; ts++) {

            var image = new Image();
            image.addEventListener("load", function() {
                successCount++;
                if (successCount + errorCount == map.tilesets.length) {
                    tmxJSON.separateTiles();
                }
            });
            image.addEventListener("error", function() {
                errorCount++;
                alert("error loading: " + map.tilesets[ts].image);
            });
            image.src = map.tilesets[ts].image;

            tilesets.push(image);

        }

    },

    separateTiles: function() {

        for (var ts = 0; ts < tilesets.length; ts++) {

            var tileCanvas = document.createElement("canvas");
            var tileContext = tileCanvas.getContext("2d");

            tileCanvas.width = map.tilewidth;
            tileCanvas.height = map.tileheight;

            var nTilesX = tilesets[ts].width / map.tilewidth;
            var nTilesY = tilesets[ts].height / map.tileheight;

            for (ty = 0; ty < nTilesY; ty++) {
                for (tx = 0; tx < nTilesX; tx++) {
                    var x = tx * map.tilewidth;
                    var y = ty * map.tileheight;

                    tileContext.drawImage(tilesets[ts], -x, -y);

                    //var imageData = tileContext.getImageData(x, y, map.tilewidth, map.tileheight);\

                    console.log(x + ", " + y);

                    var tile = new Image();
                    tile.src = tileCanvas;

                    tiles.push(tile);
                }
            }
        }
        tmxJSON.drawTiles();
    },

    drawTiles: function() {

        for (var l = 0; l < map.layers.length; l++) {
            var x = 0;
            var y = 0;
            if (map.layers[l].type === "tilelayer") {
                for (var d = 0; d < map.layers[l].data.length; d++) {

                    if (d % map.width == 0 && d != 0) {
                        y += map.tileheight;
                        x = 0;
                    }

                    if (map.layers[l].data[d] != 0) {
                        context.drawImage(tiles[map.layers[l].data[d]], x, y);
                    }
                    x += map.tilewidth;
                }

            }
        }

    }
};

}());

```

# Answer
> 0 votes
Alright I've found the solution to my problem.

Following Mokosha's advice was the way to go, but in my edit I only went halfway. I found out that when creating an Image() from a separate canvas you need to use the canvas method .toDataURL("image/png");

Here's the website I used to figure that part out: http://davidwalsh.name/convert-canvas-image

You can see my correct code below:

```
(function() {

var tilesets = [];
var tiles = [];
tiles.push(null);

tmxJSON = {

    map: null,

    load: function(jsonFile) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                // Call function for next step in process
                tmxJSON.parse(xhr.responseText);
            }
        }
        xhr.open("GET", jsonFile, true);
        xhr.send();
    },

    parse: function(json) {
        map = eval("(" + json + ")");

        tmxJSON.loadTilesetImages();

    },

    loadTilesetImages: function() {

        var successCount = 0;
        var errorCount = 0;

        for (var ts = 0; ts < map.tilesets.length; ts++) {

            var image = new Image();
            image.addEventListener("load", function() {
                successCount++;
                if (successCount + errorCount == map.tilesets.length) {
                    tmxJSON.separateTiles();
                }
            });
            image.addEventListener("error", function() {
                errorCount++;
                alert("error loading: " + map.tilesets[ts].image);
            });
            image.src = map.tilesets[ts].image;

            tilesets.push(image);

        }

    },

    separateTiles: function() {

        var successCount = 0;

        for (var ts = 0; ts < tilesets.length; ts++) {

            var nTilesX = tilesets[ts].width / map.tilewidth;
            var nTilesY = tilesets[ts].height / map.tileheight;

            for (ty = 0; ty < nTilesY; ty++) {
                for (tx = 0; tx < nTilesX; tx++) {
                    var tileCanvas = document.createElement("canvas");
                    var tileContext = tileCanvas.getContext("2d");

                    tileCanvas.width = map.tilewidth;
                    tileCanvas.height = map.tileheight;

                    var x = tx * map.tilewidth;
                    var y = ty * map.tileheight;

                    tileContext.drawImage(tilesets[ts], -x, -y);

                    var tile = new Image();
                    tile.src = tileCanvas.toDataURL("image/png");

                    tiles.push(tile);
                }
            }
        }
        tmxJSON.drawTiles();
    },

    drawTiles: function() {

        for (var l = 0; l < map.layers.length; l++) {
            var x = 0;
            var y = 0;
            if (map.layers[l].type === "tilelayer") {
                for (var d = 0; d < map.layers[l].data.length; d++) {

                    if (d % map.width == 0 && d != 0) {
                        y += map.tileheight;
                        x = 0;
                    }

                    if (map.layers[l].data[d] != 0) {
                        context.drawImage(tiles[map.layers[l].data[d]], x, y);
                    }
                    x += map.tilewidth;
                }

            }
        }

    }
};

}());

```

# Answer
> 0 votes
It's not completely clear what you're trying to do, but I assume you have a "sprite sheet" and you're trying to cut out the individual sprites into their own Image objects to later draw on a canvas using a 2d context's drawImage method.

Assuming that's what you want to do, it's not necessary. I've implemented animation using sprite-sheets in my game and I didn't copy any of the images, I just draw them directly from the sheet using drawImage.

---
Tags: javascript, html5, html-canvas, transparency
---


# Question
Title: Algorithm for creating tree-like network structures
I'm trying to procedurally model tree-like network structures with the following properties:

* A root with variable number of nodes
* A variable depth of nodes
* When graphically laid out, edges or nodes must never intersect or overlap

I don't have a background in maths or programming, so I am not sure that I am using the correct terminology. Maybe a picture would better explain what I am after:

I know my way around Ruby pretty well, so I think I should be able to implement a basic algorithm that generates these models. Any pointers or recommendations?

# Answer
Graph drawing is a little more directly relevant than the whole field of graph theory.

In particular, I'm a fan of force-based layout. See this demo from the D3 library for an introduction.

The basic idea is that you model the graph edges with springs or repulsors, and use a physics integration method to "resolve" the positions of all the nodes. You can do this in real-time like the previous demo, which is kind of fun but also distracting, or you can do a number of physics iterations before rendering a final static layout.

That D3 library has a large number of other layout modes to inspire you with, and being JavaScript-based is a great way to prototype or experiment with any layout algorithms you're interested in.
> 5 votes

# Answer
First, in order for your graph to obey the crucial property of `any two edges do not cross`, it must be a planar graph.

A tiny tutorial on the graph drawing topic is given here.

Using force driven layouts may not guarantee convergence to a planar graph: (for example, if a vertex is inside a face, apply an elastic spring force and push the vertex outside the face using the nearest edge normal). This approach would be interesting to animate, but it might not converge (unless it has been proven somewhere..?).

So, while I cannot reproduce here an algorithm for untangling a planar graph (or downright drawing it in its canonical form), there are plenty of resources dealing with the issue (some in linear time):

**NOTE**: if your graph is a *tree*, then I suggest reading this.

**RELATED**: "Untangle"-Game AI
> 1 votes

# Answer
You could use some form of Space Colonisation.

Examples ProcWorld and Sea of Memes show growing 'real trees', but could probably be adapted for arbitrary tree structures.

Space Colonisation assumes you have some limited area to be filled by a competitive 'lifeform' which grows over one or more iterations. This competitive aspect might not fit what you're wanting to do, if you're just wanting to generate random trees/graphs with no overlap.

EDIT:

Space Colonisation has certain conditions on the growth that *I think* pretty much guarantee no overlapping edges (and normally you'd process the tree afterwards anyway) - but it will only help you if you **don't** already have a graph/tree.

So if you already have a graph, Space Colonisation will not help you - see other answers like @Sean's force-based layout. If you are generating a graph while also needing to lay it out (or can store some position information for later) - this might to what you need.
> 1 votes

---
Tags: algorithm, tree
---


# Question
Title: Moving sprite from one vector to the other
I'm developing a game where enemy can shoot bullets towards the player. I'm using 2 vector that is normalized later to determine where the bullets will go.

Here is the code where enemy shoots:

```
private void UpdateCommonBullet(GameTime gt)
        {
            foreach (CommonEnemyBullet ceb in bulletList)
            {
                ceb.pos += ceb.direction * 1.5f * (float)gt.ElapsedGameTime.TotalSeconds;
                if (ceb.pos.Y >= 600) ceb.hasFired = false;
            }

            for (int i = 0; i < bulletList.Count; i++)
            {
                if (!bulletList[i].hasFired)
                {
                    bulletList.RemoveAt(i);
                    i--;
                }
            }
        }

```

And here is where i get the direction (in the constructor of the bullet):

```
direction = Global.currentPos - this.pos;
direction.Normalize();

```

`Global.currentPos` is a Vector2 where currently player is located, and is updated eveytime the player moves.

This all works fine except that the bullet won't go to player's location. Instead, it tends goes to the "far right" of the player's position.

I think it might be the problem where the bullet (`this.pos` in the direction) is created (at the position of the enemy). But I found no solution of it, please help me.

# Answer
> 3 votes
If you are using spritebatch.draw(texture, vector2, color) vector2 value is the top left of the sprite, there are two ways you could fix it. The first is that you could add width/2 and height/2 to global.currentposition. The second, which is probably a better solution is to modify the draw code so that the vector2 for the draw position is playerPosition minus width/2 and height/2 this means that that the player position is the center of the sprite.

---
Tags: xna, vector
---


# Question
Title: Convert global rotation into local rotation
I have an object in my game and I have its location, rotation and scaling in separate float\[3\]. The location rotation and scale are all on the global axis; these do not change based on the objects rotation. How would I convert them to the local axis where the xyz always corresponds to the same face?

# Answer
> 3 votes
1. invert the object's transform
2. apply that transformation to your world space rotation
3. the result is your object space rotation

---
Tags: opengl, java, mathematics
---


# Question
Title: How to effectively check for object visibility prior to object creation?
I'm using pseudo-random noise to create a cube world a la Minecraft. So I've got my noise generators up and running, working great. Right now I'm just directly scaling the noise output to a height and assuming everything below that is solid, I intend to go back later and add some caves, pits, etc. My problem right now is taking these three dimensional integer arrays, and turning them into blocks. I'm hitting a big wall there.

After the numerical list, it's taking almost 30 seconds for a chunk(16x128x16) to generate. That's not counting rendering, that's fast enough iff I don't draw every block in the chunk at one time.

My first approach wast to draw all 20,000+ blocks every frame. I figured out that was bad really fast because I was getting maybe 2 fps.

Then I decided it was better to check if the block was exposed before rendering it. That is when I started to get a huge slowdown. If my list indicated a block existed, then I would check the value of the array in all six directions surrounding the cube with my integer list to see if they also held a cube. This works great, but as I said, my generation time for just one chunk is ~30 sec.

My Exposure check code:

```
        public bool determineExposed(int x, int y, int z)
    {
        try
        {
            if (_list[x + 1, y, z] == 1 && _list[x - 1, y, z] == 1 && _list[x, y + 1, z] == 1 && _list[x, y - 1, z] == 1 &&
                _list[x, y, z + 1] == 1 && _list[x, y, z - 1] == 1) return false;
            else return true;
        }
        catch
        {
            return false;
        }
    }

```

How Can I speed this up?

# Answer
Okay, I forgot to post the answer to this problem. Come to find out, the try-catch running a few thousand times per chunk was the bottleneck. Once I circumvented it with if/elseif(s) is sped up immensely, generating a chunk in a few ms! Thanks for the help!
> 1 votes

# Answer
This is not your problem, im guessing. You need to create a single vertex array for every block in the view frustum, and send that to your gpu shader in a draw call. The code you pasted is probably part of your generation call, which usually isnt as much of a problem as the tesselation call. Look at my Techcraft code on codeplex.com for an example of how this can be done single threaded.
> 1 votes

# Answer
Two things come to mind:

1) Cache your results. You shouldn't be looking at the neighbors. Any block should always know if it's invisible (6 opaque neighbors) and if so it doesn't participate in the rendering at all. Store this as visible/invisible/unknown, only do the calculation if it's unknown. When you edit a block you set it's 6 neighbors to unknown or else you recalculate them at that time. It's probably not worth saving this flag to disk, though.

2) My inclination would be to floodfill your drawing rather than even consider most of the blocks. Take an array big enough to hold a flag (render/transparent/unseen/unknown) for every cell out to your max render distance. Init it to unknown and start from your viewpoint, traverse this like a tree but you only process cells that are unknown so you do each cell only once. For each non-opaque block you add each of it's neighbors to the list. Once you have the list you only render the ones with a status of render. Beware recursion depth here, a breadth-first traversal is a lot safer.

I have done this once, the approach based on rendering all surfaces failed badly, the second try was based on such a traversal and rendered far faster than I needed so I didn't tweak it any more. Doing it breadth-first also gave me an easy way to know the light level (although I did *NOT* do it like Minecraft--I did the light level at the vertices rather than the blocks. This made things smoothly fade to black when they were too far away rather than the pixellated effect you get with Minecraft.

You can chop the problem even further by not even considering cells outside the player's field of view.

Note that unless your render distance is huge the number of blocks that actually make it to the render list is not much more than the surface area that you can see.
> 0 votes

---
Tags: xna, perlin-noise
---


# Question
Title: When input listener set in resize(), input doubles
I created a button and assigned an input listener in the resize() method of the screen.

For simplicity's sake, whenever I press the button, 1000 adds to a total amount. The weird part is, it adds 2000 when I press the button. Then I moved the button's input listener addition to the constructor - now it works perfectly adding 1000.

For some odd reason, if I set the input handler in the resize method it somehow does everything it is supposed to twice. The game works when I transfer that piece of code to the constructor, but why on earth did it do the assigned thing twice?

This is the code I use for attaching the input listener:

```
button.addListener(new InputListener() {
        public boolean touchDown (InputEvent event, float x, float y, int   pointer, int button) {
                return true;
        }

        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
                count += increment;
                countLabel.setText(String.valueOf(count));
        }
    });

```

# Answer
> 1 votes
> For some odd reason, if I set the input handler in the resize method it somehow does everything it is supposed to twice. The game works when I transfer that piece of code to the constructor, but why on earth did it do the assigned thing twice?

If the Resize event gets called multiple times, you will add your event handler for each time it's called. Event handlers *can* be added multiple times, and they will run once for each time they're added. Your event handler worked fine, the problem is just that your handler was called more than once.

When you moved it to the constructor, you moved it to a place that would *only ever* be called once, so that worked just fine.

If the Resize event was ever called a third time, clicking the button would run the handler *three* times, incrementing the value that many times. I haven't used libgdx, but if this would occur when the phone orientation changes, you should definitely not be putting listeners like this in the Resize event.

Majd's answer explains why the Resize method would be called twice. Seems like it's safer to place those listeners elsewhere - like you have done.

# Answer
> 1 votes
This is a well known (feature) that has to do with the way Android reports the screen size. It seems to do it once for the wrong orientation and once for the correctone. I've seen some people have success by locking the orientation in the manifest. Here are some forum posts on this topic:

Libgdx forum post 1

Libgdx forum post 2

Libgdx forum post 3

Libgdx forum post 4

---
Tags: libgdx
---


# Question
Title: Getting a sprite from multiple sprites for right material pattern
Not sure how accurate the question was but I'll put it this way. I'm developing a game where player will construct his/her own stuff, like bridge, building etc. using cocos2d-iphone and Box2D. First they'll draw the draft on a blueprint and then what's drawn will be transported to physics engine and finally the bodies will be wrapped with costumes. Let's say we're building a bridge and the bridge is going to be made of wood. I don't want the wood to be plain brown, I rather want it to be more natural, have some woody patterns on it. Here's my problem: A bridge component might be of any length, how can I achieve maximum realistic wood pattern? The only idea that comes to my mind is to take an image, slice it into 1 pixel width images, number them by order and attach them side by side upon need. Do you have any other suggestions? What's the general practice?

# Answer
Good points from NauticalMile. You could download one of many free textures that are already set up to tile nicely, or create one yourself using Photoshop or similar. To make the scaling match use the length of the wood pieces as the tiling factor. Alternately if you are strongly against visible repetition you could use a pixel shader instead of a texture. Wood grain, marble and various other materials have been simulated decently with variations on Perlin noise.
> 3 votes

---
Tags: sprites, box2d, cocos2d-iphone
---


# Question
Title: OpenGL ES 2.0 obscured texture is visible
Hi, I am using LibGDX and OpenGL 2.0 to create a game. So far I have created two meshes. The front mesh is the one with the brown circle texture and another mesh on the top with a green to white gradient texture. I am using a perspective camera and everything looks ok except for one small artefact where one of the textures that should be obscured from view by another is showing through(see image).

I am fairly new to OpenGL and LibGDX. I have culling enabled on the back faces and was under the impression the problem could be solved with GL\_DEPTH\_TEST. If I set the glDepthFunc to GREATER or to LESS nothing is displayed. Currently I am using LEQUAL. So I am not sure if I am on the right track or if the problem is caused else where. Any help would be appreciated.

I am using some very simple shaders:

```
    String vertexShader = "attribute vec4 a_position;    \n" +
                "attribute vec4 a_color;\n" +
                "attribute vec2 a_texCoord0;\n" +
                "uniform mat4 u_worldView;\n" +
                "varying vec4 v_color;" +
                "varying vec2 v_texCoords;" +
                "void main()                  \n" +
                "{                            \n" +
                "   v_color = vec4(1, 1, 1, 1); \n" +
                "   v_texCoords = a_texCoord0; \n" +
                "   gl_Position =  u_worldView * a_position;  \n"      +
                "}                            \n" ;
String fragmentShader = "#ifdef GL_ES\n" +
                  "precision mediump float;\n" +
                  "#endif\n" +
                  "varying vec4 v_color;\n" +
                  "varying vec2 v_texCoords;\n" +
                  "uniform sampler2D u_texture;\n" +
                  "void main()                                  \n" +
                  "{                                            \n" +
                  "  gl_FragColor = v_color * texture2D(u_texture, v_texCoords);\n"+
                  "}";

```

Culling and depth has been set with:

```
Gdx.gl.glEnable(GL20.GL_CULL_FACE);
Gdx.gl.glCullFace(GL20.GL_BACK);

Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glDepthFunc(GL20.GL_LEQUAL);

```

Render code:

```
grassTexture.bind(); //the top mesh texture
shader2.begin();
shader2.setUniformMatrix("u_worldView", cameraSystem.camera.combined);
shader2.setUniformi("u_texture", 1);
topMesh.render(shader2, GL20.GL_TRIANGLES);
shader2.end();

texture.bind(); //the brown circle texture
shader2.begin();
shader2.setUniformMatrix("u_worldView", cameraSystem.camera.combined);
shader2.setUniformi("u_texture", 0);
mesh.render(shader2, GL20.GL_TRIANGLES);
shader2.end();

```

Clearing:

```
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT| GL20.GL_DEPTH_BUFFER_BIT);

```

UPDATED INFO:

The idea is that I am trying to create a 2.5D terrain. The brown area is the cross section of the terrain and the 2D part. The green terrain is the "roof" and it has the z-depth set to give it the 2.5D perspective look. The problem is that the section in the circle should not be visible. One can see that there is a slight hill with the green roof, and then the terrain dips down. The roof of the terrain in the dip is not being blocked form view by the top roof part. It is the only section that this is happening. I have shaded the part that should be hidden in pink.

As for my z-orders I have set the indices to create triangles in a counter-clockwise order. I think that part is correct as if I change the culling from back to front I get the expected results. The way I create the top mesh is to iterate backwards through a Box2D chainshape (that the physics uses) and setting the z to -10, I then loop again but this time from the start and add the positions with z set to 0. This creates a circular mesh. From top down this creates a rectangle that I subdivide into quads which I then break down into triangles. This is the code that does it:

```
  ChainShape shape =  ((ChainShape)fix.getShape());
      vertices= new float[(shape.getVertexCount()*2*9)];

      float b = 1f;
      indicies = new short[(shape.getVertexCount()-1)*2*3];
      int c = 0;

      for(int i=shape.getVertexCount()-1;i>=0;i--)
      {

          //back part of mesh starting from right to left
          Vector2 va = new Vector2();
          shape.getVertex(i, va);
          vertices[c] = va.x*b+pos.x;
          c++;
          vertices[c] = va.y*b+pos.y;
          c++;
          vertices[c] = -10.0f;
          c++;

          //colour
          vertices[c] =1;
          c++;
          vertices[c]= 1;
          c++;
          vertices[c] =1f;
          c++;
          vertices[c] =1f;
          c++;

          //uv
          vertices[c] =(va.x*b+pos.x)/20f;
          c++;
          vertices[c] =0;
          c++;

      }

      for(int i=0;i<shape.getVertexCount();i++)
      {
          //front part of mesh starting from left to right
          Vector2 va = new Vector2();
          shape.getVertex(i, va);
          vertices[c] = va.x*b+pos.x;
          c++;
          vertices[c] = va.y*b+pos.y;
          c++;
          vertices[c] = 0.0f;
          c++;

          vertices[c] =1f;
          c++;
          vertices[c] =1f;
          c++;
          vertices[c] =1f;
          c++;
          vertices[c] =1f;
          c++;

          vertices[c] =(va.x*b+pos.x)/20f;
          c++;
          vertices[c] =1;
          c++;
      }

      short val = (short)(0);
      for(int i=0;i<indicies.length;)
      {

          indicies[i]=(short) (val);
          i++;
          indicies[i]=(short) ((shape.getVertexCount()*2-1)-val);
          i++;
          indicies[i]=(short) (val+1);
          i++;

          indicies[i]=(short) ((shape.getVertexCount()*2-1)-val);
          i++;
          indicies[i]=(short) ((shape.getVertexCount()*2-1)-(val+1));
          i++;
          indicies[i]=(short) (val+1);
          i++;
          val++;

      }

```

# Answer
You are setting up the depth test correctly. Note that the backface culling is not needed for this case, although it's still good to enable for other reasons.

A likely reason why your depth test is not working correctly could be using 0.0 as the near plane when calling `gluPerspective`. See https://stackoverflow.com/questions/4764057/opengl-depth-test-not-working-as-expected for more information. After fixing this by using a positive near z, the default depth function GL\_LESS should also work.
> 4 votes

---
Tags: opengl, libgdx, opengl-es2
---


# Question
Title: How to do frame by frame animation in android using open gl es
I have application in some part i am using `AndroidDrawable` for `animation` but it giving jerking effect that why i planed to change the code to `Open Gl ES` for better performance .so far i have googled a lot but did not got any good example .anybody has any idea????

# Answer
> 4 votes
First you'll need to be able to setup OpenGL ES for 2D rendering. Have a look at this answer on SO for some basic introductory info on how to setup and get a texture loaded and ready for 2D rendering.

Once you have that going it is a simple matter of changing the bound texture at some interval. First, you will need some class members (globals):

```
// these are globals (class members)
double time = System.nanoTime();   // time value (initialize it)
float frameTime = 0;               // frame animation time
int frames[10];                    // 10 animation frames
int currentFrame = 0;              // active frame

```

Next, you should load the animation frames as textures during startup, or when you need them (see the answer above for details).

The final piece of the puzzle would happen in `onDraw` each frame. Something like this:

```
// calculate the elapsed time, and update timer
float elapsedTime = ( System.nanoTime() - time ) / 1000000000.0f;
time = System.nanoTime();

// now you can use the elapsed time to determine when to switch frames
frameTime += time;             // count frame time
if ( frameTime >= 0.06f )  {   // if 1/60th of a second passed (for 60fps)
   frame++;                    // step to next frame
   if ( frame > 9 )            // if end of sequence
      frame = 0;               // restart sequence
}

// now you just bind the current "frame" as the texture
gl.glBindTexture( GL10.GL_TEXTURE_2D, frames[currFrame] );

```

This is a very basic example of what you need to do. Of course, there are many different (and even better) ways of doing this but this should get you started in the right direction.

One very important thing you might want to investigate (instead of using this method) is using a texture atlas (where multiple frames are placed on the same texture) and instead of switching the bound texture each update, you simply switch the texture coordinates. This is especially essential if you will have many animated sprites onscreen at once, so as not to kill your framerate :) Here is a very basic example.

---
Tags: android, opengl-es
---