# Question
Title: Fastest way to draw small particles in opengl?
Quick question : Which is the fastest method to render a large array of 4x4/8x8 particles in opengl ? Currently i spend 2triangles for each one but i think that its slow so i would really like to know if im doing it right.....

# Answer
You can draw points with OpenGL.

You want to call **glDrawArrays()** or **glDrawElements()** with **GL\_POINTS** (instead of GL\_TRIANGLE\_STRIP or whatever you are using.)

This will draw points to the screen based on the current point size, which you can set via glPointSize(). You can also alias these points, but in my experience not all drivers / hardware supports aliased points.

You can't texture these points; they are just a single color.
> 6 votes

# Answer
In core OpenGL 3.2 and above, geometry shaders are available for use. To give a brief overview, you would only tell OpenGL to draw the points that represent the positions of your particles, and these points would pass through the vertex shader normally, but then when they get to the geometry shader, it constructs the rectangle (out of two tris) by emitting vertices to the next stage of the pipeline. Along with the vertices you can programmatically generate normals and texture coordinates.

Since this is all done in hardware, I'm pretty sure it's the fastest way right now to render point-sprite particles.
> 3 votes

---
Tags: opengl, graphics, software-engineering
---


# Question
Title: Is knowledge of hacking mechanisms required for an MMO?
Say I was planning on, in the future (not now! There is alot I need to learn first) looking to participating in a group project that was going to make a massively multiplayer online game (mmo), and my job would be the networking portion. I'm not that familiar with network programming (I've read a very basic book on PHP, MYSQL and I messed around a bit with WAMP).

In the course of my studying of PHP and MYSQL, should I look into hacking? Hacking as in port scanning, router hacking, etc. In MMOs people are always trying to cheat, bots and such, but the worst scenario would be having someone hack the databases. This is just my conception of this, I really don't know. I do however understand networking fairly well, like subnetting/ports/IP's (local/global)/etc.

In your professional opinion, (If you understand the topic, enlighten me) Should I learn about these things in order to counter the possibility of this happening?

Also, out of the things I mentioned (port scanning, router hacking) Is there anything else that pertains to hacking that I should look into? I'm not too familiar with the malicious/Security aspects of Networking.

And a note: I'm not some kid trying to learn how to hack. I just want to learn as much as possible before I go to college, and I really need to know if I need to study this or not.

# Answer
> 16 votes
Yes, somebody (in fact, multiple somebodies) on the team that develops any multiplayer game, regardless of scale, should have a strong working knowledge of networking security concepts at both the hardware and software level.

This is especially true for games that will involve a lot of persistence of agency, since that constitutes investment on the part of the player and consequently is something that makes a lucrative target for hackers.

Taking networking/network security/general security (crytography, et cetera) classes in college will be helpful in giving you some of the requisite background knowledge to be one of those aforementioned developers.

# Answer
> 11 votes
Knowing something about security is a good idea before trying to write a multiplayer game, but things like port scanning and router hacking, or even cryptography, are *not* what you should be looking into at this stage.

Rather, the things you should learn about are **trust**, **validation** and **robustness**. Knowing a little bit about psychology, especially about challenges and rewards, is not a bad thing either. I can't really teach you much of that in a short answer like this, but here are some tips to get you started with secure programming:

* Treat any input from outside your direct control as if it might not be what you expect. That includes all user input, anything you receive over the network, and even anything from other parts of your codebase. Try to get into the mindset of not thinking about what the input *should* contain, or even about what an attacker *might* feed you instead, but simply about what the input *could* possibly be and how to safely handle any possible input you might get.
* Since you mention PHP and MySQL, start by looking at SQL injection and cross-site scripting attacks. If you're also familiar with low-level languages like C, look into buffer overflow attacks. Don't just think about how to prevent them — think about how you'd write your code so that mistakes like that simply cannot happen, whether by accident or through malice. Your programming language almost certainly has the tools to let you do that, if you just learn to use them as they're meant to.
* In a multiplayer game, you'll presumably have some client code running on the player's computer. Get used to the idea that a sufficiently smart and determined user will *always* be able to compromise such code and make it do what *they* want. *Don't trust the client*, if you can avoid it. If you can't avoid it, make sure to only trust it as far as you have to.
* Try not to put all your eggs in one basket. If you can't run your game, your website and your database on separate servers, at least run them under separate accounts, and make sure none of them have any more access to each other than they need. OK, maybe both your game and your website need access to your user database, but they surely don't need *admin* access to it, do they? Perhaps they don't even need more than *read only* access to it. At least, even if you don't enforce such strict compartmentalization to begin with, design your game so that it can be put in place later — don't make your game server *require* admin access to the database. Remember that *all* software has bugs, and sooner or later someone *will* find a security hole in yours.

In general, the thing to realize about security is that *it's a mindset*. It's not about knowing the latest security buzzwords, or about how the latest attacks work or about trying to anticipate what hackers will do before they do it (although all of those things may be of some use).

Actual secure programming is about learning how to use the tools you have the way they were meant to be used, about dividing your code into pieces small enough that you can understand what each of them does (and making sure they do it right, even if other parts are compromised), and about writing your code to expect the unexpected. If you do all that, you won't *need* to know what hackers might try, because you'll be prepared for anything.

# Answer
> 8 votes
Personally, I wouldn't worry about hackers **yet**.

The rationale is simple: you won't get hackers/cheaters until you're a fairly popular game; i.e. worth the time to hack/cheat. Wait until you have a game established first and revenue coming in to fund those kinds of things.

You can spend a lot (I mean, a lot) of time trying to fool proof your code to it can't be hacked or cheated. Or you could do regular offsite backups (which you should be doing anyway) and creating regular restore points. When an exploit happens, close it.

---
Tags: networking, mmo, browser-based-games, security
---


title: How do I generate a level randomly?

text:
# Question
Title: How do I generate a level randomly?
I am currently hard coding 10 different instances like the code below, but but I'd like to create many more. Instead of having the same layout for the new level, I was wondering if there is anyway to generate a random X value for each block (this will be how far into the level it is). A level 100,000 pixels wide would be good enough but if anyone knows a system to make the level go on and on, I'd like to know that too. This is basically how I define a block now (with irrelevant code removed):

```
block = new Block(R.drawable.block, 400, platformheight);
block2 = new Block(R.drawable.block, 600, platformheight);
block3 = new Block(R.drawable.block, 750, platformheight);

```

The `400` is the X position, which I'd like to place randomly through the level, the `platformheight` variable defines the Y position which I don't want to change.

# Answer
You can have a list called "levels". You can also have a function for creating a level, ie:

```
var Level = function (x) //x is the number of blocks
{
    var self = this;

    self.x = x
    self.blocks = [];

    for (var i = 0; i < self.x; i ++)
        self.blocks.push(new Block(R.drawable.block, 100000*Math.random(), platformheight);)
}

var levels = [];

for (i = 0; i < n; i ++)
    levels.push(new Level(Math.round(Math.random()*m)))//m being the number of blocks you would like to have most in a level

```

Now, what does this do?

1. Makes a function for instancing levels
2. Makes an array for storing levels
3. Fills that array with n levels

The process of creating a Level:

1. new Level(n) get called
2. The level now knows that it has n blocks, stores that info in his `self.x`
3. The level actually makes n (or `self.x`) blocks, putting them all in an array called `self.blocks`

Now, `Math.random()` gives you a random number between 0 and 1. 0.73, for example. If you multiply that by 100 000, the said width of levels, you get a random x position in that level (73 000, for example).

When you do `Math.round(Math.random()*x)`, you get a whole number between 0 and x, including x.

For example:

`Math.round(Math.random()*10)` could give you 0, 10, 4, 7, and so on.

If you have any questions, or if you guys notice I'm wrong about something, notify me in the comments!
> 2 votes

---
Tags: android, javascript, platformer, levels, procedural-generation
---


# Question
Title: Architecture of an action multiplayer game from scratch
Not sure whether it's a good place to ask (do point me to a better one if it's not), but since what we're developing is a game - here it goes.

So this is a "real-time" action multiplayer game. I have familiarized myself with concepts like lag compensation, view interpolation, input prediction and pretty much everything that I need for this. I have also prepared a set of prototypes to confirm that I understood everything correctly.

My question is about the situation when game engine must be rewind to the past to find out whether there was a "hit" (sometimes it may involve the whole 'recomputation' of the world from that moment in the past up to the present moment. I already have a piece of code that does it, but it's not as neat as I need it to be. The domain logic of the app (the physics of the game) must be separated from the presentation (render) and infrastructure tools (e.g. the remote server interaction specifics).

How do I organize all this? :) Is there any worthy implementation with open sources I can take a look at?

What I'm thinking is something like this:

```
-> Render / User Input
    -> Game Engine (this is the so called service layer)
        -> Processing User Commands & Remote Server
        -> Domain (Physics)

```

How would you add into this scheme the concept of "ticks" or "interactions" with the possibility to rewind and recalculate "the game"? Remember, I cannot change the Domain/Physics but only the Game Engine. Should I store an array of "World's States"? Should they be just some representations of the world, optimized for this purpose somehow (how?) or should they be actual instances of the world (i.e. including behavior and all that).

Has anybody had similar experience?

(never worked on a game before if that matters)

# Answer
The way I handle lag compensation in my game doesn't involve recalculating the entire world state from a past state. That would be extremely hard to manage since it means data you sent to clients in the past was actually stale data.

For example, what happens when a player with high latency heals a target player just before the target dies? To the server, the target player is already dead by the time the heal packet arrives. If you recompute the full world state you'll have to revive that player. But what if you've already sent a packet to the target player and he's already seeing the "You're Dead" screen?

These problems aren't unsolvable, but could become a big issue, so you'll have to decide how to handle them on a case-by-case basis.

What I do for my game is, every tick, save only the positions of all networked entities. When I turn lag compensation on, I use the client's ping and interpolation amount to rewind to what the client was seeing at that time. In this rewinded state I only run commands that query the world, not mutate it (e.g. `DetectHit`, `FindInRange`). I store the results of these queries, then revert all the positions back to the current time. Then I move forward as if those queries were run in the current tick.

In this way, nothing ever gets undone. In the example I gave, if a player is dead then he'll stay dead and it's essentially the burden of the high latency player to heal earlier.
> 1 votes

---
Tags: architecture, physics, multiplayer
---


# Question
Title: Removing the circle outline rendered on Box2d CircleShape
How can I remove the outline on the `CircleShape` below?

```
CircleShape circle = new CircleShape();
circle.setRadius(1f);

```

This is what I'm using to draw:

```
batch.draw(textureRegion, position.x - 1, position.y - 1, 1f, 1f, 2, 2, 1, 1, angle);

```

I use this to set the body for a Box2d collision but I get a silly circle shape around my texture in `libGdx`. My textured sprite (ball) has a circle over the top of it with a line running from center along the radius.

Any ideas on how to remove the overlying circle lines?

# Answer
It sounds like you are using the DebugRenderer which would cause the outline.
> 6 votes

---
Tags: libgdx
---


title: Efficient path-finding in free space

text:
# Question
Title: Efficient path-finding in free space
I've got a game situated in space, and I'd like to issue movement orders, which requires pathfinding. Now, it's my understanding that A\* and such mostly apply to trees, and not empty space which does not have pathfinding nodes. I have some obstacles, which are currently expressed as fixed AABBs- that is, there is no unbounded "terrain" obstacle. In addition, I expect most obstacles to be reasonably approximable as cubes or spheres.

So I've been thinking of applying a much simpler pathfinding algorithm- that is, simply cast a ray from the current position to the target position, and then I can get a list of obstacles using spatial partitioning relatively quickly. What I'm not so sure about is how to determine the part where the ordered unit manoeuvres around the obstacles.

What I've been thinking so far is that I will simply use potential fields- that is, all units will feel a strong repulsive force away from each other and a moderate force towards the desired point. This also has the advantage that to issue group orders, I can simply order a mid-level force towards another entity. But this obviously won't achieve the optimal solution.

Will potential fields achieve a reasonable approximation given my parameters, or do I need another solution?

# Answer
> 7 votes
While potential fields may work, I imagine you'll have issues with sub-optimal paths and "local minimums" where your units will be trapped by surrounding obstructions. A\* is suitable for 3D open space environments. It simply becomes an issue of generating a navigation mesh that fits your needs. You can even use structures like Octrees for navigational nodes. The smaller the maximum size of each octant, the smoother the path. Check out this article from Face to Face games (now defunct, added wayback link). A\* combined with path optimization (like line of sight shortcuts) and steering behaviors and you'll be good to go! See the image below as an example of using an octree for path nodes:

---
Tags: c++, path-finding
---


title: Random World Generator

text:
# Question
Title: Random World Generator
I'm a new game developer. I am working on my first game at the moment. It's sort of a Risk like game, but I have added my own elements. Also sort of Starcraft inspired. I want a random world generator for maps, but I'm having a little trouble making a generator. Tips?

# Answer
Basically you will want some sort of random that you can use to generate your world. In the realm of games Perlin Noise is fairly common as a starting point for such a thing. Minecraft is a pretty well known game that use/used this kind of technique as well.

I am not sure if you are doing 2D or 3D but the algorithm follows in suit. There is an article about the world generation for the game Realm of the Mad God that is also very useful to gather information on random world generation.

Another noise algorithm you may come across is Simplex Noise. Here is an article on it in C++/Python (since I am not sure which language you are interested in).

There is actually quite a bit of information out there. I find all this stuff fascinating and so have collected a good amount of URLs on the topics around it. I hope some of these will help you out.. The article on the Realm of the Mad God generation is fairly interesting in a thought provoking way as well (ie, what can I do with this set of algorithms).

Hope this helps.
> 6 votes

---
Tags: game-design
---


# Question
Title: How can I place a ProgressBar in Android using Cocos 2d?
I want to place a horizontal progress bar in my Android application and I want to change its progress color. I used the following code, but the progress bar is not being displayed.

```
CCProgressTimer progressBar = CCProgressTimer.progress("progressbar.png");
progressBar.setType(kCCProgressTimerTypeHorizontalBarLR);
progressBar.setScale(5);
progressBar.setAnchorPoint(CGPoint.ccp(0, 0));
progressBar.setPosition(CGPoint.ccp(0,0));
addChild(progressBar);

```

# Answer
> 2 votes
You should add a CCProgressFromTo action into your `progressBar`, then show `progressBar`.

---
Tags: opengl, android, cocos2d
---


# Question
Title: After building a .exe file game view does not show whole viewport
So, I went to build a game today in a .exe, and when I build it, it doesn't show the whole viewport as it does in the unity engine itself. So the game is cut off. It does this no matter what I do.

What I see in Unity:

What I get running the exe:

Anyone know what's causing this?

# Answer
You are using "Free Aspect" for screen ratio in your game view, which essentially makes it as big as it can be. Go to "Edit-\>Project Settings-\>Player" and you should see a "Resolution and Presentation"-tag. Now select the "PC and Mac Standalone"-option and input the resolution you are planning to test it on. Then change the "Free Aspect" in the editor to "Standalone". This changes the Editor's gameview to the given resolution.
> 3 votes

# Answer
The problem is that the screen ratio you see in Unity's environment depends on the size of the viewport, not the game's final resolution or ratio. If you want your game to be in widescreen you need to limit your screen resolution to 16:9 or 16:10 ratios. If I remember it correctly, it is one of the build options.

To test your game using those resolutions from Unity's environment, enable the "Maximize on play" button in your Game viewport.
> 1 votes

---
Tags: unity
---


# Question
Title: Managing game state / 'what to update' within an XNA game 'screen'
I'm trying to figure out how best to manage state within my game *screens* \- please bare with me though! At the moment I'm using a heavily modified version of the fantastic game state management example on the XNA site available here. **This is working perfectly for my 'Screens'** \- 'IntroScreen' with some shiny logos, 'TitleScreen' and a 'MenuScreen' stacked on top for the title and menu, 'PlayScreen' for the actual gameplay, etc. Each screen has the a bunch of sprites, and an 'Update' and 'Draw', managed by a 'ScreenManager'.

In addition to the above, and as suggested as an answer to my other question here, most screens have a 'GameProcessQueue' class full of 'GameProcess'es which lets me do just about anything (animations, youbetcha!), in any order, in sequence or parallel.

Why mention all this? When I talk about managing game state I'm thinking more for complex scenarios within a 'Screen'. 'TitleScreen', 'MenuScreen' and the like are all relatively simple. 'Play Screen' less so. **How do people manage the different 'states' within the screen (or whatever you call it) that 'does' gameplay?** (for me, the 'PlayScreen')

I've thought about the following:

1. **Enum of different states in the Screen**, 'activeState' enum-type variable, switching on the enum in the Screen Update() loop to determine what Screen Update 'sub'-function is called. I can see this getting hairy pretty fast though as screens get more complex and with the 'PlayScreen' becoming a behemoth mega-class.
2. **'State' class with Update loop** \- a Screen can have any number of 'States', 1+ of which are 'active'. Screen update loop calls update on all active states. States themselves know which screen they belong to, and may even belong to a 'StateManager' which handles transitioning from one state to the next. Once a state is over it's removed from the ScreenState list. The Screen doesn't need a bunch of GameProcessQueues, each State has its own.
3. **Abstract Screen further to be more flexible** \- I can see the similarities between what I've got (game 'Screens' handled by a ScreenManager) and what I want (states within a screen, and a mechanism to manage them). However at the moment I see 'Screens' as high level and very distinct ('PlayScreen' with baddies != 'MenuScreen' with 4 words and event handlers), where as my proposed 'States' are more intrinsically tied to a specific screen with complex requirements. I think.

This is for a turn-based board game, so it's easier to define things as a discrete series of steps (IntroAnimation -\> P1Turn -\> P2Turn -\> P1Turn ... -\> GameOver -\> .... Obviously with an open-world RPG things are very different, but any advice in this scenario is appreciated.

If I'm just going OOP-crazy please say so. Similarly I'm concious there's a huge amount on this site re: state management. But as my first 'serious' game after a couple of false starts I'd like to get this right, and would rather be harassed and modded down than never ask :)

# Answer
> 5 votes
Your reasoning is sound, and pretty much all I can give here is opinion. Any of the alternatives you gave seem reasonable, although my recommendation would be to keep it simple at first, and stick with the enum, unless you really expect a *lot* of different gameplay states from the start.

But you are right, what you have already implemented for screens is indeed just a finite state machine (in this case using a stack based implementation) whose states are screens. Naturally, a finite machine is not limited to managing screens, and can just as well be used for managing all kinds of game state. This includes, for example, what you refer to as being gameplay states within a screen, or more specific concepts such as artificial intelligence states of a game entity.

You could abstract the screen manager into a general finite state machine class, but screens have separate update *and draw* methods in order to match the framework, while a state in a FSM will typically only have an update method. There's also a few other features here and there that might useful only to a screen manager. Then again, you could have a generic finite state machine base class, and make the screen manager inherit from it to provide the additional features. But your screen manager has a stack based implementation, and a regular finite state machine usually doesn't need it.

So instead of trying to cover all the bases at this point with the most flexible design possible, I'd say to just **keep it simple**, and use the enum. Chances are, the amount of gameplay states you'll need will never grow large enough for it to be impractical. Unlike the action chaining method I spoke about in the other question, which I find to be extremely useful, my experience so far with *this* particular problem of higher level gameplay state management, is that over engineering it doesn't really pay out that much.

# Answer
> 1 votes
In similar situation I decided to go with enums. To be honest I actually didn't considered any other options though :). The main concern, I suppose is the *'PlayScreen' becoming a behemoth mega-class* part. But most of the time, it should be. Very big, maybe ugly but pretty straightforward which is a synonym to "easy to understand and debug". This comes from experience of studying open-source games code (small to medium, 'indie' size).

---
Tags: xna, c#, game-loop
---


title: Moving multiple objects on a map

text:
# Question
Title: Moving multiple objects on a map
I have multiple objects on my isometric game, for example, NPC's doing path finding automatically to walk around the map. Now there could be any number of them from 0 to infinity (hypthetical as no PC could handle that).

My question is: is simply looping each one individually the smartest way to animate them all? Surely as the number of units increases you will notice a lag occuring on units near the end of loop still "waiting" for their next animation movement.

The alternative is a swarm algorithm to move all objects together. Is that a smarter idea or do both situations apply depending on the circumstances of the game?

# Answer
Whichever algorithm you choose to update your NPCs, they will still have their animations updated one at a time. Yes, there are multiple cores, and you could write a multi-threaded update loop that can update 2, 4, 8 or however many NPCs at a time. However, this would only be necessary in extreme cases, and there are many easier methods to employ first.

A major one, **only animate the units that are visible.** This applies to your assumption that there could theoretically be infinity units to update. The number of units that need an animation update is finite. The maximum is the number that can reasonably fit into the view of your camera and still be large enough to notice animation changes.

**But what you really need to do** is write a simple update loop that updates each npc's animation one at a time. *Then* you test the performance to see if you really need to improve it. If you spend too much time wondering which way to do it best, you'll never finish.
> 6 votes

# Answer
*Swarm algorithm* is probably not the word you're looking for, as it conjures associations with flocking.

What I think you're trying to say is some sort of level of detail (LoD) for behaviour, which isn't a bad idea at all. After all, behaviour can be simulated at different granularities (e.g. we don't need to simulate every sub-atomic particle's movement to animate a walking dog).

**Example:** In a 3D medieval battle game you wouldn't animate every individual bone on a single soldier which shows up as 4 pixels on the player's screen, instead you would treat the soldier's battalion as a single entity (the military catch-all phrase "unit" is most appropriate here) and consider only its movements in reaction to the world state. This would result in a simple translation vector, which you of course still need to apply to each individual soldier, so you will never get rid of the loop(\*), but you will be able to minimize the number of calculations needed within it.

Once the battalion gets closer to the camera you add a check to make sure each soldier is touching the terrain, and closer still you'll actually start animating them individually.

Rewinding from this example to your current endeavor, depending on the distance of the entity from the player's view (and the speed with which the player would be able to move the view) you would:

1. translate and animate them normally (when the units are on screen)
2. translate but not animate (when they are just off screen)
3. update them less than once per frame (when they are further away)
4. not even update them (if this wouldn't lead to strange situations)

For 2 and 3 you would be able to use the method of grouping the behaviour of multiple entities, especially if they were supposed to move in (relative) unison anyway.

**In closing**: whether this is applicable to your game depends on its mechanics, and (as was already mentioned) if you actually need these optimizations: avoid "*premature* optimization". :-)

---

(\*) Though one could make use of a scene graph to defer the propagation of the translation to the drawing phase of the game loop.
> 1 votes

# Answer
**"The alternative is a swarm algorithm to move all objects together"**

What does *together* mean? In programming, together will be updating at the same time which in turn means updating them in separate threads, otherwise there is no *together*, it will always be linear, one after the other. Needless to say, separate threads does not guarantee updating at the same time if there are not enough available cores.

Bytes56's suggestion to animate only the units that are visible is sound but to avoid the weird effect of the NPC suddenly stopping to animate as soon as it goes off-screen, you may want to update NPCs that are in a certain radius around the player.
> 0 votes

---
Tags: game-design
---


# Question
Title: Sharing functions across multiple shaders
Simple question:

In GLSL, is there a way to share functions across multiple shaders, or do I have to define all functions in every shader that needs them?

# Answer
> 12 votes
You can define some functions in a header file and #include them into your shader. It's a bit different from C/C++ in that you'd put the *bodies* of your functions in the headers, not just their prototypes (since shaders have no concept of separate compilation & linking), but other than that it's just like C/C++ headers.

# Answer
> 7 votes
If #include is not available you would use the arguments of glShaderSource to specify the shared stuff. Example:

```
char *sharedcode = "...shared code here...";
char *fs1 = "...fragment shader 1...";
char *fs2 = "...fragment shader 2...";

char *awesomeeffect1[] = {sharedcode, fs1};
char *awesomeeffect2[] = {sharedcode, fs2};

glShaderSource (shader1, 2, awesomeeffect1, NULL);
glShaderSource (shader2, 2, awesomeeffect2, NULL);

```

---
Tags: glsl
---


# Question
Title: Converting a DrawModel() using BasicEffect to one using Effect
Take this DrawModel() provided by MSDN:

```
private void DrawModel(Model m)
{
    Matrix[] transforms = new Matrix[m.Bones.Count];
    float aspectRatio = graphics.GraphicsDevice.Viewport.Width /
        graphics.GraphicsDevice.Viewport.Height;
    m.CopyAbsoluteBoneTransformsTo(transforms);
    Matrix projection =
        Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f),
        aspectRatio, 1.0f, 10000.0f);
    Matrix view = Matrix.CreateLookAt(new Vector3(0.0f, 50.0f, Zoom),
        Vector3.Zero, Vector3.Up);

    foreach (ModelMesh mesh in m.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();

            effect.View = view;
            effect.Projection = projection;
            effect.World = gameWorldRotation *
                transforms[mesh.ParentBone.Index] *
                Matrix.CreateTranslation(Position);
        }
        mesh.Draw();
    }
}

```

How would I apply a custom effect to a model with that? Effect doesn't have View, Projection, or World members. This is what they recommend replacing the foreach loop with:

```
foreach (ModelMesh mesh in terrain.Meshes)
{
    foreach (Effect effect in mesh.Effects)
    {
        mesh.Draw();
    }
}

```

Of course, that doesn't really work. What else needs to be done?

EDIT: This is the effect I want to apply, generated by RenderMonkey:

```
string Procedural_Graphic_Effects_2D_Electricity_Single_Pass_ScreenAlignedQuad : ModelData = "..\\..\\..\\Program Files (x86)\\AMD\\RenderMonkey 1.82\\Examples\\Media\\Models\\ScreenAlignedQuad.3ds";

float4x4 World;
float4x4 View;
float4x4 Projection;

struct VS_OUTPUT {
   float4 Pos: POSITION;
   float2 texCoord: TEXCOORD;
};

VS_OUTPUT Procedural_Graphic_Effects_2D_Electricity_Single_Pass_Vertex_Shader_main(float4 Pos: POSITION){
   VS_OUTPUT Out;

   // Clean up inaccuracies
   Pos.xy = sign(Pos.xy);

   Out.Pos = float4(Pos.xy, 0, 1);
   Out.texCoord = Pos.xy;

   return Out;
}

float4 color
<
   string UIName = "color";
   string UIWidget = "Color";
   bool UIVisible =  true;
> = float4( 0.69, 0.48, 1.00, 1.00 );
float glowStrength
<
   string UIName = "glowStrength";
   string UIWidget = "Numeric";
   bool UIVisible =  true;
   float UIMin = 0.00;
   float UIMax = 200.00;
> = float( 144.00 );
float height
<
   string UIName = "height";
   string UIWidget = "Numeric";
   bool UIVisible =  true;
   float UIMin = 0.00;
   float UIMax = 2.00;
> = float( 0.44 );
float glowFallOff
<
   string UIName = "glowFallOff";
   string UIWidget = "Numeric";
   bool UIVisible =  true;
   float UIMin = 0.00;
   float UIMax = 0.30;
> = float( 0.02 );
float speed
<
   string UIName = "speed";
   string UIWidget = "Numeric";
   bool UIVisible =  true;
   float UIMin = 0.00;
   float UIMax = 3.00;
> = float( 1.86 );
float sampleDist
<
   string UIName = "sampleDist";
   string UIWidget = "Numeric";
   bool UIVisible =  true;
   float UIMin = 0.00;
   float UIMax = 0.04;
> = float( 0.01 );
float ambientGlow
<
   string UIName = "ambientGlow";
   string UIWidget = "Numeric";
   bool UIVisible =  true;
   float UIMin = 0.00;
   float UIMax = 1.00;
> = float( 0.50 );
float ambientGlowHeightScale
<
   string UIName = "ambientGlowHeightScale";
   string UIWidget = "Numeric";
   bool UIVisible =  true;
   float UIMin = 0.00;
   float UIMax = 8.00;
> = float( 1.68 );
float vertNoise
<
   string UIName = "vertNoise";
   string UIWidget = "Numeric";
   bool UIVisible =  true;
   float UIMin = -1.00;
   float UIMax = 1.00;
> = float( 0.78 );
float time_0_X : Time0_X;
texture Noise_Tex
<
   string ResourceName = "..\\..\\..\\Program Files (x86)\\AMD\\RenderMonkey 1.82\\Examples\\Media\\Textures\\NoiseVolume.dds";
>;
sampler Noise = sampler_state
{
   Texture = (Noise_Tex);
   ADDRESSU = WRAP;
   ADDRESSV = WRAP;
   ADDRESSW = WRAP;
   MAGFILTER = LINEAR;
   MINFILTER = LINEAR;
   MIPFILTER = LINEAR;
};
float4 Procedural_Graphic_Effects_2D_Electricity_Single_Pass_Pixel_Shader_main(float2 texCoord: TEXCOORD) : COLOR {
   float2 t = float2(speed * time_0_X * 0.5871 - vertNoise * abs(texCoord.y), speed * time_0_X);

   // Sample at three positions for some horizontal blur
   // The shader should blur fine by itself in vertical direction
   float xs0 = texCoord.x - sampleDist;
   float xs1 = texCoord.x;
   float xs2 = texCoord.x + sampleDist;

   // Noise for the three samples
   float noise0 = tex3D(Noise, float3(xs0, t)).r;
   float noise1 = tex3D(Noise, float3(xs1, t)).r;
   float noise2 = tex3D(Noise, float3(xs2, t)).r;

   // The position of the flash
   float mid0 = height * (noise0 * 2 - 1) * (1 - xs0 * xs0);
   float mid1 = height * (noise1 * 2 - 1) * (1 - xs1 * xs1);
   float mid2 = height * (noise2 * 2 - 1) * (1 - xs2 * xs2);

   // Distance to flash
   float dist0 = abs(texCoord.y - mid0);
   float dist1 = abs(texCoord.y - mid1);
   float dist2 = abs(texCoord.y - mid2);

   // Glow according to distance to flash
   float glow = 1.0 - pow(0.25 * (dist0 + 2 * dist1 + dist2), glowFallOff);

   // Add some ambient glow to get some power in the air feeling
   float ambGlow = ambientGlow * (1 - xs1 * xs1) * (1 - abs(ambientGlowHeightScale * texCoord.y));

   return (glowStrength * glow * glow + ambGlow) * color;
}

//--------------------------------------------------------------//
// Technique Section for Effect Workspace.Procedural Graphic Effects 2D.Electricity
//--------------------------------------------------------------//
technique Electricity
{
   pass Single_Pass
   {
      CULLMODE = NONE;

      VertexShader = compile vs_1_1 Procedural_Graphic_Effects_2D_Electricity_Single_Pass_Vertex_Shader_main();
      PixelShader = compile ps_2_0 Procedural_Graphic_Effects_2D_Electricity_Single_Pass_Pixel_Shader_main();
   }

}

```

EDIT: Simply changing the code in the way that MSDN suggested, my entire model is replaced by a smooth curved line (static, not animated) with the effect applied to said line. The line takes up the entire width of the screen, and does not move when the ship object moves. I know that the ship.position changes properly because other objects look in the direction that the ship is at all times. However, looking at what's drawn in place of the ship, it would appear to not move at all.

# Answer
`Effect` has a `Parameter` collection, so you can do:

`effect.Parameters["World"].SetValue(World)`
> 1 votes

---
Tags: xna, 3d, models
---


# Question
Title: Procedural generation of seabeds / underwater terrain
There are a lot of resources available for procedural content generation when it comes to terrain, which is above sea-level.

For a naval simulation, I now need to procedural generate terrain below sea-level. My first idea was to just use standard techniques (like fractals) but maybe somebody knows good resources about this topic?

Thanks.

# Answer
> 12 votes
You can use the same techniques as above-water landscape generation - but simply apply different principles. Here are some examples:

**Basic Landscape**

Underwater landscapes have much more pronounced features than above-water. This is likely because (as far as I know) the ocean beds are more tectonically active. None-the-less you will need to tweak the generator/perlin so that you get immensely deep ravines and so forth.

**Erosion/Weathering**

Typical above-water landscape generation relies on the fact that there is infrequent rainfall that runs downhill: contrast this with underwater where you have permanent erosion (so exaggerate the erosion effect) and where it **also/partially** runs in the direction of the local currents (so don't **only** send it downhill: create some currents before eroding). However keep in mind (depending on the depth of the area you are eroding) that the amount of deposits (sand) might be relatively small so you would reduce the weathering effect.

This type of erosion could likely get **very** expensive to the degree where I would consider skipping it and just use classical erosion.

**Features**

Due to the depth variance (shallow to extremely deep) the features on the seabed vary widely. At relatively low depths you get coral reefs and so forth, at the other end of the spectrum (trenches) you get volcanic vents and so forth.

**Summary**

Read up on weathering and tectonics under water and try and simulate that. Remember you don't need to perfect it and create the perfect seabed - just something convincing so that the player doesn't think to question it. On my first attempt I would concentrate on:

* Ravines and other unique tectonic features.
* Classical erosion instead of underwater erosion (only add underwater erosion if it isn't convincing enough).
* Features like vents or coral would likely be the most convincing aspect.

---
Tags: procedural-generation
---


# Question
Title: How to integrate ad mob ads in cocos2d android portal?
Could anybody tell me how to integrate ad mob ads in my cocos2d android app.

# Answer
Since I'm sure you've already tried the official tutorial. And have done a basic Google search and found this and this and this video tutorial and this tutorial. I think you may have to provide more detail about a specific problem you've come across.
> 1 votes

---
Tags: android, cocos2d
---


# Question
Title: Good Video Game User Interface Design Books/Websites?
I having been programming games for some time, but while my teachers say that my code is good and advanced, my friends say that the interface is hard to understand and not the easiest to navigate. I want to learn how to design good user interfaces so that I can program better games, and people will have a easier time getting around. Does anyone know of any good books or websites about designing video game interfaces?

# Answer
I feel as if good design is something that is hard to get right the first time. The field you might want to read up into is called human computer interaction.

Basically the approach is based heavily on prototyping and running usability tests on participants to observe how they interact with your system, where the difficulties arise from, what is intuitive and non-intuitive. These type of tests need to be run without bias and you need to encourage the participants to think out loud.

You start off by given them a scenario to complete in your system. You don't tell them anything about the specifics of how to do it, and let them try figure it out. If they get stuck, you try and find out what they're thinking. You note down all of this information and iterate over the design.

Good interface design is something that's hard to get right without doing these style of tests. I would even recommend doing paper prototyping for your interface.
> 1 votes

# Answer
I reccomend picking up "The Design of Everyday Things" by Donald Norman. I think it is a very good basic book that anyone who is concerned with usability should pick up.

Playing other games with similar features as well as iterating on your friends' feedback should also help you get a better understand of user interface design.
> 1 votes

# Answer
gamedesignreviews.com \- reviews and constructively critiques game design

brandfeelsgood.com \- a sporadic game interface reviewer (my own blog )
> 0 votes

---
Tags: c++, ui-design
---


# Question
Title: Is it possible to programmatically prevent a game from pausing when its window loses focus?
I'm playing Skyrim in windowed mode and I am trying to create a bot for this game for personal use. I would like to have the bot play the game in the background, while I do other things, the only problem is that the game window pauses when it loses focus. Is there a way to make the Skyrim process think that it still has the focus, so it continues to run while I do something else on another window? I'm not a windows programming expert but would this be possible if I could somehow intercept the message that says unfocused or minimized to the process, and thus let the process think its still focused? I think Skyrim uses directx, so is it possible to come up with a solution from that end?

# Answer
Well the Eula doesn't really have any actual legal basis as long as you're not hurting anyone but yourself. And it is possible to do what you want, I don't know the specifics but basically you intercept the windows messages and have it ignore any kind of non focusing messages or just force it into thinking it's focused.
> 1 votes

---
Tags: c++, directx, windows
---


# Question
Title: How to get this wavefront .obj data onto the frustum?
I've finally figured out how to get the data from a .obj file and store the vertex positions x,y,z into a structure called `Points` with members `x` `y` `z` which are of type `float`. I want to know how to get this data onto the screen.

Here is my attempt at doing so:

```
//make a fileobject and store list and the index of that list in a c string
ifstream file (list[index].c_str() );

std::vector<int>faces;
std::vector<Point>points;
points.push_back(Point());
Point p;
int face[4];

while ( !file.eof() )
{
    char  modelbuffer[10000];
    //Get lines and store it in line string
    file.getline(modelbuffer, 10000);
    switch(modelbuffer[0])
    {
        case 'v' :
            sscanf(modelbuffer, "v %f %f %f",  &p.x, &p.y, &p.z);
            points.push_back(p);
            cout << "Getting Vertex Positions" << endl;
            cout << "v" << p.x << endl;
            cout << "v" << p.y << endl;
            cout << "v" << p.z << endl;
            break;
        case 'f':
            sscanf(modelbuffer, "f %d %d %d %d", face, face+1, face+2,  face+3 );
            cout << face[0] << endl;
            cout << face[1] << endl;
            cout << face[2] << endl;
            cout << face[3] << endl;
            faces.push_back(face[0]);
            faces.push_back(face[1]);
            faces.push_back(face[2]);
            faces.push_back(face[3]);
    }
    GLuint vertexbuffer;
    glGenBuffers(1, &vertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, points.size(), points.data(), GL_STATIC_DRAW);
    //glBufferData(GL_ARRAY_BUFFER,sizeof(points), &(points[0]), GL_STATIC_DRAW);

    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
    glVertexPointer(3, GL_FLOAT, sizeof(points),points.data());
    glIndexPointer(GL_DOUBLE, 0, faces.data());
    glDrawArrays(GL_QUADS, 0, points.size());
    glDrawElements(GL_QUADS, faces.size(), GL_UNSIGNED_INT,  faces.data());
}

```

As you can see I've clearly failed the end part but I really don't know why its not rendering the data onto the frustum? Does anyone have a solution for this?

# Answer
I'm going to leave my other answer in place, because I think it's more valuable general advice, and people can consider it separately.

Looking in more detail at your code raises the following questions, all of which need answered before you'll get working code.

* Why are you calling glDrawArrays **and** glDrawElements? You should be doing one or the other, depending on how you've organised your data.
* Why are you performing a draw every line? Only some lines (faces) contain primitives that you can actually draw, and even then you want to collect them all up **then** render, not add one, then render, then add another, then render. I'm going to assume that everything from the 'vertexbuffer' declaration is actually supposed to be outside the loop and it's just a typo transcribing into the question, because otherwise the code is just broken.
* In glBufferData, why are you passing the number of points instead of the size of the data buffer (in bytes) as specified?
* In glVertexAttribPointer, why are you telling it that the Point structure consists of 4 GL\_FLOATs when you only have 3?
* In fact, why are you using glVertexAttribPointer at all (given that you've not called glEnableVertexAttribArray to enable it, and you go on to use glVertexPointer)
* Why are you telling glVertexPointer that you have a stride equal to the size of the points array in bytes, instead of the 0 bytes you actually have?
* Have you enabled the vertex array client state using glEnableClientState(GL\_VERTEX\_ARRAY, GL\_TRUE) somewhere else? And GL\_INDEX\_ARRAY?
* In glDrawArrays, why are you passing the number of vertices, instead of 4 * the number of quads?
* Why are your indices ints, and not unsigned ints like you're telling glDrawElements?

All of these I found in 15 minutes just looking at the OpenGL function reference. I think you'd be better served by stepping back and going through a few tutorials which illustrate the use of vertex / index arrays and other basic GL functions before you jump to trying to write a .OBJ renderer. Alternatively I'd recommend Googling for other existing OpenGL .OBJ implementations (of which there must be dozens) to look at for reference.
> 1 votes

# Answer
In every case where I have some bare bones geometry rendering but no real infrastructure, it's been something simple and obvious, and the geometry rendering part has actually been fine. Check:

* Your camera /view matrix is actually looking at the object (move either the object or your camera around until you see something - a dirty animation loop where you orbit the camera or object will usually suffice)
* Your projection matrix is sensible (FOV isn't zero, or just plain uninitialised)
* Your scene is lit (you're not rendering a black object on a black background - change your background colour)
> 0 votes

---
Tags: models, loading, obj
---


# Question
Title: Initializing OpenFeint for Android outside the main Application
I am trying to create a generic C++ bridge to use OpenFeint with Cocos2d-x, which is supposed to be just "add and run" but I am finding problems.

OpenFeint is very exquisite when initializing, it requires a Context parameter that MUST be the main Application, in the onCreate method, never the constructor. Also, the main Apps name must be edited into the manifest. I am trying to fix this. So far I have tried to create a new Application that calls my Application to test if just the type is needed, but you do really need the main Android application. I also tried using a handler for a static initialization but I found pretty much the same problem.

Has anybody been able to do it? This is my working-but-not-as-intended code snippet

```
public class DerpHurr extends Application{

@Override
public void onCreate() {
    super.onCreate();
    initializeOpenFeint("TestApp", "edthedthedthedth", "aeyaetyet", "65462");
}

public void initializeOpenFeint(String appname, String key, String secret, String id){
    Map<String, Object> options = new HashMap<String, Object>();
    options.put(OpenFeintSettings.SettingCloudStorageCompressionStrategy, OpenFeintSettings.CloudStorageCompressionStrategyDefault);
    OpenFeintSettings settings = new OpenFeintSettings(appname, key, secret, id, options);

//RIGHT HERE
    OpenFeint.initialize(***this***, settings, new OpenFeintDelegate() { });
    System.out.println("OpenFeint Started");
}

}

```

Manifest

```
<application
    android:debuggable="true"
    android:label="@string/app_name"
    android:name=".DerpHurr">

```

# Answer
> 2 votes
You're not going to be able to initialize OpenFeint without having an application context and respecting the Android life cycle. It needs a context and it needs to be done in onCreate(). To my knowledge, there is no way around that.

---
Tags: android, openfeint
---


# Question
Title: Which data structure to use to render a large isometric game world?
I'm starting development of a 2d isometric (tiled, roguelike) game and I'm brainstorming which kind of data structure I would use to store runtime data like tiles and entities, but I don't want to use a 2D array (as the world will be huge). How could I handle the rendering in such a case?

# Answer
If your argument against an array is "The world will be huge", then it's not about the data-structure, but rather about memory constraints. If your world is so large, that it doesn't fit into memory with a 2D array, then it won't fit into any other data-structure.

Instead you would have to implement a (file-)format, that allows loading chunks (or sectors) of the world. Then you simply load/unload the needed chunks into a data-structure. There's nothing wrong with a 2D array.

As for rendering: I assume you have some sort of camera/viewport. Then you simply render all tiles that are currently in the viewport.
> 8 votes

# Answer
The Chronicles of Doryen has a nice approach (at least I think so, I'm using it) to both

1. hierarchical storage of a world map comprised of smaller regional maps, and
2. sparse storage of upper floors/basements/... so you're not storing megabytes and megabytes of "empty air" or "solid rock".

It's designed to work with procedural generation, and personally I'm aiming to do the procedural gen of new regions in a second thread to cut down on stalling the main thread, but there's no reason you couldn't use it for storing a hand-generated world to disk.
> 1 votes

---
Tags: java, tilemap, isometric, data-structure
---


# Question
Title: Why does a physics engine produce different results each run through?
There are no random numbers in the engine and everything is calculated the same way. How can it happen differently each time?

This is on my own small physics engine that I made earlier that is written in lua and runs in the Moai SDK

# Answer
> 6 votes
Use the same time steps every time. My physics engine is set to use 33 ms time steps, and I can produce the exact same simulations that way (assuming I use the same machine.) If I use different time steps, even 1 ms more, the game will slowly diverge.

You can do this with this basic loop:

```
void update( long timeMS ) {
    _accumulatedTime += timeMS;
    while ( _accumulatedTime >= _timeStepMS ) {
        // do physics simulation
        _accumulatedTime -= _timeStepMS;
    }
}

```

This will ensure that you always run your physics simulation with exact time steps, and will also ensure that you never lose any time.

# Answer
> 5 votes
Read here for a good explanation of timestep http://gafferongames.com/game-physics/fix-your-timestep/ Timestep should be fixed, and this article takes a good approach and explains everything clearly.

# Answer
> 1 votes
This is difficult to answer without more details regarding the engine itself. My hunch, however, would be to look for race conditions in your code.

The kinds of details that would be useful include:

* Is your engine multi-process or multi-threaded?
* Is your engine event-driven?
* How are you guaranteeing your test is consistent?

---
Tags: physics-engine
---


title: Game programming basics under Windows

text:
# Question
Title: Game programming basics under Windows
I've been trying to learn some Windows programming using the Win32 API. Now, i'm used to working with the OS layer being abstracted away, mostly thanks to libraries like SFML or Allegro. Could you guys help me out and tell me if i'm thinking right here.

The place for my gameloop is where i'm reading the messages?

```
while (TRUE)
{
     if (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
     {
          if (msg.message == WM_QUIT)
               break ;

          TranslateMessage (&msg) ;
          DispatchMessage (&msg) ;
     }
     else
     {
          //my game loop goes here
     }
}

```

Now the slightly bigger issue, that is, drawing. Do i run my drawing where i normaly do it, inside the game loop after the game logic? Or do i do it when WM\_PAIN is being called and just call InvalidateRect (hwnd, NULL, TRUE); when i want to draw? This does feel weird, the WM\_PAINT is a queued message, so i don't know for sure when it'll be called. So if i wanted to avoid this, do i just get the device handle inside the game loop and only ValidateRect (hwnd, NULL); in the WM\_PAINT case (beside the ValidateRect (hwnd, NULL); called after drawing in the game loop)? Actually, now that i think about it, do i even need WM\_PAINT in this situation or can i skip it and let DefWindowProc handle it (does it validate the screen if WM\_PAINT isn't processed)?

If this is any important, i'm setting up my code for OpenGL.

# Answer
You need to `while` that `PeekMessage`, and then loop. Something like

```
bool DoMessages() {
    while(PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) {
        if (msg.message == WM_QUIT)
            return false;

        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return true;
}

while(DoMessages()) {
    Draw();
}

```

It's not common for game architectures to draw in response to `WM_PAINT`\- that's mostly for GDI rendering for applications whose states do not change without user interaction, as far as I'm aware. You can basically just ignore it.

Also, if you want to render to a window (how else would you render..?) then you need to pass the HWND in to `PeekMessage`.
> 3 votes

---
Tags: windows, winapi
---


title: How do I show a minimap in a 3D world?

text:
# Question
Title: How do I show a minimap in a 3D world?
Got a really typical use-case here. I have large map made up of hexagons and at any given time only a small section of the map is visible. To provide an overview of the complete map, I want to show a small 2D representation of the map in a corner of the screen.

What is the recommended approach for this in libgdx? Keep in mind the minimap must be updated when the currently visible section changes and when the map is updated.

I've found `SpriteBatch`(info here), but the warning label on it made me think twice:

> A SpriteBatch is a pretty heavy object so you should only ever have one in your program.

I'm not sure I'm supposed to use the one `SpriteBatch` that I can have on the minimap, and I'm also not sure how to interpret "heavy" in this context.

Another thing to possibly keep in mind is that the minimap will probably be part of a larger UI, is there any way to integrate these two?

# Answer
Generate the minimap from your primary map data beforehand. As the player explores, copy the pre-generated minimap data onto the 'known area' minimap texture (or, alternatively, erase the blackness from a mask). You simply pan/rotate/crop this texture as needed.

Generating the entire map on the fly tile by tile TWICE (once for your main map, once for your minimap) is excessive. The minimap is so small you rarely need to worry about texture size or memory limitations, so compression-by-tiling is not a necessary task.
> 3 votes

# Answer
SpriteBatch allocate Mesh for batching purposes. You can set the size of this Mesh buffer with constructor parameter. Its also create some matrices and couple primitives. Nothing too heavy but warning is just there that people understand that its allocate native resources and its not something that you create every frame.(belive me that is quite often a problem with new comers) It's also create a shader if gles2.0 is used.

Some information related you game and skills would be needed to good answer.

Do you know opengl? Do you use shaders? Do you use fbo's How big portion of screen minimap is covering? is
> 3 votes

---
Tags: libgdx
---


title: Passing POD arrays to shader?

text:
# Question
Title: Passing POD arrays to shader?
How do I pass to my vertex shader an array of N elements?

From what I see I can only pass float arrays of 3|4 elements, vectors 2|3d and matrices, but I want to pass a POD array and use it like this:

```
void ShaderFunction(float* array,int count)
{
    for (int i = 0;i < count;i++)
    {
        DoJob(array[i]);
    }
}

```

So far all of my tests fail.

# Answer
You can define an array in GLSL like so:

```
uniform float array[size];

```

Then passing in depends on what language you're using. For Java (LWJGL):

```
FloatBuffer floatBuffer = BufferUtils.createFloatBuffer(size);
floatBuffer.put(x);
floatBuffer.put(y);
...
int location = GL20.glGetUniformLocation(shaderProgram, "array");
GL20.glUniform1f(location, floatBuffer);

```

Or in C++

```
GLfloat floatArray[size] = {...};
int location = glGetUniformLocation(program, "array");
glUniform1fv(location, size, floatArray);

```

Then you can use it:

```
void ShaderFunction(int count)
{
    for (int i = 0;i < count;i++)
    {
        DoJob(array[i]);
    }
}

```
> 3 votes

# Answer
Short answer: You can't.

Long answer: Need more info what you are trying to do and why.
> 1 votes

# Answer
Another way you might do this is by using a floating point texture - you would create a one-channel FP texture of the required size, upload your data to it, and sample from that in your shader (remember that vertex shaders can also sample from textures).

Where this is going to cause you huge trouble - irrespective of your chosen solution - is in terms of instruction counts. GPUs are not really designed around being used for this kind of programming, and if your count value is sufficiently high and/or if it varies between calls your performance is at risk of falling off the edge of a cliff.

Since you say that you're looking to do this in a vertex shader, it may yet turn out to be more performance-efficient (and even advantageous from a code-cleanliness perspective) to leave it running on the CPU instead.
> 1 votes

---
Tags: glsl
---


# Question
Title: Designing generic render/graphics component in C++?
I'm trying to learn more about Component Entity systems. So I decided to write a Tetris clone. I'm using the "style" of component-entity system where the Entity is just a bag of Components, the Components are just data, a Node is a set of Components needed to accomplish something, and a System is a set of methods that operates on a Node. All of my components inherit from a basic IComponent interface.

I'm trying to figure out how to design the Render/Graphics/Drawable Components. Originally, I was going to use SFML, and everything was going to be good. However, as this is an experimental system, I got the idea of being able to change out the render library at will. I thought that since the Rendering would be fairly componentized, this should be doable. However, I'm having problems figuring out how I would design a common Interface for the different types of Render Components. Should I be using C++ Template types?

It seems that having the RenderComponent somehow return it's own mesh/sprite/whatever to the RenderSystem would be the simplest, but would be difficult to generalize. However, letting the RenderComponent just hold on to data about what it would render would make it hard to re-use this component for different renderable objects (background, falling piece, field of already fallen blocks, etc).

I realize this is fairly over-engineered for a regular Tetris clone, but I'm trying to learn about component entity systems and making interchangeable components. It's just that rendering seems to be the hardest to split out for me.

# Answer
> 4 votes
Templates are not the answer, no.

The first thing to keep in mind is that your Drawable components will generally just be data components. For instance, in a simpler 2.5D game I have right now, my DrawableComponet has the following broad subclasses:

* SpriteDrawableComponent
* ParticleEmitterComponent
* FluidComponent
* StaticMeshComponent

All these components do is hold data and state. All of the actual logic for rendering is encapsulated entirely by the graphics system.

The graphics system contains a list of these drawable components in a data structure optimized for rendering and batching of the draw calls. In my example, the graphics system itself is still actually fully abstracted from the low-level graphics API, and deals with more general purpose rendering concepts. It knows how to ask the graphics API wrapper to create textures, create buffers, set rendering state, load shader packages, and submit geometry to the GPU.

The graphics API wrapper is made of a smaller number of abstract interfaces. There are interfaces for the various types of GPU resources (vertex buffers, textures, shader programs, vertex attrib layouts, and state objects). The implementation of the API then knows how to map those to whichever API is in use (OpenGL 3.3, GL|ES 2.0, and D3D11, for example). The only game-specific code that we need to rewrite for each API then becomes the shaders, and only because Cg outright doesn't support GL|ES shaders.

tl;dr version:

* Components hold data.
* Rendering system manages scene state and rendering.
* Graphics wrapper deals with portability between platform APIs.

---
Tags: c++, component-based, entity-system, game-component
---


title: How do I draw a scrolling background?

text:
# Question
Title: How do I draw a scrolling background?
How can I draw background tile in my 2D side-scrolling game? Is that loop logical for OpenGL es? My tile 2400x480. Also I want to use parallax scrolling for my game.

```
batcher.beginBatch(Assets.background);
for(int i=0; i<100; i++)
    batcher.drawSprite(0+2400*i, 240, 2400, 480, Assets.backgroundRegion);

batcher.endBatch();

```

---

## UPDATE

And thats my onDrawFrame.I'm sending deltaTime for fps control.

```
public void onDrawFrame(GL10 gl) {
    GLGameState state = null;

    synchronized(stateChanged) {
        state = this.state;
    }

    if(state == GLGameState.Running) {
        float deltaTime = (System.nanoTime()-startTime) / 1000000000.0f;
        startTime = System.nanoTime();

        screen.update(deltaTime);
        screen.present(deltaTime);
    }

    if(state == GLGameState.Paused) {
        screen.pause();
        synchronized(stateChanged) {
            this.state = GLGameState.Idle;
            stateChanged.notifyAll();
        }
    }

    if(state == GLGameState.Finished) {
        screen.pause();
        screen.dispose();
        synchronized(stateChanged) {
            this.state = GLGameState.Idle;
            stateChanged.notifyAll();
        }
    }
}

```

# Answer
In this code, you are drawing the background 100 times in 100 different places in **1** frame. Learn how to properly use a game loop to run your game (here's a good article: http://www.koonsolo.com/news/dewitters-gameloop/). Your going to want to update the background's position in each update tick of your game loop and draw it at its current location in each frame.

**Post-Update Edit**: So in `screen.update(deltaTime);` you'll want to change the current background position with something like:
`background.translate(BACKGROUND_SCROLL_SPEED * deltaTime, 0)`

Then, in `screen.present(deltaTime);` draw the background with: `batcher.drawSprite(background.getX(), 240, 2400, 480, Assets.backgroundRegion);`

Let me know if you still have questions.
> 2 votes

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


# Question
Title: How do I communicate with an IronPython component in a C#/XNA game?
My XNA game is component-oriented, and has various components for position, physics representation, rendering, etc, all of which extend a base `Component` class. The player and enemies also have **controllers** which are currently defined in C#. I'd like to turn them into Python scripts via IronPython (a .NET implementation of Python). My problem is that I'm not sure how to interact with those scripts.

The examples in Embedding IronPython in a C# Application suggest I'd have to create something like a Script component which compiles a Python script and calls the controller's Update method via Python - essentially, it'd be a wrapper class for C# to interface with Python.

I feel that I'm missing something in my research. There *must* be a way to load up a script, instantiate a Python object (either in the Python script or in C#) and then then have a *direct* reference to that Python object in my C# code.

**Is there a way to work with an IronPython object *directly*, or is a wrapper required?**

# Answer
> 7 votes
I've figured out how to do this. As I expected, since IronPython compiles down to CLR, C# and IronPython objects can interact with each other just fine with no special treatment necessary. I've created a script which actually creates a new type of Component which can be referenced just fine from C#.

**A brief word on my game's structure:** Its solution has two projects: Game, and GameEngine. The Game is what is ultimately compiled into an EXE, and the GameEngine is compiled into a DLL which sits in the same directory.

### The script

This currently sits in the default content project, has no build action and is copied to the output directory.

Note that the Component class is a part of GameEngine, and so is compiled into *GameEngine.dll*. It also has nothing to do with XNA's GameComponent class and its methods don't need to be passed a GameTime object.

```
import clr
clr.AddReferenceToFileAndPath("GameEngine.dll")
from GameEngine import *
# or: from GameEngine import Component

class PyComponent(Component):
    def __new__(self):
        Component.__new__(self)

    def Initialize(self):
        pass

    def Update(self):
        pass

    def Draw(self):
        pass

pc = PyComponent()

```

### How the script is compiled and run

Just once within the game, I run this:

```
// Engine setup stuff. The scope can work with variables in the script by
// adding references, accessing/removing current references, etc.
// Each script COULD have its own scope but I have no reason to do that yet.
ScriptEngine PythonEngine = Python.CreateEngine();
ScriptScope DefaultScope = PythonEngine.CreateScope();

string filename = @"Content\ScriptTest.py";
ScriptSource script = PythonEngine.CreateScriptSourceFromFile(filename, Encoding.ASCII);
script.Execute(scope);

```

When the script gets executed, it creates its own instance of a PyComponent.

Of course you'll need to reference the IronPython library and the Microsoft Dynamic runtime. I've found I only need these four DLLs from the root folder of the IronPython download:

* IronPython.dll
* IronPython.Modules.dll
* Microsoft.Dynamic.dll
* Microsoft.Scripting.dll

Add these references to your project, then these `using` statements to your code (according to Embedding IronPython in a C# Application):

```
using IronPython.Hosting;
using IronPython.Runtime;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;

```

### Obtaining a reference to the Python object

I'm not sure how I'd get a reference directly from the script, but I do have a roundabout way of doing that. In my engine design, all components automatically register themselves with the engine's component collection, so I can get a reference to the object through there. In a more specific case, you could just have new Python objects register themselves with a queue somewhere, so you create them and then immediately retrieve them.

---
Tags: xna, c#, component-based, python, scripting
---


# Question
Title: Are there some methodologies to define a game's rules?
I would like to write some rules for a game I have in head but I don't know how to do that. So are there some methodologies or modeling tools (like UML) to do that? I'm thinking about a kind of tree of competencies or some kind of map to be sure that the game is well balanced.

I always wonder how the team who imagines some powers in magic the gathering for example does it. Do they have some diagrams to be sure the powers or creatures they imagine are well balanced for the entire game?

I'm pretty noob in the game creation so I'll be happy with some directions to seek.. Technical terms or basic principles to learn.

Thanks for help.

# Answer
Balance is mostly attained by intuition and play testing. Games where balance is important usually have extended beta cycles and frequent updates because of this. In your specific example "Magic" attains balance through years of experience in play balancing - if they find that they have released an unbalanced deck they might come up with a ruleset to address it.

Unfortunately I don't think you could really fit balance into any of the UML models - considering that UML is typically used to design transactional or architectural software you would have a hard time fitting the balance problem-set into it (and would likely be wasting a lot of your time).

One of the methods you might want to look into is "zero-sum balance". Basically each "thing" can exert so much "stuff" into the world given a certain amount of external factors. Taking the example of a strategy game you could do your initial balancing by saying that each unit must exert 300 damage points within 15 seconds. This way you can work out hit damage based on, say, attack speed. More complicated systems obviously have more variables and are likely impossible to calculate - so you have to need to guesstimate (intuition): any errors on your part can easily be fixed by releasing balancing patches.

Another option is to try to autonomously break your balance using AI and adjust to avoid that scenario: doing this would likely teach you a lot of the intuition involved in balancing.

If there was a simple way to ensure balance you wouldn't see Blizzard releasing patches for Starcraft, IceFrog wouldn't have been so famous because of his balancing prowess. It all comes down to testing and listening to your community: which are often rife with people who are very experienced with balance - especially if your game's subject matter manages to attract such a community.

One of the main reasons balance is hard because there is a lot of "ghost in the machine" (where a computer exhibits surprising behaviour) involved in games. For example, if you are using a dice-roll/random damage system the random number generator you are using could introduce balancing factors. Another problem is ingenuity: you might make some unit that can teleport and completely underestimate how important mobility is. Things like this simply can't be modelled at all.
> 3 votes

# Answer
There's a difference between documenting gameplay and making sure it is balanced. The latter is typically done through math (see for example: The Craft of Game Systems: Tuning RPG Content) and testing, the former (typically) by writing a design document. If you're familiar with UML, you'll also know that its main use is communicating a design, not validating it, or its implementation, through and through.

A universally applicable formal methodology hasn't yet cropped up, mainly because game design is a very organic process(\*). Keeping that fact in mind, one of the main ways to approach game design is *prototyping*, for example as described here: Casual Game Design - Building a prototype. Excerpt:

> **Advantages *\[of prototyping\]***
>
> * Find out if the game works.
> * Try out different ideas.
> * Balance game rules.
> * Ease communication.
> * Get feedback.
>
> **Kinds of prototypes**
>
> * Pencil and paper.
> * Board games.
> * Graphics program.
> * Program a prototype. *\[the game designers I know extensively use Unity for this purpose\]*

This seems a good way to go for designing a new game from the ground up, and will probably also work well for extending an existing game, like Magic: The Gathering. Although in that case a design team might already have a more formal process in place (e.g. to design an expansion pack, a type of unit, a specific card) given the fact there are set constraints to work with (e.g. previously released rule sets and expansion packs).

(\*) In the last backer's update for his Kickstarter project Tim Schafer made an interesting analogy about a game \[design\] being a painting created by paint drops falling in slow motion. They can be seen falling and moved about by the designer, but in the end they all have to fall down on the canvas at the same time to create the painting/game.
> 1 votes

---
Tags: methodology
---


# Question
Title: Learning C++ but wanting to develop iOS Apps
I'm a computer engineering student and taking my second programming class. I'm learning C++ using "C++ Primer Plus" 5th edition by Prata. I want to develop for iOS. I understand the main language for Xcode is Objective-C. Am I hurting myself by learning C++ before any other language (notably before my desired lang Objective-C)? There's got to be a reason the university requires C++ to learn as a basis language.

Please offer any helpful guidance or how I should go about this. Thanks//

# Answer
> 8 votes
## Am I hurting myself by learning C++ before...

No, C++ is a good way to learn about all the basics of programming, including Object Oriented programming, and memory management which might be handled for you in other languages.

**There's got to be a reason the university requires C++**

It is an industry standard across the world. It is quite portable as there are compilers and implementations for most platforms.

## notably before my desired lang Objective-C ?

Objective-C is contemporary of C++, they appeared around the same time and take different approaches when it comes to their Object Oriented paradigms. But they are both supersets of C and as such you can mix both.

## My experience

The fact is most games I worked on for mobile are C++ games with some C, Objective-C or Java providing native functions to C++ in the game code.

I actually worked on only one Objective-C game. The dev time was shorter, but the game is now stuck as an iPhone only product.

**Word**: Rest assured that C++ is definitely the best choice of language you could currently start with. It's not the simplest, there are fewer standard libraries, memory management without smart pointers seems harder... But in the end, once you understand C++, you can approach other languages with a better understanding of what they provide, do and what they hide from you.

---

**Another word**: As a programmer you should not stop at one language. You will have multiple opportunities to learn other languages and different approaches... Don't shy away from acquiring these little skills and seemingly uninteresting languages. They make all the difference when you are faced with new (and increasingly challenging) problems, like building leader board servers, web games, massively distributed databases and games...

---

**Note**: If you learn both C++ and Objective-C at the same time, the experience shouldn't be too confusing as they are not so similar and the first approach of iOS dev quickly goes into the high level UI APIs while C++ digs into more low level things.

You might end-up favoring Objective-C as it comes with great APIs on Mac/iOS, it has a *solid* (for lack of a better word) memory management system, garbage collection, etc. But remember that in games development C++ remains the most used language

C++ deserves a place in every programmer's heart, mainly now **there is much more to modern C++ than C with classes**.

# Answer
> 7 votes
You're not hurting yourself because you're doing what is required by your school. Learning to program is only partially about learning the syntax of a specific language (and it's a small part!). Right now you're learning to think logically and like a programmer. Don't worry about learning things you don't need, because it's all useful in some way.

# Answer
> 2 votes
`C++` is where almost every new programmer learn about `object-oriented designs` first (at least in my area, it's true). So you are not hurting yourself. Also you can develop `iOS` (even `Android` )apps in C++.
If you are thinking to go into `game-development`, C++ is the de-facto language here, supported by most of the `game-engines`. So learning C++ is always a win-win situation whichever path you choose.

# Answer
> 2 votes
Objective-C is but one of many languages you can learn to use for iOS programming. Not only are you completely free to write C and C++ code on iOS (with some caveats), Apple also supports a language called Objective-C++, which is exactly what it sounds like.

While you do not need to use Objective-C to program your core application, the Apple APIs are all exposed in Objective-C. However, this matters a lot less than you might think. Well designed, well architected programs do not generally rely a lot on platform APIs (some exceptions apply). If you do your job right as a programmer then porting your application to other platforms should require relatively little of your application's code to be rewritten. This is done with the arts of abstraction and encapsulation. As an example, one engine I have now has less than a dozen Objective-C files but close to a thousand C++ files.

Regarding the choice of C++ as a first language, you should consider yourself very lucky. Most schools start with much worse first languages. You are unlikely to find any school that teaches Objective-C outside of a course or two on iOS development, and there's a reason for that. Especially when it comes to developing large, complex applications like games, Objective-C has a lot of weaknesses (all the weaknesses of C combined with all the weakness of a dynamic language, in fact) compared to C++, and you're going to be far better off having a solid grasp of all the tools that C++ offers. Learning Objective-C on your own will be very easy after you get a decent grip on C++.

# Answer
> 1 votes
Also (in addition to the other answers posted), objective C is a layer on top of C and most of the code you will be writing is c and c++.

---
Tags: c++, objective-c, xcode
---


# Question
Title: What should I use (controls, methods) to make a 2D tile based map editor?
I'm making a 2d game where each tile is a square and it's viewed at straight angle, no skewing, no rotation, it's pretty simple.

Two weeks ago I tried using DataGridView, but as the number of rows and columns increased, it became frustratingly slow, then I read how it should've happened to me earlier, because this control is not supposed to work with large number of cells, and I have at least 7500 cells in my smallest level, which made it unbearable to use.

This is what I expect from my new editor: Most importantly, **tile type**. Tile images or their color codes are fine (seeing map as it is in-game is cool, but the faster, the better).

Secondly, all tile parameters (in text, preferrably editable in a popup or sidebar).

I'm using my own format, so I'm most probably not going to use third party product. Besides, I'm trying to learn how to do it myself.

# Answer
> 2 votes
I use a simple WinForm for a map's canvas and another form for tiles toolbox. No grid is necessary, the user just selects a tile and point-clicks on the canvas. Mouse coords are recalculated according to predefined grid dimensions, and one can easily paint/overwrite the map below the pointer. Another toolbox-form contains varoius objects to place over the map (can be used as a height map). These forms are placed inside a MDI container. It took less than an hour to create the editor, no special controls or DX methods are required, GDI+ works fine.

# Answer
> 1 votes
Why not use an existing tile editor? Tiled seems well supported.

# Answer
> 0 votes
A simple 3D engine should suffice, depending on your video card and various other factors it shouldn't be too much to expect that it can draw 100000 quads/tiles with no special optimization.

# Answer
> 0 votes
If you can play your levels, you can make the editor ingame...

it is not too difficult..

these are two samples one of my tiled games and its ingame editor

1st version ... http://www.youtube.com/watch?v=ZPHjpB-ErnM

3trd version playable... http://www.youtube.com/watch?v=4QDeY15Ox-g

other editor for non tiled game but ingame too...

http://www.youtube.com/watch?v=958eDY3S0No

---
Tags: c#, 2d, tiles, maps, map-editor
---


title: Full screen display mode

text:
# Question
Title: Full screen display mode
Could somebody point me to resources that would explain what full screen actually is?

What's the point of it? It seems to be more than just a window that has the client are taking the whole screen.

# Answer
> 2 votes
In the old days a fullscreen mode was sometimes also called an "exclusive mode". The clue here is in the name - such a mode has exclusive control of the screen and other video hardware; nothing else can use it. Because it doesn't need to share resources with other programs, and doesn't need to co-operate nicely with other programs, it can be somewhat more agressive in it's use of the hardware, which can result in higher performance. A windowed mode by comparison does have to play nice with other programs you may be running, so it doesn't get to take what may be more optimal paths in the driver.

How this manifests to your program depends on your API of choice. Under D3D you must explicitly select a fullscreen mode whereas OpenGL has no such concept (but presumably the driver is able to make some intelligent decisions during context creation time).

Some further info here from an SO question a while back: https://stackoverflow.com/questions/304669/why-direct3d-application-performs-better-in-full-screen-mode (with a slightly heavier focus on behaviour of the DWM in Windows Vista/7 than is necessary for this current question, but it's all relevant nonetheless).

# Answer
> 1 votes
There are several benefits of fullscreen:

* Full screen apps sometimes change the resolution (if possible) to a lower resolution, which means there aren't as many pixels to draw (and hence improves performance)
* Full screen applications can grab the mouse and use it for themselves (on platforms which have mice) - for example, FPS games normally use it to aim the gun.
* Historically, there were other performance benefits of using fullscreen mode, these are mostly nonexistent now.
* Full screen apps could historically use a different colour depth than the desktop, but this doesn't matter any more as everything is always true colour (maximum depth typically) now.

Fullscreen can also be used by non-game applications, typically embedded "kiosk" or information systems which have a single application "take over" the whole screen.

Note that using fullscreen mode for security (i.e. prevent access to desktop or other apps) is not a good idea and has historically been a security hole in many kiosk-type systems.

---
Tags: graphics, graphics-programming
---


# Question
Title: Issues glVertexAttribPointer last 2 parameters?
## Introduction

Hello I will start out by explaining my setup, showing samples as I go along explaining the situation.

---

I'm using these tools:

* OpenGL 3.3
* GLSL 330
* C++

---

## Problem

The problem is when I render the wavefront obj 3d model it gives a very weird visual glitch the model was supposed to be a square but instead its a triangluated mess with parts of the vertexes pointing in a stretched direction in massive amounts towards the bottom left side of the frustum....

## Explanation:

I'm using std::vectors to store my wavefront .obj model data using sscanf to get the floating point values into the structure members x,y,z and store them into the Points structure variable p;

```
int index = IndexAssigner(1, 1);
ifstream file (list[index].c_str() );
points.push_back(Point());
Point p;
int face[4];

while (!file.eof() ) {
    char  modelbuffer[10000];
    file.getline(modelbuffer, 10000);
    switch(modelbuffer[0]) {
        case 'v' :
        sscanf(modelbuffer, "v %f %f %f",  &p.x, &p.y, &p.z);
        points.push_back(p);
        break;
        case 'f':
        sscanf(modelbuffer, "f %d %d %d %d", face, face+1, face+2,  face+3 );
        faces.push_back(face[0]);
        faces.push_back(face[1]);
        faces.push_back(face[2]);
        faces.push_back(face[3]);
    }
    //Turn on FileReader aka "RENDER CODE"
    FileReader = true;
}

```

then I render the Points vector using the .data() member of std::vectors to the frustum.

Other declarations:

```
int numfloats = 4;
float* point=reinterpret_cast<float*>(&points[0]);
int num_bytes=numfloats*sizeof(float);

```

Vector declarations:

```
struct Point {float x,  y , z; };
std::vector<int>faces;
std::vector<Point>points;

```

Render code:

```
glGenBuffers(1, &vertexbuffer);
glGenTextures(1, &ModelTexture);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBindTexture(GL_TEXTURE_3D, ModelTexture);
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA,  ModelSurface->w, ModelSurface->h, 0, GL_BGR, GL_UNSIGNED_BYTE, ModelSurface->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBufferData(GL_ARRAY_BUFFER, sizeof(points), points.data(), GL_STATIC_DRAW);
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE,num_bytes ,points.data());
glEnableVertexAttribArray(3);

//Translation Process
GLfloat TranslationMatrix[] = {
        1.0, 0.0, 0.0, 0.0,
        0.0, 1.0, 0.0, 0.0,
        0.0, 0.0, 1.0, 1.0,
        0.0, 0.0, 0.0, 1.0
      };

//Send Translation Matrix up to the vertex shader
glUniformMatrix4fv(translation, 1, TRUE, TranslationMatrix);

glDrawElements( GL_QUADS, faces.size(), GL_UNSIGNED_INT,  faces.data());

```

I tried looking at what was causing this and went through every function every parameter ,etc looked at the man pages.

Then found out that it could be my glVertexAttribPointer.

*Here are the man pages for glVertexAttribPointer*

http://www.opengl.org/sdk/docs/man/xhtml/glVertexAttribPointer.xml

The last 2 parameters is my problem

*How do I write those 2 last parameters do I try putting the data from Points into it?.*

glVertexAttribPointer(3, 3, GL\_FLOAT, GL\_FALSE,num\_bytes ,points.data());

*How does it work with vectors?*

*Is it fast?**

if you can not be bothered too look at the man pages here is the scripts coming from the man pages directly.

## Stride

Specifies the byte offset between consecutive generic vertex attributes. If stride is 0, the generic vertex attributes are understood to be tightly packed in the array. The initial value is 0.

## Pointer

Specifies a pointer to the first component of the first generic vertex attribute in the array. The initial value is 0.

If you want my full source -\> http://ideone.com/fPfkg

Thanks Again if you do read this.

# Answer
The parameters in your case should both be 0, because you don't have stride (your `Point` structure is packed) and because your data starts at the beginning of the vertex buffer.

However, there is another problem: `sizeof(points)` will not return the size of the data, only the size of the base vector class: you need to use your `num_bytes` instead.

But your computation of `num_bytes` uses the size of `float`, not `Point`. This is a more correct way to compute it:

```
num_bytes = points.size() * sizeof(points[0]);

```

And you are mixing `GL_TEXTURE_3D` and `GL_TEXTURE_2D`.

Also your "render" code should be split. There is initialisation code, and per-frame code.

This is initialisation code; it needs only be done once:

```
glGenTextures(1, &ModelTexture);
glBindTexture(GL_TEXTURE_2D, ModelTexture);
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA,  ModelSurface->w, ModelSurface->h,
             0, GL_BGR, GL_UNSIGNED_BYTE, ModelSurface->pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, num_bytes, points.data(), GL_STATIC_DRAW);

```

And this is code that needs to be run each frame:

```
glBindTexture(GL_TEXTURE_2D, ModelTexture);

glEnableVertexAttribArray(3);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 0, 0);

```

Hope this helps you fix your code a bit.
> 2 votes

# Answer
Also, Wavefront .OBJ format specifies that the index of the first vertex is 1. In OpenGL, it is assumed to be 0. So you might want to decrement each int of your `faces` vector to get correct indices in your array buffer.

```
faces.push_back(face[0] - 1);
faces.push_back(face[1] - 1);
faces.push_back(face[2] - 1);
faces.push_back(face[3] - 1);

```
> 1 votes

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


title: Segment-Cylinder intersection

text:
# Question
Title: Segment-Cylinder intersection
What is the complete code (C#, pseudo, does not matter) for calculating the resulting segment (or its absence) for the intersection of asegment and a cylinder?

The segment is defined by `Vector3`(x,y,z) as **Start** and`Vector3`(x,y,z) as **End**.

The cylinder is defined by the same parameters plus a value for **Radius**.

# Answer
> 1 votes
**Mathematical explanation with readable symbols and LaTeX format** \- great for 1st or 2nd year undergrad students or skilled high-school people.

Well, if you need to understand the maths behind it rather than copy-pasting some code that might not be the good one (it's not clear whether it will work or not judging from the SO code). Here are the steps:

* It's easier to find the intersection points if the cylinder is aligned with the Z axis of your Oxyz frame.

Let *v = normalize(Cylinder.End - Cylinder.Start)*

Compute *w = cross(v, vec3(0,0,1))*. If *w*'s not the null vector, you have to perform a *T* transform for both Cylinder and Segment to align the scene with the oZ axis:

*T = Rotation(w, arccos(dot(v,z)) ) x Translation( - Cylinder.Start)* Use this transform to find the coordinates of the transformed Cylinder and Segment: *Cylinder2 = T x Cylinder1*, *Segment2 = T x Segment1*. For simplicity, I'll call the results Cylinder and Segment.

* Since the Cylinder is aligned with the Z axis, the equation of a point that lies on its surface is *x^2 + y^2 = r^2*, there's no constraint on the *z* component.

Let the equation of your segment be *(x0 + t(x1-x0), y0 + t(y1-y0), z0 + t(z1-z0))* where *Segment.Start(x0,y0,z0)* and *Segment.End(x1,y1,z1)*. For simplicity, let's forget about *v, w* and all those letters that were used until now and call *x1-x0 = u, y1-y0 = v, z1-z0 = w*.

That means that a POINT on the segment is written as *vec3(x0+tu, y0+tv, z0+tw)*, where *t* should be in the \[0,1\] interval! Remember the condition for a POINT to also lie ON the SURFACE of the Cylinder? Now we get:

-- *(x0+tu)^2 + (y0 + tv)^2 = r^2* which is equivalent to

-- *(u^2 + v^2)t^2 + 2(u x0 + v y0)t + x0^2 + y0^2 - r^2 = 0.*

Let *A = (u^2 +v^2), B= 2(u x0 + v y0)t, C= x0^2 + y0^2 -r^2*. You end up with a quadratic equation. *Delta = B^2 - 4AC*.

* Discussion:

If *Delta \<0* you have no intersection.

If *Delta = 0*, the segment is tangent to the cylinder.

If *Delta \> 0*, you solving for *t* gives you *t1* and *t2*.

Plug *t1* and *t2* in the POINT ON SEGMENT equation and get your P1 and P2 points that are CANDIDATES.

Remember, *t1* and *t2* must be between \[0 and 1\] in order for P1 and P2 to be points on your segment. If one of them is outside \[0,1\], it means your segment has an endpoint inside the cylinder. If both *t1,t2* are outside \[0,1\], the supporting LINE of the segment intersects the cylinder, but not your segment.

One last checkup, P1.z and P2.z should be between 0 and Cylinder.End.Z, because you work with *finite* cylinders.

Wrap-up: you have to plug in your *t1*, *t2* values in the INITIAL SEGMENT equation to recover the intersection points. That's it, I don't have the time to sum it up in a C# snippet, but I hope you understand what to do.

---
Tags: geometry, computational-geometry, intersection
---


# Question
Title: Open GL Android frame-by-frame animation tutorial/example code
My first question was asked wrong, so I need to ask again :)

I found out, that I will have to do an OpenGL animation for my Android game. The closest (known) example is Talking Tom (but I don't know how they did the animations).

I have large PNGs which I would like to put into a animation. For example - 30 PNGs 427×240px at 8 FPS.

I know some things already about Open GL, but I am used to learn from example code. And it is quicker that way (so I don't need to invent hot water all over again :)). Does anybody has any points to direct me?

# Answer
> 1 votes
All you have to do is set the correct frame of the animation based on the time since starting the animation. You could try to simply switch the texture, but in order to get better performance you would usually put all frames in one texture and shift the UV coordinates to each frame.

If you wish to learn from some code, I would suggest taking a look at the libgdx source code here. It may also be better for you to simply use that library to handle the graphics for your game.

---
Tags: java, android, animation, opengl-es
---